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 | ||
|
|
f5155baddd | ||
|
|
24f342adfe | ||
|
|
1954192a8c | ||
|
|
50e812321f | ||
|
|
14d1f4d2bd | ||
|
|
20b002a518 | ||
|
|
6667a491e8 | ||
|
|
8dd649952c | ||
|
|
8dff9e380c | ||
|
|
611ea9e2dd | ||
|
|
1b35dc4c8e | ||
|
|
40536ee77e | ||
|
|
08af9b6aa8 | ||
|
|
35bf28a14f | ||
|
|
992428e6d8 | ||
|
|
5945b5a538 | ||
|
|
128f08c3f4 | ||
|
|
e4f02657f8 | ||
|
|
4412039f53 | ||
|
|
0fff3d8e06 | ||
|
|
e0736ac6a0 | ||
|
|
45e2917073 | ||
|
|
00920b222f | ||
|
|
35bfdd6166 | ||
|
|
fe35d24530 | ||
|
|
8e820e2e90 | ||
|
|
8652055ed2 | ||
|
|
462b86213c | ||
|
|
e51618a9bc | ||
|
|
e471f80b52 | ||
|
|
d48684c848 | ||
|
|
80f2712c05 | ||
|
|
6629497fd1 | ||
|
|
6a056e3a8c | ||
|
|
16f18aff33 | ||
|
|
bed3864d31 | ||
|
|
ecec030cf8 | ||
|
|
dc2ab47d84 | ||
|
|
2c97ae1b55 | ||
|
|
3a6a14e265 | ||
|
|
28c591b9b3 | ||
|
|
66481def88 | ||
|
|
ed34596a0c | ||
|
|
a0946f962a | ||
|
|
b2dfe474e2 | ||
|
|
19b9e0fd6e | ||
|
|
13260e3927 | ||
|
|
f68ad40378 | ||
|
|
0581b222c0 | ||
|
|
948938a647 | ||
|
|
fdd25f7b31 | ||
|
|
61e864a7b1 | ||
|
|
1c4c3f2c63 | ||
|
|
b4686ea4af | ||
|
|
2859f5b9b0 | ||
|
|
193c9f36b3 |
No files matched your search
+110
@@ -55,6 +55,15 @@ Always pass `root`. Node ids and `source_file` values are derived relative to it
|
||||
|
||||
## Extraction output schema
|
||||
|
||||
Terraform/HCL per-file AST results record the scope used to mint their node IDs.
|
||||
After a cache hit, extraction consumes that scope to rewrite node IDs and edge
|
||||
endpoints relative to the current scan root, including when the cache was copied
|
||||
from another checkout. Module-source topology is still resolved against the
|
||||
current permitted corpus. The scope marker is internal and is not exported in
|
||||
the graph. AST cache schema 33 retires entries without this marker; the semantic
|
||||
cache is unchanged. Existing graphs with stale absolute Terraform IDs need a full
|
||||
code rebuild: `graphify extract . --code-only --force`.
|
||||
|
||||
Every extractor returns:
|
||||
|
||||
```json
|
||||
@@ -70,6 +79,35 @@ Every extractor returns:
|
||||
|
||||
`validate.py` enforces this schema before `build()` consumes it.
|
||||
|
||||
Validation reports list/object enum values as schema errors. Graph assembly
|
||||
repairs structured `file_type` values to `concept` and structured `confidence`
|
||||
values to `INFERRED`, without fabricating a confidence score, so malformed
|
||||
semantic fields cannot abort an otherwise usable build.
|
||||
|
||||
JS/TS calls through default imports of directly default-exported object literals reuse existing static method nodes.
|
||||
Members match the imported module path, exact label and source line. Lexically shadowed receivers, constructor calls,
|
||||
spread, computed keys, accessors, duplicate keys and dynamic aliases are not inferred. These files bypass the per-file
|
||||
AST cache, so resolving these cross-file calls does not require an AST cache schema bump.
|
||||
|
||||
|
||||
## Semantic provenance during file-node folding
|
||||
|
||||
`build_from_json()` normally folds an evidence-free semantic mention of a
|
||||
filename into its unique AST file-self node (Pass 2b, #3344); references to
|
||||
that mention are rewired to the AST node. A cross-source semantic record that
|
||||
contains its own `rationale`, source URL, author/contributor, capture time,
|
||||
or metadata is **not** a disposable mention: a label-only fold would discard
|
||||
its explanation or attribution. Such records remain separate even when their
|
||||
label matches a unique AST file node. This is intentionally conservative:
|
||||
a richly annotated mention may remain distinct until an explicit
|
||||
provenance-preserving merge is available. The saved-semantic-node shrink guard
|
||||
uses the same rule and still rejects any unexplained loss. Same-source AST/semantic twins that are evidence-free keep their
|
||||
existing exact-path merge rule (#4389/#4391), but an independently evidenced
|
||||
semantic YAML/document record is retained across a later AST extractor
|
||||
upgrade. If AST disambiguation path-qualifies a file-node label, the shrink
|
||||
guard accounts for a plain same-source fold using the exact source identity
|
||||
instead of accepting a mere basename collision.
|
||||
|
||||
## Edge direction in graph.json
|
||||
|
||||
`graph.json` is written `"directed": false`, but every link is directed: **arc order is the direction** (`source` → `target`, #563). Older canonicalized files carry it in `_src`/`_tgt` markers instead, and those win where present (#2309).
|
||||
@@ -84,6 +122,22 @@ A plain `json_graph.node_link_graph()` load loses this: an undirected graph re-o
|
||||
| `INFERRED` | Relationship is a reasonable deduction (e.g., call-graph second pass, co-occurrence in context) |
|
||||
| `AMBIGUOUS` | Relationship is uncertain; flagged for human review in GRAPH_REPORT.md |
|
||||
|
||||
Go member calls, including same-file calls, resolve through declared receiver types and
|
||||
carry `INFERRED` confidence. Bare calls to package-level functions remain `EXTRACTED`;
|
||||
unknown or ambiguous receivers do not bind by method name alone. AST cache schema 37
|
||||
retires Go entries created before these receiver-binding rules.
|
||||
|
||||
C++ member chains such as `client.actions->Execute()` use lexical local/parameter
|
||||
bindings and class-scoped field declarations, including fields in unchanged headers.
|
||||
Raw pointers and single-type-argument `std::unique_ptr<T>` / `std::shared_ptr<T>`
|
||||
receivers are supported; `.` does not unwrap a smart pointer. Resolved instance
|
||||
calls are `INFERRED` static-type relationships, not proof of runtime dispatch.
|
||||
Unknown/shadowed types, ambiguous class identities, unresolved aliases, custom
|
||||
pointer wrappers, containers, and computed receivers are not guessed. AST cache
|
||||
schema 41 retires entries without receiver chains and persistent class fields.
|
||||
Rebuild existing graphs with `graphify extract . --code-only --force` to populate
|
||||
unchanged headers before relying on changed-file-only updates.
|
||||
|
||||
## Adding a new language extractor
|
||||
|
||||
1. Add an `extract_<lang>(path: Path) -> dict` function following the existing pattern (tree-sitter parse → walk nodes → collect `nodes` and `edges` → call-graph second pass for INFERRED `calls` edges). New languages go in their own module under `graphify/extractors/` - see `graphify/extractors/MIGRATION.md`; `extract.py` re-exports them while the existing ones are ported out of it.
|
||||
@@ -92,6 +146,14 @@ A plain `json_graph.node_link_graph()` load loses this: an undirected graph re-o
|
||||
4. Add the tree-sitter package to `pyproject.toml` dependencies.
|
||||
5. Add a fixture file to `tests/fixtures/` and tests to `tests/test_languages.py`.
|
||||
|
||||
## Search hook scope
|
||||
|
||||
The search hook omits project hints when a structured Grep path or every literal
|
||||
target of a simple grep/rg command resolves outside the project. Mixed targets,
|
||||
implicit paths, shell composition/expansion, wrappers, unknown options and
|
||||
unmapped Windows shell drive paths retain the advisory hint. It does not execute
|
||||
shell input or change search permissions.
|
||||
|
||||
## Security
|
||||
|
||||
All external input passes through `graphify/security.py` before use:
|
||||
@@ -134,6 +196,15 @@ ambiguous return references emit no inferred call. Resulting call edges remain
|
||||
as resolver context. Changes to a producer's return annotation require a full
|
||||
rebuild to recompute unchanged callers' inferred relationships.
|
||||
|
||||
Python direct module-level constructor assignments (`g = Service()`) retain the
|
||||
class for member-call resolution inside functions, including an imported alias
|
||||
or a lowercase class rebound to its instance. The constructor must be declared
|
||||
or imported before the assignment and resolve to a unique visible class by exact
|
||||
spelling. Local shadowing, other module bindings, conditional assignments and
|
||||
dynamic namespace mutation leave these calls unresolved. Qualified constructors
|
||||
and decorated classes are not inferred by this pass. Edges remain `INFERRED`;
|
||||
AST cache schema 37 retires Python entries without the instance marker.
|
||||
|
||||
C# partial types merge across files by their path inside the namespace,
|
||||
enclosing types first and each with its arity (`` Outer`1.Inner ``), within one
|
||||
assembly. Nested halves merge only under the same enclosing chain, and `Foo` and
|
||||
@@ -142,8 +213,47 @@ lack this path. The merge runs after colliding ids are salted apart by path, so
|
||||
a half whose file stem collides with another file's (`Spec.cs` and `_Spec.cs`,
|
||||
`Cfg/Helpers.cs` and `Cfg_Helpers.cs`) still merges and keeps its members.
|
||||
|
||||
C# constructors (instance, static and a type's primary constructor) are nodes
|
||||
owned by their type through a `method` edge, labeled `.TypeName()` with
|
||||
metadata `kind: "constructor"`. The id is the one a method named after the type
|
||||
would get, `_make_id(type_id, TypeName)`; each further signature is salted like
|
||||
a method overload, a static constructor is its own `static` signature, and when
|
||||
a member spelled like the type in another case (`foo()` in `Foo`) already owns
|
||||
that id, the constructor takes a salted one, so no existing id moves. Calls in
|
||||
a constructor's body and `: base(...)`/`: this(...)` arguments are its calls.
|
||||
`new X(...)` keeps its edge to the type and also links the constructor whose
|
||||
parameter count fits, as do `: base(...)`/`: this(...)`; two fitting overloads,
|
||||
an unresolved base or an unbound type give no constructor edge. Constructors
|
||||
stay out of every name-keyed call index. AST cache schema 40 retires C# entries
|
||||
without them.
|
||||
|
||||
C# property and indexer accessor bodies (and expression bodies) are walked
|
||||
with the member as the caller, and the member counts as owned by its type for
|
||||
unqualified, `this.`/`base.` and partial-type lookups, like a method. It is never
|
||||
a call target by name. An indexer is a `this[]` node (`defines`, context
|
||||
`field`) with id `_make_id(type_id, "this")`, salted per signature and away
|
||||
from a member spelled `This`. A user-defined operator or conversion is a
|
||||
`.operator +()` / `.operator int()` node owned through `method`, with id
|
||||
`_make_id(type_id, "operator", sha1(signature)[:6])`, since several conversions
|
||||
share one parameter list. Existing ids do not move. AST cache schema 40.
|
||||
|
||||
R extraction preserves symbol-only bindings such as `%||%` as separate nodes.
|
||||
When normal ID normalization removes an entire binding name, its UTF-8 bytes
|
||||
provide a deterministic operator suffix within the same lexical owner. Its double
|
||||
underscore separators cannot collide with an ordinary normalized binding ID. Local
|
||||
call resolution stops if malformed scope metadata cycles.
|
||||
|
||||
### Same-ID AST / semantic provenance during extractor upgrades (#4896)
|
||||
|
||||
A newly supported AST extractor can mint an ID that is already owned by an
|
||||
independently evidenced semantic node in a saved graph, even when the two nodes
|
||||
refer to the same file. Watch reconciliation retains the saved semantic ID and
|
||||
its rationale/attribution, assigns the fresh AST record a deterministic
|
||||
ID-derived AST suffix, and rewrites only fresh AST edge/hyperedge
|
||||
references. This applies to full and incremental re-extractions; incrementally
|
||||
rebuilt sources are not positive evidence of semantic deletion. The shrink
|
||||
guard refuses same-ID losses of semantic provenance even when the total node
|
||||
count grows, preventing the ordinary missing-ID guard from being bypassed.
|
||||
If multiple new AST records already share that ID, all use one deterministic
|
||||
AST successor ID: this retains their preexisting AST coalescing behavior while
|
||||
ensuring they cannot overwrite independent semantic provenance.
|
||||
+168
@@ -2,6 +2,174 @@
|
||||
|
||||
Full release notes with details on each version: [GitHub Releases](https://github.com/Graphify-Labs/graphify/releases)
|
||||
|
||||
## 0.9.105 (2026-11-09)
|
||||
|
||||
- Fix: **watch** ignored directories (`node_modules`, `.git`, build output) are pruned from the Linux watch tree, so a large project no longer registers tens of thousands of wasted inotify watches and risks `ENOSPC`; the non-Linux recursive watcher is unchanged and still fires on every real change (#5074, #5091, thanks @Deepjyoti-Sarmah).
|
||||
- Fix: **cpp** a member-call chain routed through class fields declared in other headers (`client.actions->Execute()`, with value `.`, raw-pointer `->` and single-arg `unique_ptr`/`shared_ptr` receivers) resolves to the field type's member across the include set, gated to a unique type and member and fail-closed otherwise; a typed local whose class is in another repo is parked for the cross-repo merge (#5098, thanks @xRedLeader).
|
||||
- Fix: **markdown** a code span naming an uppercase `\`-namespace class (`\Foo\Bar`, `App\API`) or a type-qualified method call (`Type::member()`) is kept as a symbol mention instead of being dropped, while a non-call `Type::CONST`/`Type::class` stays dropped (#5093, thanks @Adityakk9031).
|
||||
- Fix: **ts/js** a call through a destructured CommonJS barrel require (`const { Thing } = require('./barrel')` where the barrel re-exports `Thing`) resolves to the real declaration by following the barrel's exports, instead of dropping the edge (#5034, #5104, thanks @qq2514568380).
|
||||
- Fix: **wiki** the orphan sweep folds slugs with `casefold` (not `lower`), so two article names that collide only under full Unicode case-folding (`Straße`/`STRASSE`, `Σ`/`ς`) each keep their own file instead of one being deleted as an orphan; a file written this run is never swept (#5087, #5102, thanks @nothariharan).
|
||||
- Fix: **build** hyperedges are kept whole across an incremental `graphify update`: they are read from the nested graph slot a JSON-only writer uses, and after a deleted-source prune a hyperedge drops only its removed members (and itself only when none remain), instead of silently losing or leaving dangling hyperedges (#5081, #5103, thanks @nothariharan).
|
||||
- Fix: **cache** a degraded (under-producing) semantic cache entry no longer pins the corpus: after the shrink guard sees a re-extraction come back smaller than the stored graph, the entry is stamped `partial` so the next run re-dispatches it instead of replaying the degraded result forever (#5083, #5101, thanks @nothariharan).
|
||||
- Fix: **affected** `graphify affected <file>` seeds the file's nested member nodes (a method inside a class) transitively, not just one hop, so impact analysis no longer under-reports callers that bind to a nested member (#5094, thanks @Adityakk9031).
|
||||
- Fix: **tree** `build_tree` derives the common directory root from file parents, so a single-file or single-directory tree is no longer self-nested under the file itself (#5092, thanks @Adityakk9031).
|
||||
- Fix: **query** a label whose name is behind a schema or namespace qualifier (`public.sweep_widget_state()`, `fmt.Println`) is matched on its tail by the whole query and ranked above the per-token tiers, so it is no longer out-competed by single-token collision nodes and dropped from the seeds (#5080, #5095, thanks @sunhouy).
|
||||
- Fix: **detect** an incremental staleness check hashes a file whose stamp lands within the clock-skew window on either side of its mtime, so a same-tick rewrite that does not move mtime is still caught instead of being served stale (#5090, thanks @sunhouy).
|
||||
- Fix: **path** `graphify path A B` refuses an endpoint whose words appear nowhere in the graph (exit not-found) instead of returning a misleading route built from loosely-overlapping tokens (#5085, thanks @sunhouy).
|
||||
|
||||
- Fix: **csharp** a classic extension-method call (`x.Foo()` where `Foo` is declared `static ... Foo(this X x, ...)`) binds to the extension method's declaration through an additive pass that runs after nominal dispatch, gated to a visible namespace, a matching `this` type and a unique applicable method; an instance method of the same name wins, a non-extension static or an unimported extension gets no edge, and ambiguity fails closed (#4828, #4849, thanks @Deepjyoti-Sarmah).
|
||||
- Fix: **markdown** a bare, unqualified free-function mention in prose (`token`, no `()` and no namespace) binds to a same-named function only when its defining file (or another symbol from it) is cited within the heading's section chain, instead of matching any same-named callable in the corpus; reference-style links (`[text][label]`) resolve at the use site (#4804, #4806, thanks @madanlalit).
|
||||
- Fix: **export** the `to_json` shrink guard no longer counts semantic sources that were replaced on re-extract or pruned as deletions as "lost", so a legitimate `graphify update` is not refused; a genuine unexplained shrink is still refused (#5107, thanks @khkar).
|
||||
- Fix: **build** a node whose `file_type` or `confidence` arrives as a structured value (list/dict) from a drifting LLM pass no longer crashes the validate/build membership checks: validation surfaces it as a schema error, and the build folds it to `concept`/`INFERRED` without fabricating a score (#5088, thanks @sdivyanshu90).
|
||||
- Fix: **llm** a splittable document below the character cap whose model output truncates is promoted to a full-range slice and bisected (and retried) instead of being kept as a truncated partial result; a non-splittable or code/binary unit still fails closed (#5072, #5078, thanks @aadilrizwan).
|
||||
- Feat: **llm** a custom OpenAI-compatible provider's `extra_headers` are forwarded to the client as `default_headers`, scoped to that provider and with any `Authorization` header dropped so it cannot override the configured credential (#3680, #4783, thanks @jaimemartinez).
|
||||
- Perf: **extract** whole-graph intermediates (the parse memo on the one-shot CLI, build/cluster/export working lists) are freed as soon as they are consumed, cutting peak memory on a large corpus; graph output is byte-identical (#5063, thanks @TPAteeq).
|
||||
- Fix: **skillgen** the claw/kiro/pi subagent prompt now tells the worker to write its chunk to `CHUNK_PATH`, so a disk-dispatch chunk is no longer returned inline and lost at the merge step (#5040, thanks @connhodendatabase).
|
||||
- Fix: **deps** the pypdf floor is raised to 6.21.4 in the `pdf` and `all` extras to pick up its security fixes (#5015, thanks @yotamleo).
|
||||
|
||||
The AST cache schema is bumped to 42; warm caches re-run the affected C++, Markdown and C# extractions.
|
||||
|
||||
## 0.9.104 (2026-11-07)
|
||||
|
||||
- Security: **skill** the `/graphify` runbook no longer substitutes the scan path into Python code. Every generated code block (detect, AST and semantic extraction, build, diagnose, label, manifest, and `--update`) now reads the resolved scan root from the trusted `graphify-out/.graphify_root` sidecar that Step 1 writes through a quoted heredoc, instead of pasting the agent-supplied path into a string literal. A directory whose name carried a quote or `$(...)` could previously break out of `Path('INPUT_PATH')` and run as code; it is now read as inert data. Covers the assembled hosts and the Aider/Devin monoliths (#4762, thanks @danikdanik).
|
||||
- Fix: **solidity** a call on a receiver of a contract or interface type (`IERC20 token; token.transfer()`, `IERC20(a).transfer()`, `token().balanceOf()`) binds by name and arity through that type's linearization to the type's own declaration, instead of producing no edge; gated to a single visible contract/interface and fail-closed on an unknown or ambiguous type (#5060, thanks @rohit-jsfreaky).
|
||||
- Fix: **solidity** a call attached by a `using A for T` directive (`using SafeCast for uint256; x.toUint48()`) binds to the library or free function it attaches, matched by the receiver's type and an arity one greater than the call; fail-closed when the receiver type is unknown, the library is ambiguous, or two functions fit (#5062, thanks @rohit-jsfreaky).
|
||||
- Fix: **solidity** members, free functions and types in one scope whose names differ only by a leading `_` or by case (`_grantRole` / `grantRole`) get separate node ids, so the `_` symbol no longer vanishes into its twin and its calls land on the right node (#5027, thanks @rohit-jsfreaky).
|
||||
- Fix: **csharp** a constructor (instance, static or primary) is its own node owned by its type, with its body and `: base(...)`/`: this(...)` calls credited to it; `new X(...)`, `: base(...)` and `: this(...)` additively link the arity-correct overload, and two fitting overloads or an unresolved base give no constructor edge (#5054, thanks @rohit-jsfreaky).
|
||||
- Fix: **csharp** calls inside a property or indexer accessor, an expression body, or an operator/conversion body are credited to that member instead of being lost; an indexer becomes a `this[]` node and an operator a `.operator +()` node (#5056, thanks @rohit-jsfreaky).
|
||||
- Fix: **query** a same-label node that is the only match for a query term is kept as a seed instead of being dropped by the per-label cap, so every distinct term keeps at least one seed while generic-label flooding stays capped (#5027, thanks @Vaibhav2824).
|
||||
- Fix: **watch** read-only events are kept out of the inotify mask via a change-only `event_filter`, so a large tree no longer drives watchdog into a self-sustaining queue-overflow loop; falls back with a warning on watchdog versions without `event_filter` support (#5033, thanks @Deepjyoti-Sarmah).
|
||||
- Fix: **cache** the `\\?\` long-path spelling is kept out of cache identity, so the same file reached through `\\?\C:\...` and `C:\...` shares one entry; also fixes empty stat-index writes under UNC shares, a spurious "stat index switched" warning on Windows, and a junction/symlink alias wrongly sharing its target's digest (#5035, thanks @Bortlesboat).
|
||||
- Fix: **cache** stat-index keys stay root-relative under a Windows long-path root, so a moved or cloned corpus keeps the portable-key fastpath (#5035, thanks @Vaibhav2824).
|
||||
- Fix: **tests** the TypeScript unicode fixture is written as UTF-8 on every platform, so byte offsets match the extractor on Windows (cp1252) hosts (#5064, thanks @ayushcodes10).
|
||||
- Fix: **tests** the hook-freshness source mock is normalized through `os_long_path`, so the read-error/stale branch is actually exercised on Windows (#5065, thanks @ayushcodes10).
|
||||
- Fix: **tests** the watch pending-queue test compares `Path` objects so `/` and `\` separators compare equal on Windows (#5039, thanks @Yi-111-a).
|
||||
- Fix: **extract** an ambiguous Python import's placeholder node id is hashed from checkout-independent data (module name, scan-root-relative source file, location) instead of the absolute path, so the same project at a different path or a moved cache gets the same ids (#5045, thanks @Fardin7798).
|
||||
- Fix: **yaml** a template using CloudFormation intrinsic tags (`!Ref`, `!GetAtt`, `!Sub`) no longer fails to parse: a scoped permissive loader rebuilds each `!`-tagged node's shape without evaluating it, while `!!python/...` tags still raise and never execute (#5077, thanks @ayushcodes10).
|
||||
- Fix: **watch** a `--watch` incremental update rebuilds the full corpus when `graph.json` is missing, instead of writing a partial graph from the manifest alone (#5016, #5021, thanks @azizur100389).
|
||||
- Fix: **watch** a change to a JS/TS resolution input (`tsconfig.json`, `jsconfig.json`, a lockfile) triggers a full rebuild so importers pick up the new resolution, instead of leaving stale `imports_from` edges (#5017, #5022, thanks @azizur100389).
|
||||
- Fix: **ingest** two concurrent `graphify add` captures for the same URL no longer clobber each other: the capture file is created exclusively (`O_EXCL`) and a collision retries a fresh name, with the payload fetched once (#5018, #5023, thanks @azizur100389).
|
||||
- Fix: **reflect** a malformed entry in the learning overlay is skipped instead of crashing the whole load, and a legacy null-source entry is preserved as a source-less annotation (#5019, #5024, thanks @azizur100389).
|
||||
- Fix: **global** a malformed repo entry in the global manifest is dropped on its own, keeping the other tracked repos, and only a non-object root or repos map is backed up and reset (#5020, #5025, thanks @azizur100389).
|
||||
- Fix: **query** a graph freshly built on a subfolder is no longer flagged as a pre-#1504 build (which nagged a no-op `extract --force`): the legacy-id probe strips the `.graphify_root` offset before deriving file stems, and a genuine legacy graph is still caught (#2603, #5028, thanks @neumannpeter1231-lang).
|
||||
- Fix: **tree** `graphify export tree` recognises the `src` node alias (and `file`/`path`/`filepath`) so a graph carrying those keys renders a populated tree instead of an empty one; a concept-only graph still reports empty (#5030, thanks @Adityakk9031).
|
||||
- Fix: **cli** `graphify provider add` accepts `--pricing-input=VALUE`/`--pricing-output=VALUE` equals-syntax and rejects a non-numeric, non-finite or negative price with a clean error instead of a traceback or a poisoned cost estimate (#5031, thanks @Adityakk9031).
|
||||
|
||||
The AST cache schema is bumped to 40; warm caches re-run the affected Solidity and C# extractions. The Python and YAML fixes above need no bump (placeholder ids are resolved after the per-file cache, and previously-failing YAML was never cached).
|
||||
|
||||
## 0.9.103 (2026-11-05)
|
||||
|
||||
- Fix: **markdown** a code span written as a backslash namespace (`\Foo\Bar`) or a type-qualified member (`Type::member`) is recognised as a symbol mention and resolves to the real node when one exists, instead of being silently dropped; an absent chain mints nothing (#4610, #4695, thanks @viwe-monai).
|
||||
- Fix: **detect** `extract` warns loudly when a large share of the corpus has no supported extractor (a 20-file floor and a 20% threshold), instead of only printing a bare unclassified count; a normal mixed project stays silent (#2942, #4646, thanks @ayushcodes10).
|
||||
- Fix: **thread-safety** the ambient scan root is held in a `ContextVar` instead of a module global, so concurrent library/async callers extracting different roots no longer clobber each other's root; the single-threaded CLI is unchanged (#4602, #4694, thanks @WyattAu).
|
||||
- Feat: **tree** `graphify export tree` caps how many children a directory lists (`--max-children`, default 200) while `total_count` still reports the full count, so a directory with thousands of entries no longer renders them all (#4766, #4768, thanks @oleksii-tumanov).
|
||||
- Fix: **install** the Pi project skill is written to `.pi/skills`, where Pi reads it, instead of a `.pi/agent/skills` path it never looks at; uninstall is symmetric (#5011, #5012, thanks @Vivek1898).
|
||||
- Internal: stage fake install bundles in a temp package root and fail loudly (not skip) on a wheel-build error, and serialise both wheel builders under a shared lock so concurrent runs on one checkout do not collide (#4603, #4664, thanks @wanjinhao1); characterize `_is_stale` across changed/unchanged/vanished sources (#4996, thanks @PratikDhanave); isolate the ambient venv/PATH in the `_detect_run` hook test (#4991, thanks @HhH666-ux).
|
||||
|
||||
- Fix: **solidity** a library call (`Lib.f()`, including an aliased import) and an `emit`/`revert`/`require` naming a declared event or error now link to the member they name instead of producing no edge; resolution is gated to a single visible type whose unique name/arity member matches, so a builtin `require` or an ambiguous qualifier is left unresolved (#5001, #5005, thanks @rohit-jsfreaky).
|
||||
- Fix: **csharp** preprocessor directives and `#if` branches that derail tree-sitter are blanked before parsing (byte-length preserving, so line and column numbers do not move), so a directive no longer closes the enclosing class early and orphans later members or drops their calls; the first `#if` branch and distinct framework-fallback branches are kept (#5003, thanks @rohit-jsfreaky).
|
||||
- Fix: **python** a bare builtin-named call (`raise NotImplementedError(...)`, `list(...)`) no longer binds to a same-named class in another module unless that caller imported the symbol; an imported homonym still resolves (#4989, #4999, thanks @Deepjyoti-Sarmah).
|
||||
- Fix: **typescript** a type-position `import('mod')` expression (a parameter/alias/`typeof`/generic-constraint annotation) no longer emits a spurious `dynamic_import` runtime edge; a real runtime `import('mod')` in the same file still does (#4992, #4998, thanks @mathewgeejo).
|
||||
- Fix: **resolution** a call inside a top-level `def _main()` is attributed to `_main`, not the public `main` it collides with after id normalization; the fix matches only the underscore-collision salt, so a class member's type reference is not misattributed to a sibling method (#4994, #4997, thanks @sunhouy).
|
||||
- Fix: **yaml** a `<<` merge sequence gives the earlier anchor precedence for a duplicated key, matching the YAML merge spec and PyYAML, so the winning key carries its correct source line (#4995, thanks @PratikDhanave).
|
||||
- Fix: **markdown** a dotted mention whose method name is a language builtin (`Repository.open`) is no longer dropped; only a bare builtin name is skipped, and no spurious mention is minted (#4990, thanks @PratikDhanave).
|
||||
- Fix: **hooks** a Bash file read (`cat`, `head`, `tail`, `sed -n`, `nl`) of an in-project code file gets the same graph read-nudge a Read tool does (nudge-only, never a strict deny); writes, stdin, heredocs, docs and globs stay silent (#5010, thanks @rohit-jsfreaky).
|
||||
- Fix: **hooks** the once-per-session nudge budget is restored after a Claude Code compaction (a `SessionStart` with `source=compact`), so orientation can re-fire once the earlier nudges have left the model's context (#5008, thanks @rohit-jsfreaky).
|
||||
- Fix: **hooks** the toplevel-anchor logic keeps working when `CDPATH` is exported; an exported `CDPATH` was corrupting the relative `.git` capture and silently skipping the post-commit/checkout rebuild (#4977, #4988, thanks @HhH666-ux).
|
||||
- Perf: **update** the watch reconcile pass resolves AST ownership once per file instead of re-reading each header once per node, with identical graph output (#4978, #4986, thanks @Deepjyoti-Sarmah).
|
||||
- **AST cache schema bumped to 39** for the C# (#5003), Solidity (#5001, #5005), YAML (#4995) and Markdown (#4695) extractor fixes; warm caches re-run the affected extractions.
|
||||
|
||||
## 0.9.102 (2026-11-03)
|
||||
|
||||
- Perf: **update** `graphify update` re-extracts only the files whose content changed since the last build (derived from the manifest inside the lock), instead of re-running the whole pipeline over the corpus for a single edit; the resulting graph is identical to a full rebuild, including cross-file edges from unchanged files into a changed one, and deletions (#4740, #4800, #4801, thanks @Deepjyoti-Sarmah).
|
||||
- Fix: **watch** a contended incremental rebuild request is recorded on its own queue marker instead of being dropped, so a derived-change request that loses the rebuild lock still runs on the next pass (#4800, #4802, thanks @Deepjyoti-Sarmah).
|
||||
- Fix: **query** source nodes are ranked above tests, docs and config in query results (a soft weight, not exclusion, so a term matched only by a test still seeds it and a question mentioning "tests" restores full weight), and the answer is rendered file-first (#4982, thanks @rohit-jsfreaky).
|
||||
- Feat: **query** `graphify query` reads project `query_budget` and `query_depth` defaults from `.graphifyrc` (explicit CLI flags still win), and gains a `--depth N` flag; a malformed setting warns and falls back to the built-in defaults (#1654, #4760, thanks @oleksii-tumanov).
|
||||
- Fix: **install** `graphify uninstall` removes the global `# graphify` skill registration it wrote into `~/.claude/CLAUDE.md`, instead of leaving a dangling pointer to the deleted skill; a hand-written `# graphify` section or another tool's registration is preserved (#4975, thanks @madhusudanpatnaik).
|
||||
- Fix: **js** a class `extends` through a CommonJS require binding (`const Base = require('./base'); class D extends Base {}`) resolves the `inherits` edge to the required file's class, matching the ESM import path; an external/unresolved require is left alone (#4688, #4700, thanks @Mpasha17).
|
||||
- Fix: **skill** the `--update` runbook passes `partial_source_files` to the manifest write and clears a stale `.graphify_partial.txt` at the start of the run, so a doc whose chunk was only partly read is re-queued on the next update instead of being stamped done forever (#4807, #4814, #4816, thanks @gitmotion).
|
||||
- Fix: **skill** Step 4 threads `force=IS_FORCE` into `to_json`, so a `--force` rebuild actually overwrites past the #479 shrink guard the runbook told the user to use `--force` for (#4777, #4805, thanks @pei711).
|
||||
- Feat: **skill** for a hub/bridge question, the query workflow now tells the agent to grep the corpus for the hub's distinctive literals in edge-less files and report code that reimplements the hub instead of calling it (#4426, #4704, thanks @ayushcodes10).
|
||||
- Fix: **hooks** a file whose mtime is newer than `graph.json` but whose content is unchanged no longer weakens the strict read gate; the hook checks the file's extraction hash against the build manifest before declaring it stale, so a checkout that writes `graph.json` first does not force a re-read (#4974, thanks @andrebrait).
|
||||
- Fix: **hooks** a dedicated Grep call is held to the same once-per-session orientation gate as Read in strict mode; a directory Grep needs no index match, a single-file Grep is denied only when the graph indexes it, and external or graph-output targets stay silent without consuming the deny (#4973, thanks @andrebrait).
|
||||
- Fix: **hooks** a search whose every literal target is outside the project (a Bash `grep`/`rg` on a `/tmp` or sibling path) emits no project hint, so the graph nudge only fires for in-project searches (#4961, #4979, thanks @Shubham-Padkonde).
|
||||
- Perf: **load** `graph.json` rows are released as the graph is built (and repeated strings interned) so a load no longer holds both the parsed rows and the finished graph at peak, with identical output (#4960, thanks @ajbmachon).
|
||||
- Perf: **resolve** symbol resolution holds one parsed file at a time instead of retaining every parsed file across the JS and Python passes, collapsing them into a single per-file loop with unchanged edges (#4958, thanks @ajbmachon).
|
||||
- Perf: **extract** edge-dedup keys and per-file rows are released once consumed, cutting peak retention during extraction with identical output (#4959, thanks @ajbmachon).
|
||||
- Fix: **typescript** a typed tagged template (`` sql<{...}[]>`...` ``) and an import-qualified generic annotation (`import("mod").T<X>`) no longer leave the file half-parsed; the recovery runs only on files that already fail to parse, so a type-only `import("mod").T` stops minting a bogus module node and a false `dynamic_import` edge (#4976, thanks @briascoi).
|
||||
- Fix: **go** a same-file member call resolves through the receiver's type instead of a declaration-order-dependent same-named method; a bare package-function call no longer binds to a same-named method, and a package-level `var` fallback only applies to a genuinely unbound receiver (#4962, #4966, thanks @xiongjianxu).
|
||||
- Fix: **go** a member call on a receiver typed from another package (`pkg.T`, the usual shape of a dependency injected across packages) binds only to the `T` declared at the path the file imports `pkg` from, so two packages that both declare `T` are disambiguated by import evidence; an out-of-corpus qualifier stays unresolved (#3368, #4853, thanks @nothariharan).
|
||||
- Feat: **go** an interface method call additively dispatches to the interface's implicit implementers (method-set superset match, unexported methods scoped to the same directory, capped at 10 implementers and skipped past that), surfacing the concrete methods a call can reach while keeping the edge to the interface (#4934, thanks @nothariharan).
|
||||
- Fix: **kotlin** a call to an overloaded method resolves (Java gives every overload one node id, which the resolver mis-counted as ambiguous), calls inside an `init {}` block are attributed to the class, and a bare call no longer binds to a class the caller cannot reach through its type chain (#4935, #4956, thanks @Deepjyoti-Sarmah).
|
||||
- Fix: **python** a module-level singleton (`g = Service()` then `g.method()`) resolves its member calls through the instance's type, gated by an exact-spelling and lexical-shadow guard so rebinding, local shadowing or an ambiguous constructor leaves it unresolved (#4970, #4972, thanks @Shubham-Padkonde).
|
||||
- Fix: **js** a call through a default-exported object's method (`import m from './x'; m.foo()`) resolves to the static method, bound only on a single unambiguous target and suppressed by local shadowing, getters, spread or computed keys (#4963, #4967, thanks @xiongjianxu).
|
||||
- Fix: **solidity** an `import "../x/Y.sol"` resolves the `..` to the real file instead of a dangling id that kept the importer's own folder (#4984, #4985, thanks @rohit-jsfreaky).
|
||||
- Fix: **build** the write guard no longer counts an intentional ghost fold (a #1145 same-file twin, #3344 doc-names-a-file, or #3705 method ghost folded into its surviving twin) as a dropped node on the `build_merge` path; a genuine drop whose survivor is also gone is still refused (#4955, #4957, thanks @Deepjyoti-Sarmah).
|
||||
- Fix: **extract** paths skipped by ignore rules are reported in the extract summary (bounded, sorted, root-relative, with a VCS-aware hint), surfacing the already-collected ignore list without changing the graph (#4965, #4969, thanks @xiongjianxu).
|
||||
- Perf: **resolution** the #3252 cross-file repoint indexes edges by source file instead of scanning every corpus edge per importing file, cutting resolution time on large graphs with no change to the resulting edges (#4980, #4981, thanks @jinsoo).
|
||||
- Fix: **python** a bare builtin name (`NotImplementedError`, `TimeoutError`, `ConnectionError`, …) no longer links to a package class of the same name when the calling module never imports it; the edge is kept (and stays EXTRACTED) only when the caller imports that exact symbol, so a module-level import of some other name from the same file can no longer certify it (#4989).
|
||||
- **AST cache schema bumped to 37** for the Go (#4966, #4853, #4934), Kotlin (#4956), Python (#4972) and Solidity (#4985) extractor fixes; warm caches re-run the affected extractions.
|
||||
|
||||
## 0.9.101 (2026-11-02)
|
||||
|
||||
- Fix: **watch** AST-only updates preserve cross-file semantic evidence whose node id collides with a code definition. Semantic nodes and their document-owned links use the existing citing-file namespace, keeping both the code definition and semantic provenance in `graph.json`, including with `--no-cluster`. Fresh AST facts remain authoritative for same-source ids; full-build deduplication is unchanged.
|
||||
- Fix: **python** a bare call inside a method (`do_thing()`) no longer wrongly self-binds to a same-named method on the class; it resolves to the imported or module-level function it actually names, and a bare call with no such target emits no edge (#4933, thanks @nothariharan).
|
||||
- Fix: **python** imports resolve across PEP 420 namespace packages split over multiple `src/` roots (no `__init__.py`), while a module ambiguously provided by two roots stays unresolved and loose/stdlib-named modules are left alone (#4929, thanks @nothariharan).
|
||||
- Fix: **go** a method value reached through a receiver field (`m.UseMiddleware(hs.handler.Middleware)`) is linked as an `indirect_call`, extending the method-value-as-argument handling to field chains rooted at the method's own receiver (#1566, #4931, thanks @nothariharan).
|
||||
- Fix: **go** a package-level `var` initialiser references the types it names (`var s = wire.NewSet(new(T), ...)`, composite literals, `new(T)`), the type-reference complement to crediting its calls to the file, so a wire-set file no longer extracts as no symbols (#2360, #4932, thanks @nothariharan).
|
||||
- Fix: **rust** a module-qualified call (`crate::b::helper()`, `super::m::f()`) resolves to the function it names through qualifier-verified cross-file resolution, the dominant idiomatic call form that previously produced no edge; the resolver keeps the call inside the caller's crate and will not bind to a local name, preserving the historical false-positive guards (#2135, #4944, thanks @nothariharan).
|
||||
- Fix: **rust** a call written inside an expression macro's arguments (`println!("{}", f())`, `vec![g()]`) is linked instead of being lost, gated to an allowlist of expression macros so `macro_rules!` bodies and custom DSLs are left alone, and a normally parsed call still wins the dedupe (#4945, thanks @nothariharan).
|
||||
- Fix: **llm** a sliced file is cached only once every slice has succeeded, and a held sliced file is assembled in chunk order rather than completion order, so a partial failure no longer leaves a truncated or out-of-order file in the semantic cache; failed slices are stamped for retry (#4943, #4947, thanks @nothariharan).
|
||||
- Fix: **rebuild** a graph built with `--code-only` stays code-only across hook, `update` and watch rebuilds; the scope is recorded in `.graphify_build.json`, honoured by the rebuild path and the no-change skip key, and a later flagless extract that actually ingests docs clears the scope (#4923, #4939, thanks @Deepjyoti-Sarmah).
|
||||
- Fix: **watch** a rebuild no longer waits forever when `msvcrt.locking` is unsupported on the filesystem; an unexpected errno is treated as lock-unsupported and the rebuild proceeds unlocked with a warning, matching the existing no-`fcntl`/no-`msvcrt` fallback, while genuine contention still retries (#4924, #4926, thanks @AndresDiagoM).
|
||||
- Fix: **watch** a full reconcile evicts source records for a linked git worktree that the current ignore rules exclude, including sources owned only through an edge or hyperedge, so a worktree copy's nodes no longer linger after it is excluded; an intentionally scanned linked root and live unexplained sources are preserved (#4919, thanks @azizur100389).
|
||||
- Fix: **cache** cache keys keep their written case so `README.md` and `readme.md` no longer collide on a case-sensitive filesystem, and hashed and word-count files are opened through `os_long_path` so a path folded by `normcase` can no longer raise `IsADirectoryError`; the digest salt is no longer lowercased, which also closes a latent same-digest collision on POSIX (#4925, #4937, thanks @Deepjyoti-Sarmah).
|
||||
- Fix: **build** the write guard no longer refuses a healthy graph when entity dedup folds a saved node into a surviving twin; the dedup merge map is carried on the built graph and threaded into both the missing-node check and the net-count check, which now counts N saved ids folded into one survivor as the expected N-1 shrink, while a genuine loss (survivor also absent) is still refused (#4940, #4952, thanks @Deepjyoti-Sarmah).
|
||||
- Fix: **build** independently sourced semantic file evidence survives a fold into an AST file-self node; a mention carrying its own provenance (`rationale`, `source_url`, `author`, `contributor`) is kept distinct instead of collapsing by label alone, so two docs describing the same file no longer lose one explanation. Ordinary `INFERRED` mention ghosts with only `metadata`/`captured_at` still fold, so graphs do not accumulate duplicates (#4896, #4927, thanks @Ethan-Ethan-Ethan).
|
||||
- Fix: **build** the file-stem alias index only rebinds an edge onto a migrated node when the edge's file and the alias target share a language family, so a reference in one language (for example Dart) no longer binds onto an unrelated same-stemmed file in another (for example Java); same-language and provenance-less aliases resolve exactly as before (#4949, thanks @ayushcodes10).
|
||||
- Fix: **cpp** a type-alias reference (`using Foo = Bar;` then `Foo x;`) binds by exact spelling, so it no longer loses to a same-normalized function of the same name, and a salted alias node keeps its own `contains` edge (#4951, thanks @madhusudanpatnaik).
|
||||
- Fix: **cpp** a member call `x.m()` binds by the receiver's type, now typed from function parameters and class fields and not only local variables (`void render(Base* b){ b->draw(); }` resolves to `Base::draw`), the dominant idiom of passing state by reference; an untyped or ambiguous receiver keeps its in-file binding rather than guessing (#3215, #4946, thanks @nothariharan).
|
||||
- Fix: **cpp** an out-of-line or split-header definition attaches to the unique owner whose class file is in its include set, carried by a `_cpp_qualified` identity marker, instead of being file-contained or cross-binding to an unrelated same-named function in another file; an ambiguous or namespace-colliding owner fails closed with no edge (#4916, #4920, thanks @azizur100389).
|
||||
- Fix: **cpp** a local callable value (a lambda or `std::function` assigned to a variable) is kept out of global call resolution by byte-range binding lifetimes, so it no longer mints a spurious `INFERRED` call to a same-named global; a later legitimate call to a real global of that name in the same function is preserved (#4917, #4921, thanks @azizur100389).
|
||||
- Internal: cover deletion-only semantic manifest preservation so an undispatched semantic stamp survives a deletion-only or failed incremental change (#4922, thanks @azizur100389).
|
||||
- **AST cache schema bumped to 36** for the Rust call-resolution fixes (#4944, #4945), the case-preserving cache keys (#4937), and the C++ extractor fixes (#4951, #4946, #4920, #4921); warm caches re-run the affected extractions.
|
||||
|
||||
## 0.9.100 (2026-11-01)
|
||||
|
||||
- Fix: **ids** a type and a function whose names differ only in case (`Foo` the class, `foo` the function) get distinct node ids instead of colliding (which dropped one node and minted a bogus self-loop) (#4904, #4908, thanks @bercedev).
|
||||
- Fix: **php** a `Scope::MEMBER` access in a class-level initializer (a const value, a property default, or a parameter/promoted-constructor default) emits a `references_constant` edge; `self::`/`static::`/`parent::` are skipped and unknown scopes mint no stub (#4648, #4895, thanks @Jitendarmahara).
|
||||
- Fix: **hooks** `git rev-parse` output is decoded as UTF-8, so a linked worktree under a non-ASCII path resolves correctly on Windows instead of mojibake (#4903, thanks @LukeTheoJohnson).
|
||||
- Fix: **analyze** on a code-only graph the isolated-node question reason says "possible missing edges" rather than referencing documentation gaps that cannot apply (#4887, thanks @oleksii-tumanov).
|
||||
- Perf: **resolve** reference edges are indexed by source once, so JS/TS import resolution no longer re-walks every edge per import (output unchanged) (#4909, #4913, thanks @Deepjyoti-Sarmah).
|
||||
- Docs: **skill** the skill now says when a graph is worth building, across all generated hosts, while preserving the "if the user invoked /graphify, do it as asked" invariant (#4829, #4906, thanks @TanmayShah29).
|
||||
- Fix: **deps** the `video` extra caps PyAV below 19 (`av>=11,<19`), because PyAV 19 removed the `metadata_errors` argument that faster-whisper passes unconditionally when opening audio; without the cap a fresh install on Python 3.12+ failed to transcribe (#4842, thanks @SyedFahad7).
|
||||
- Fix: **r** `setClass`/`setRefClass` S4/R5 inheritance declared with `contains=` now emits an inherits edge (previously only R6Class's `inherit=` was recognised) (#4902, thanks @ayushcodes10).
|
||||
- Fix: **elixir** a bare function call resolves to a function in the caller's own module before other modules, instead of binding to the last-walked same-named definition (#4900, thanks @ayushcodes10).
|
||||
- Fix: **dart** a mixin `on A, B` clause resolves every superclass constraint, not just the first (#4899, thanks @ayushcodes10).
|
||||
- Fix: **fortran** a derived type's `extends(base)` emits an inherits edge, bringing Fortran in line with the other OOP extractors (#4897, thanks @ayushcodes10).
|
||||
- Fix: **scala** an `extension (x: T) def m` is scoped to its receiver type `T` (a `method` edge to `T`) instead of leaking to file scope (#2044, #4856, thanks @divakantpandey).
|
||||
- Fix: **terraform** a node carries its original scope so ids stay stable when a cached project directory is moved, instead of re-deriving the scope from the new path (#4858, #4861, thanks @yUm1k4).
|
||||
- Fix: **extract (JVM)** Java and Kotlin imports, `extends`/`implements` and member calls resolve across files and across the two languages when a written FQN names exactly one sourced type (#4874, #4879, thanks @Deepjyoti-Sarmah).
|
||||
- Fix: **export** a path/explain/wiki rendering lists every parallel relation between two nodes (via `edge_datas`), and a raw `--no-cluster` write marks the graph `multigraph` so parallel edges survive reload (#4794, thanks @ensell-yes).
|
||||
- Fix: **export** a partial or failed backup is reported as no backup and retried on the next run, instead of being recorded as a false success (#3769, #4834, thanks @barlowa124).
|
||||
- Fix: **affected** `graphify affected` (and `query --seed`) resolve the same `path::Symbol` and dotted reference forms `explain` accepts, reusing explain's resolver, and exit non-zero (3 ambiguous / 4 not-found) on a seed that does not resolve (#4792, #4797, thanks @dupeisen).
|
||||
- Fix: **install** `graphify uninstall` removes every platform's user-scope skill (13 were left behind) and the kilo global command; and `graphify kilo uninstall` removes the kilo skill's `references/` sidecar (#4782, #4789, thanks @bercedev).
|
||||
- Feat: **llm** the Claude backend caches its (stable, large) system prompt with `cache_control`, counting the cached tokens back into `input_tokens`, and `GRAPHIFY_CLAUDE_PROMPT_CACHE=0` disables it for gateways that reject `cache_control` (#4835, #4855, #4880, thanks @Jvxoq and @1akashkalita).
|
||||
- Fix: **prompt** the node-id format description in the extraction prompt matches what `ids.py` actually produces (word characters kept, non-ASCII letters/digits preserved, ASCII lowercased) instead of the stale "`[a-z0-9_]` only" wording (#4432, #4799, thanks @dupeisen).
|
||||
- Docs: **how-it-works** the supported-language count is updated (about 40: 33 tree-sitter grammars plus 7 built-in parsers) and Pass 3 is described as running the configured LLM backend, not Claude only (#4873, thanks @SyedFahad7).
|
||||
|
||||
## 0.9.99 (2026-10-30)
|
||||
|
||||
- Feat: **path** when several routes tie on length, `graphify path` and the MCP `shortest_path` tool report the most conservative one: among all shortest paths, the route whose weakest hop is weakest is chosen, and the summary notes it was the weakest of N equal-length routes. Previously an arbitrary equal-length route was returned, so the confidence could overstate how sure the connection is. This is the second half of #4881 (the first half, keeping a collapsed edge's weaker evidence in `also_seen`, shipped in 0.9.98 via #4891, thanks @SyedFahad7).
|
||||
- Fix: **go** a call in a package-level `var` initialiser (including inside a func-literal closure, the common swappable-hook pattern) is credited to the file node instead of being dropped (#2360, #4867, thanks @nothariharan).
|
||||
- Fix: **go** a method value passed as a function argument (`Wrap(s.Health)`) is linked as an `indirect_call`, bringing Go to parity with Python/JS for callback-by-method-value; conservatively guarded against field-access false positives (#1566, #4868, thanks @nothariharan).
|
||||
- Fix: **go** a receiver's field whose struct is declared in a sibling file of the same package is typed, so its member calls resolve across the usual struct-here-methods-there Go layout, and the field types persist across incremental rebuilds (#3368, #4866, thanks @nothariharan).
|
||||
- Fix: **python** `module.func` values listed in a dispatch table (`{"a": mod.func_a}`, including nested collections) resolve to the referenced functions as `indirect_call`s instead of being dropped; non-callable, class, and local-receiver values are left alone (#1566, #4773, thanks @nothariharan).
|
||||
- Fix: **install** gemini gets its own global skill dir (`~/.gemini/skills/graphify`) on Windows instead of colliding with the `agents` platform's dir; a pre-existing `agents` skill is noted, not deleted (#2800, #4770, thanks @nothariharan).
|
||||
- Fix: **install** the global OpenCode plugin is written to `~/.config/opencode` (co-located with the global skill) instead of the current directory, with install/uninstall/refresh kept symmetric and legacy locations still cleaned up (#3398, #4771, thanks @nothariharan).
|
||||
- Docs: **skill** the "Follow these steps in order. Do not skip steps." instruction is reworded to "unless the fast path above applies," resolving the contradiction with the existing-graph fast path across all generated hosts (#4061, #4721, thanks @nothariharan).
|
||||
- Feat: **serve** `path`, `explain` and `neighbors`/`get_neighbors` print an edge's stored `confidence_score` alongside its tag (`[INFERRED 0.75]`); EXTRACTED stays bare (1.0 by definition) and a missing or non-finite score keeps the bare tag. Composes with the weakest-hop path summary and the `also_seen` evidence tags (#4882, #4888, thanks @SyedFahad7).
|
||||
|
||||
## 0.9.98 (2026-10-30)
|
||||
|
||||
- Fix: **build** when duplicate same-relation edges collapse, the losing (weaker-confidence) copy's provenance is kept in an `also_seen` list on the surviving edge instead of being discarded, so the weaker evidence is not silently lost; the field is serialized to graph.json and is idempotent across rebuilds (#4881, #4891, thanks @SyedFahad7).
|
||||
|
||||
@@ -253,7 +253,9 @@ Codex users also need `multi_agent = true` under `[features]` in `~/.codex/confi
|
||||
|
||||
`--platform agents` (alias `--platform skills`) targets the generic cross-framework [Agent-Skills](https://github.com/anthropics/skills) locations: the spec's user-global `~/.agents/skills/` (read by `npx skills` and spec-compliant frameworks) for a global install, and `./.agents/skills/` for a project (`--project`) install. The bare `graphify install` stays single-platform (Claude Code) by design: use the named `agents` platform when you want the skill discoverable by any framework that reads `.agents/skills`.
|
||||
|
||||
Pi has no `PreToolUse` hook, so `graphify pi guard install` registers a native Pi extension (via Pi's own `pi install <package directory>`) that runs the installed `graphify hook-guard` before Pi's `read`, `grep`, `find` and search-style `bash` calls. Fresh/stale graph decisions and the `GRAPHIFY_HOOK_STRICT=1` once-per-session indexed-read denial come from that same policy, so Pi matches Claude Code's hook behavior; guidance arrives as a `<system-reminder source="graphify">` steering message. It needs Pi 0.58.4 or newer: earlier versions let a steering message skip the rest of a parallel tool-call batch. The package ships inside the Graphify installation, so install Graphify persistently (`uv tool install graphifyy` or `pipx install graphifyy`, not `uvx`), restart Pi after installing or upgrading, and remove it with `graphify pi guard uninstall`. Only local file targets are inspected; the hook needs `graphify` on an absolute `PATH` entry outside the project, is bounded to a two-second, 256 KiB-in/64 KiB-out call, and fails open. The same package also loads in [Oh My Pi](https://github.com/can1357/oh-my-pi): `omp plugin install "$(graphify pi guard path)"`. The registered path contains the Python version and venv, so re-run `graphify pi guard install` after changing either, and remove the old entry with `pi remove <old path>`.
|
||||
Claude Code's `graphify install --project --strict` makes Read and dedicated Grep share one denial per session unless a recent graph query has oriented the agent (default 30 minutes). A Grep over a directory needs no indexed-file match; a Grep pinned to a single file is denied only when the graph indexes that file, as with Read. External and graph-output Grep targets produce neither a deny nor a nudge, in soft mode as well as strict mode, matching Read's scope. A graph marked `needs_update` never triggers a Grep denial. Bash searches and Glob stay advisory. `GRAPHIFY_HOOK_STRICT=1` enables the policy without reinstalling; `GRAPHIFY_HOOK_STRICT=0` disables it even when installed with `--strict`. Existing strict installs need a reinstall to add the search hook's `--strict` flag, or the environment override. Soft nudges are capped per session (`GRAPHIFY_HOOK_NUDGE_CAP`, default 5). After a context compaction, a `SessionStart` hook (matcher `compact`) resets that budget, the subagents' budgets and the strict denial, since the compacted context no longer holds the earlier nudges.
|
||||
|
||||
Pi has no `PreToolUse` hook, so `graphify pi guard install` registers a native Pi extension (via Pi's own `pi install <package directory>`) that runs the installed `graphify hook-guard` before Pi's `read`, `grep`, `find` and search-style `bash` calls. Fresh/stale graph decisions and the `GRAPHIFY_HOOK_STRICT=1` once-per-session denial shared by indexed Read and dedicated Grep come from that same policy, so Pi matches Claude Code's hook behavior; Bash and file listing remain advisory. Guidance arrives as a `<system-reminder source="graphify">` steering message. It needs Pi 0.58.4 or newer: earlier versions let a steering message skip the rest of a parallel tool-call batch. The package ships inside the Graphify installation, so install Graphify persistently (`uv tool install graphifyy` or `pipx install graphifyy`, not `uvx`), restart Pi after installing or upgrading, and remove it with `graphify pi guard uninstall`. Only local file targets are inspected; the hook needs `graphify` on an absolute `PATH` entry outside the project, is bounded to a two-second, 256 KiB-in/64 KiB-out call, and fails open. The same package also loads in [Oh My Pi](https://github.com/can1357/oh-my-pi): `omp plugin install "$(graphify pi guard path)"`. The registered path contains the Python version and venv, so re-run `graphify pi guard install` after changing either, and remove the old entry with `pi remove <old path>`.
|
||||
|
||||
> Codex uses `$graphify` instead of `/graphify`.
|
||||
|
||||
@@ -303,7 +305,7 @@ Run `graphify <platform> install` once in your project, for example `graphify cl
|
||||
|
||||
This writes a small config file that tells your assistant to consult the knowledge graph for codebase questions, preferring scoped queries like `graphify query "<question>"` over reading the full report or grepping raw files.
|
||||
|
||||
- **Hook platforms** (Claude Code, Gemini CLI): a hook fires automatically before search-style tool calls (and, on Claude Code, before reading source files one by one via the Read/Glob tools) and nudges your assistant toward the graph path.
|
||||
- **Hook platforms** (Claude Code, Gemini CLI): a hook fires automatically before search-style tool calls (and, on Claude Code, before reading source files one by one via the Read/Glob tools, or via `cat`, `head`, `tail`, `sed -n` and similar readers in Bash) and nudges your assistant toward the graph path.
|
||||
- **Instruction-file platforms** (Codex, OpenCode, Cursor, etc.): persistent instruction files (`AGENTS.md`, `.cursor/rules/`, etc.) provide the same query-first guidance.
|
||||
|
||||
`GRAPH_REPORT.md` is still available for broad architecture review.
|
||||
@@ -385,6 +387,12 @@ See the [full command reference](#full-command-reference) below.
|
||||
|
||||
graphify honors `.gitignore` and supports `--exclude` patterns and a project `.graphifyignore`. Details: **[Configuration](https://docs.graphify.com/reference/configuration)**.
|
||||
|
||||
`graphify extract` reports paths skipped by ignore rules, with up to three sorted examples relative to
|
||||
the scan root. Each pruned directory counts once; its contents are not enumerated. Default noise
|
||||
directories such as `node_modules` are excluded from this summary. If source is missing, review the
|
||||
ignore rules. `--no-gitignore` bypasses VCS ignore rules only; `.graphifyignore` and `--exclude`
|
||||
remain effective.
|
||||
|
||||
|
||||
## Project configuration
|
||||
|
||||
@@ -404,6 +412,20 @@ viz_node_limit=0
|
||||
|
||||
The declaration flows through classification, extractor selection, grammar and resolution, imports, `graphify watch`, and the AST cache (a file re-parsed under a different language never reuses the old entry), and the same `.graphifyrc` is read by `extract`, `update`, the hooks, the MCP server, and the `/graphify` skill. A typo is reported once on stderr and the scan continues with the defaults. How declarations interact with caching, incremental rebuilds, and import resolution: **[Configuration](https://docs.graphify.com/reference/configuration)**.
|
||||
|
||||
|
||||
**Query defaults.** Set `query_budget` to a positive integer and `query_depth` to an integer from 1 to 6:
|
||||
|
||||
```ini
|
||||
query_budget=4000
|
||||
query_depth=3
|
||||
```
|
||||
|
||||
For `graphify query`, explicit `--budget N` / `--budget=N` and `--depth N` / `--depth=N` override these settings independently. Without a project setting or explicit option, the defaults remain budget 2000 and depth 2. These keys do not change the MCP server's defaults.
|
||||
|
||||
Settings come from the project owning the selected `--graph`, even when the command runs from another directory. An existing absolute directory in the graph's sibling `.graphify_root` marker identifies that project. Otherwise a matching relative `GRAPHIFY_OUT` suffix identifies it; absolute, empty, traversal-containing or nonmatching output paths fall back to the graph file's directory. Relative markers are ignored.
|
||||
|
||||
The query command always reads that project's `.graphifyrc`. An invalid recognized setting or an unreadable file produces one stderr warning and discards all project settings for that query; explicit options still apply. The settings parser stays strict for its other callers. Existing explicit budget values retain their behavior; persisted `query_budget` values must be positive.
|
||||
|
||||
---
|
||||
|
||||
## Team setup
|
||||
@@ -422,6 +444,7 @@ Beyond your AI assistant, query `graph.json` straight from the CLI with `graphif
|
||||
|
||||
Backends, API keys, hook behavior, and tuning are controlled by environment variables. Full table: **[Configuration](https://docs.graphify.com/reference/configuration)**.
|
||||
|
||||
- **Claude API prompt caching**: `GRAPHIFY_CLAUDE_PROMPT_CACHE` controls system-prompt caching for `--backend claude`. Unset or blank keeps caching enabled; `1`, `true`, `yes`, or `on` explicitly enables it, and `0`, `false`, `no`, or `off` disables it (case-insensitive, surrounding whitespace ignored). Invalid values raise an error before sending a request. For example, run `GRAPHIFY_CLAUDE_PROMPT_CACHE=0 graphify extract . --backend claude` when an Anthropic-compatible endpoint rejects `cache_control`. Disabling sends the original plain-text system prompt. The setting applies equally to official Anthropic and custom `ANTHROPIC_BASE_URL` / `ANTHROPIC_MODEL` endpoints, including deep mode; it does not affect Bedrock, Claude CLI, or Graphify's local extraction cache. Enabling requests caching but cannot guarantee cache hits: the endpoint/model must support it and the prompt must meet its minimum length. Unsupported caching errors are not silently retried without caching.
|
||||
- **Claude CLI model**: `GRAPHIFY_CLAUDE_CLI_MODEL` overrides the model for the `claude-cli` backend (default: Opus). `haiku` or `sonnet` are usually enough for community naming; the semantic extraction pass benefits from a larger model.
|
||||
|
||||
---
|
||||
|
||||
+1
-1
@@ -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. |
|
||||
|
||||
@@ -5,15 +5,15 @@
|
||||
graphify processes your files in three passes:
|
||||
|
||||
**Pass 1 — Code structure (free, no API calls)**
|
||||
Tree-sitter parses your code files and extracts classes, functions, imports, call graphs, and inline comments. This runs locally with no LLM involved. 25 languages supported. SQL files get special treatment: tables, views, foreign keys, and JOIN relationships are extracted deterministically.
|
||||
Tree-sitter parses your code files and extracts classes, functions, imports, call graphs, and inline comments. This runs locally with no LLM involved. About 40 languages are supported: 33 are parsed with tree-sitter grammars and 7 (Dart, Apex, COBOL, Razor, Blade, Pascal and Robot Framework) use built-in parsers. A few languages need an optional extra, e.g. `pip install "graphifyy[sql]"`; graphify tells you which extra to install if one is missing. SQL files get special treatment: tables, views, foreign keys, and JOIN relationships are extracted deterministically.
|
||||
|
||||
Code files are not sent to the LLM semantic extractor in the normal pipeline. If a corpus contains only code files, Pass 3 is skipped entirely; semantic extraction is reserved for docs, papers, images, and transcripts.
|
||||
|
||||
**Pass 2 — Video and audio (local, no API calls)**
|
||||
Video and audio files are transcribed with faster-whisper. To focus the transcript on your domain, the transcription prompt is seeded with your top god nodes (the most-connected concepts in your code graph so far). Transcripts are cached — re-runs skip already-processed files.
|
||||
|
||||
**Pass 3 — Docs, papers, images (Claude subagents, costs tokens)**
|
||||
Claude runs in parallel over markdown, PDFs, images, and transcripts. Each subagent reads a batch of files and outputs a JSON fragment: nodes, edges, and any group relationships. The fragments are merged into a single graph.
|
||||
**Pass 3 — Docs, papers, images (LLM subagents, costs tokens)**
|
||||
Your assistant's subagents (or, with `graphify extract --backend`, a model such as Gemini, Kimi, OpenAI, DeepSeek or a local Ollama model) run in parallel over markdown, PDFs, images, and transcripts. Each subagent reads a batch of files and outputs a JSON fragment: nodes, edges, and any group relationships. The fragments are merged into a single graph.
|
||||
|
||||
Before Pass 3, optional converters turn supported pointer/binary formats into
|
||||
Markdown sidecars under `graphify-out/converted/`. Office files (`.docx`,
|
||||
@@ -27,7 +27,7 @@ Markdown sidecars under `graphify-out/converted/`. Office files (`.docx`,
|
||||
|
||||
Communities are found using the [Leiden algorithm](https://www.nature.com/articles/s41598-019-41695-z) — a graph-clustering method that groups nodes by edge density. Nodes with many connections between them end up in the same community.
|
||||
|
||||
**No embeddings needed.** The semantic similarity edges that Claude extracts (`semantically_similar_to`) are already in the graph, so they influence community shape directly. The graph structure is the similarity signal — there's no separate embedding step or vector database.
|
||||
**No embeddings needed.** The semantic similarity edges that the model extracts (`semantically_similar_to`) are already in the graph, so they influence community shape directly. The graph structure is the similarity signal — there's no separate embedding step or vector database.
|
||||
|
||||
---
|
||||
|
||||
@@ -38,7 +38,7 @@ Every relationship is tagged with one of three labels:
|
||||
| Tag | Meaning |
|
||||
|-----|---------|
|
||||
| `EXTRACTED` | Found directly in the source (e.g. a function call, an import) |
|
||||
| `INFERRED` | A reasonable inference Claude made, with a `confidence_score` (0.0–1.0) |
|
||||
| `INFERRED` | A reasonable inference the model made, with a `confidence_score` (0.0–1.0) |
|
||||
| `AMBIGUOUS` | Uncertain — flagged in the report for manual review |
|
||||
|
||||
EXTRACTED edges always have confidence 1.0. INFERRED edges use a discrete rubric:
|
||||
@@ -70,7 +70,7 @@ Each `worked/` folder in the repo has the raw input files and actual output (`GR
|
||||
|
||||
## Parallel extraction
|
||||
|
||||
Code files are extracted in parallel using `ProcessPoolExecutor` — bypasses Python's GIL for genuine multiprocessing. Doc/paper/image batches are dispatched as parallel Claude subagents. On a corpus of 84 code files, parallel AST extraction runs in about 1.66x less time than sequential.
|
||||
Code files are extracted in parallel using `ProcessPoolExecutor` — bypasses Python's GIL for genuine multiprocessing. Doc/paper/image batches are dispatched as parallel LLM subagents. On a corpus of 84 code files, parallel AST extraction runs in about 1.66x less time than sequential.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+19
-4
@@ -122,6 +122,7 @@ from graphify.install import ( # noqa: E402,F401
|
||||
_OPENCODE_PLUGIN_HEADER,
|
||||
_drop_opencode_config_entry,
|
||||
_opencode_config_names_plugin,
|
||||
_opencode_dir,
|
||||
_opencode_plugin_is_v1_only,
|
||||
_PLATFORM_CONFIG,
|
||||
_skill_lock,
|
||||
@@ -429,12 +430,21 @@ def _refresh_v1_opencode_plugins() -> None:
|
||||
if os.environ.get("GRAPHIFY_NO_AUTO_REFRESH", "").strip().lower() in ("1", "true", "yes"):
|
||||
return
|
||||
try:
|
||||
directories = dict.fromkeys(d.resolve() for d in (Path.cwd(), Path.home()))
|
||||
# The cwd and home .opencode dirs are where installs before #3398 wrote,
|
||||
# ~/.config/opencode is the global install's dir since.
|
||||
directories = dict.fromkeys(
|
||||
d.resolve()
|
||||
for d in (
|
||||
_opencode_dir(project=True, project_dir=Path.cwd()),
|
||||
_opencode_dir(project=True, project_dir=Path.home()),
|
||||
_opencode_dir(project=False),
|
||||
)
|
||||
)
|
||||
except (OSError, RuntimeError):
|
||||
return
|
||||
loadable: "bool | None" = None # asked once, and only when an old plugin is found
|
||||
for directory in directories:
|
||||
plugin_file = directory / _OPENCODE_PLUGIN_PATH
|
||||
plugin_file = directory / _OPENCODE_PLUGIN_PATH.relative_to(".opencode")
|
||||
|
||||
def pending() -> "bool | None":
|
||||
"""True for an old plugin, False for a stale entry only, None for neither."""
|
||||
@@ -486,7 +496,7 @@ def _refresh_v1_opencode_plugins() -> None:
|
||||
elif dropped:
|
||||
print(
|
||||
f"graphify: removed the stale graphify entry from "
|
||||
f"{directory / _OPENCODE_CONFIG_PATH}; set GRAPHIFY_NO_AUTO_REFRESH=1 to disable",
|
||||
f"{directory / _OPENCODE_CONFIG_PATH.name}; set GRAPHIFY_NO_AUTO_REFRESH=1 to disable",
|
||||
file=sys.stderr,
|
||||
)
|
||||
|
||||
@@ -923,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")
|
||||
@@ -969,6 +982,8 @@ def _run_cli() -> None:
|
||||
print(" and OPENAI_MODEL to the model name your server serves")
|
||||
print(" claude also reaches custom Anthropic-compatible endpoints (LiteLLM")
|
||||
print(" proxy, gateways): set ANTHROPIC_BASE_URL and ANTHROPIC_MODEL")
|
||||
print(" GRAPHIFY_CLAUDE_PROMPT_CACHE=0 disables Claude system-prompt caching")
|
||||
print(" (default: enabled; set 1 to explicitly enable)")
|
||||
print(" --model M override backend default model")
|
||||
print(" --mode deep aggressive INFERRED-edge semantic extraction")
|
||||
print(" --force full re-scan and re-dispatch: skip the incremental")
|
||||
|
||||
+80
-19
@@ -171,6 +171,36 @@ def _prefer_file_node(
|
||||
return None
|
||||
|
||||
|
||||
def resolve_reference_forms(graph: nx.Graph, query: str) -> str | None:
|
||||
"""Resolve the reference forms `explain` accepts but `resolve_seed` did not.
|
||||
|
||||
`explain` resolves a `path::Symbol` reference (#3485) and a dotted Python
|
||||
name (`pkg.mod.func` / `pkg.mod:func`, #4366) to a single node; `affected` and
|
||||
`query --seed` rejected both with "No unique node match" even when `explain`
|
||||
resolved the very same string. Following the README's own advice ("use the
|
||||
precise ID returned by the graph") therefore forced a caller through
|
||||
`explain` first just to obtain an id (#4792).
|
||||
|
||||
Only the two path-qualified forms are handled here — they carry their own
|
||||
disambiguating context, so a match is never a guess. A bare name keeps going
|
||||
through `resolve_seed`'s existing tiers, where an exact-name tie must stay
|
||||
unresolved rather than be broken by graph-iteration order.
|
||||
|
||||
Returns the unique node id, or None to fall through to the ordinary tiers.
|
||||
"""
|
||||
from graphify.serve import _find_node_tiers
|
||||
|
||||
source_exact, exact, _prefix, _substring = _find_node_tiers(graph, query)
|
||||
for tier in (source_exact, exact):
|
||||
if len(tier) == 1:
|
||||
return str(tier[0])
|
||||
if tier:
|
||||
# Several nodes in the winning tier is ambiguity, not precedence;
|
||||
# do not fall back to a looser tier and pick one arbitrarily.
|
||||
break
|
||||
return None
|
||||
|
||||
|
||||
def resolve_seed(graph: nx.Graph, query: str, root: Path | None = None) -> str | None:
|
||||
# A trailing path separator must not change a source-file match — serve's
|
||||
# _find_node tokenizes the path (which drops it), so strip it here for parity
|
||||
@@ -178,6 +208,11 @@ def resolve_seed(graph: nx.Graph, query: str, root: Path | None = None) -> str |
|
||||
query = query.rstrip("/\\") or query
|
||||
if query in graph:
|
||||
return query
|
||||
# `path::Symbol` and dotted Python names resolve exactly as `explain` does
|
||||
# (#4792); checked before the label tiers, which cannot express them.
|
||||
qualified = resolve_reference_forms(graph, query)
|
||||
if qualified is not None:
|
||||
return qualified
|
||||
query_lower = _normalize_label(query)
|
||||
exact_label_matches = [
|
||||
str(node_id)
|
||||
@@ -283,19 +318,23 @@ def affected_nodes(
|
||||
# otherwise. The member nodes are seeds only (not reported as hits), and
|
||||
# `method`/`contains` stay out of the general relation-filtered walk, so this
|
||||
# adds no forward noise anywhere else.
|
||||
if hasattr(graph, "out_edges"):
|
||||
member_edges = graph.out_edges(seed, data=True)
|
||||
else:
|
||||
member_edges = (
|
||||
(s, t, d) for s, t, d in graph.edges(data=True) if s == seed
|
||||
)
|
||||
for _s, member, data in member_edges:
|
||||
if str(data.get("relation", "")) not in ("method", "contains"):
|
||||
continue
|
||||
member = str(member)
|
||||
if member not in seen:
|
||||
seen.add(member)
|
||||
queue.append((member, 0))
|
||||
member_queue = deque([seed])
|
||||
while member_queue:
|
||||
parent = member_queue.popleft()
|
||||
if hasattr(graph, "out_edges"):
|
||||
member_edges = graph.out_edges(parent, data=True)
|
||||
else:
|
||||
member_edges = (
|
||||
(s, t, d) for s, t, d in graph.edges(data=True) if s == parent
|
||||
)
|
||||
for _s, member, data in member_edges:
|
||||
if str(data.get("relation", "")) not in ("method", "contains"):
|
||||
continue
|
||||
member = str(member)
|
||||
if member not in seen:
|
||||
seen.add(member)
|
||||
queue.append((member, 0))
|
||||
member_queue.append(member)
|
||||
|
||||
supertype_cache: dict[str, list[str]] = {}
|
||||
# Overridden members walked without being reported; one that a real edge
|
||||
@@ -353,6 +392,27 @@ def affected_nodes(
|
||||
return hits
|
||||
|
||||
|
||||
def resolve_seed_outcome(
|
||||
graph: nx.Graph, query: str, root: Path | None = None
|
||||
) -> tuple[str | None, list[str]]:
|
||||
"""Resolve a seed and report why it failed, so the CLI can set an exit code.
|
||||
|
||||
`affected` printed "No unique node match" and still exited 0, so a script
|
||||
could not branch on the outcome the README documents (3 = ambiguous,
|
||||
4 = no match) while `explain` already follows it (#4792). Returns
|
||||
``(node_id, [])`` on success, ``(None, rivals)`` when the query is the
|
||||
ambiguous name of several nodes, and ``(None, [])`` when nothing matched.
|
||||
"""
|
||||
seed = resolve_seed(graph, query, root)
|
||||
if seed is not None:
|
||||
return seed, []
|
||||
from graphify.serve import find_node_ambiguity
|
||||
|
||||
normalized = query.rstrip("/\\") or query
|
||||
rivals = find_node_ambiguity(graph, normalized)
|
||||
return None, [str(node_id) for node_id in rivals]
|
||||
|
||||
|
||||
def format_affected(
|
||||
graph: nx.Graph,
|
||||
query: str,
|
||||
@@ -360,9 +420,11 @@ def format_affected(
|
||||
relations: Iterable[str] = DEFAULT_AFFECTED_RELATIONS,
|
||||
depth: int = 2,
|
||||
root: Path | None = None,
|
||||
seed: str | None = None,
|
||||
) -> str:
|
||||
relation_list = tuple(relations)
|
||||
seed = resolve_seed(graph, query, root)
|
||||
if seed is None:
|
||||
seed = resolve_seed(graph, query, root)
|
||||
if seed is None:
|
||||
return f"No unique node match for {query}"
|
||||
|
||||
@@ -395,7 +457,8 @@ def load_graph(path: Path) -> nx.Graph:
|
||||
from networkx.readwrite import json_graph
|
||||
|
||||
try:
|
||||
raw = json.loads(path.read_text(encoding="utf-8"))
|
||||
from graphify.paths import consumed, read_graph_json
|
||||
raw = read_graph_json(path)
|
||||
except (json.JSONDecodeError, OSError) as exc:
|
||||
raise RuntimeError(
|
||||
f"Cannot read graph file {path}: {exc}. "
|
||||
@@ -410,7 +473,5 @@ def load_graph(path: Path) -> nx.Graph:
|
||||
# (__main__.py) already normalizes this (#738; same class as #1198).
|
||||
if "links" not in raw and "edges" in raw:
|
||||
raw = dict(raw, links=raw["edges"])
|
||||
try:
|
||||
return json_graph.node_link_graph(raw, edges="links")
|
||||
except TypeError:
|
||||
return json_graph.node_link_graph(raw)
|
||||
raw = dict(raw, nodes=consumed(raw["nodes"]), links=consumed(raw["links"]))
|
||||
return json_graph.node_link_graph(raw, edges="links")
|
||||
+26
-14
@@ -3,7 +3,7 @@ from __future__ import annotations
|
||||
from pathlib import Path
|
||||
import networkx as nx
|
||||
|
||||
from graphify.build import edge_data
|
||||
from graphify.build import edge_datas
|
||||
|
||||
# Builtin/mock names that can appear as annotation-derived nodes in pre-existing
|
||||
# graphs. Excluded from god-node ranking so they don't displace real abstractions
|
||||
@@ -410,18 +410,22 @@ def _cross_community_surprises(
|
||||
top_edges = sorted(betweenness.items(), key=lambda x: x[1], reverse=True)[:top_n]
|
||||
result = []
|
||||
for (u, v), score in top_edges:
|
||||
data = edge_data(G, u, v)
|
||||
result.append({
|
||||
"source": G.nodes[u].get("label", u),
|
||||
"target": G.nodes[v].get("label", v),
|
||||
"source_files": [
|
||||
G.nodes[u].get("source_file", ""),
|
||||
G.nodes[v].get("source_file", ""),
|
||||
],
|
||||
"confidence": data.get("confidence", "EXTRACTED"),
|
||||
"relation": data.get("relation", ""),
|
||||
"note": f"Bridges graph structure (betweenness={score:.3f})",
|
||||
})
|
||||
for data in edge_datas(G, u, v):
|
||||
result.append({
|
||||
"source": G.nodes[u].get("label", u),
|
||||
"target": G.nodes[v].get("label", v),
|
||||
"source_files": [
|
||||
G.nodes[u].get("source_file", ""),
|
||||
G.nodes[v].get("source_file", ""),
|
||||
],
|
||||
"confidence": data.get("confidence", "EXTRACTED"),
|
||||
"relation": data.get("relation", ""),
|
||||
"note": f"Bridges graph structure (betweenness={score:.3f})",
|
||||
})
|
||||
if len(result) >= top_n:
|
||||
break
|
||||
if len(result) >= top_n:
|
||||
break
|
||||
return result
|
||||
|
||||
# Build node → community map
|
||||
@@ -579,11 +583,19 @@ def suggest_questions(
|
||||
and G.nodes[n].get("file_type") != "rationale"
|
||||
]
|
||||
if isolated:
|
||||
has_semantic_layer = any(
|
||||
G.nodes[n].get("file_type") in ("document", "paper", "image")
|
||||
for n in G.nodes()
|
||||
)
|
||||
reason = (
|
||||
"possible documentation gaps or missing edges" if has_semantic_layer
|
||||
else "possible missing edges"
|
||||
)
|
||||
labels = [G.nodes[n].get("label", n) for n in isolated[:3]]
|
||||
questions.append({
|
||||
"type": "isolated_nodes",
|
||||
"question": f"What connects {', '.join(f'`{l}`' for l in labels)} to the rest of the system?",
|
||||
"why": f"{len(isolated)} weakly-connected nodes found - possible documentation gaps or missing edges.",
|
||||
"why": f"{len(isolated)} weakly-connected nodes found - {reason}.",
|
||||
})
|
||||
|
||||
# 5. Low-cohesion communities → structural questions
|
||||
|
||||
+310
-24
@@ -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 = 30 # File and per-declaration ids are kept distinct so a top-level declaration sharing the file's name is not dropped (#4854); a SystemVerilog `function new(...)` constructor gets its own node, `method` edge and parameter refs (#4848); a Go `var x = T{}`/`var x = &T{}` types `x` as `T` for receiver resolution like `x := T{}` (#4843); a PowerShell `using module`/`using assembly` name drops its file extension (#4847); a Solidity free-function `using {a, b} for T` set emits `uses` edges (#4846); a CommonLisp forward-referenced superclass binds to its local node instead of a sourceless stub (#4845); and Pascal `inherited`/`inline` form component blocks are recognised so later `object` blocks keep their parent (#4844), so cached extractions across those languages re-run; prior (29): OCaml `and`-chained module/class bindings are all walked (only the first was, so later bindings were silently dropped, #4822), and a SystemVerilog class `task` method is modeled like a `function` one with its own node and parameter refs while its task-locals no longer leak as class fields (#4774), so cached OCaml and Verilog/SystemVerilog extractions re-run; prior (28): Markdown ATX headings parse per CommonMark (closing `#` runs dropped, 0-3 space indent, hash-only lines mint no node, #4790) and fenced code blocks are tracked by CommonMark rules so headings inside fences stop leaking (#4787); YAML keys carry their written spelling and real line and `on`/`off`/`yes`/`no` keys no longer fold to booleans (#4784); rationale labels redact more credential shapes before caching (#4647); Razor `@implements` interface edges are extracted (#4820); aliased Terraform providers get their own node and `provider =` refs resolve (#4819); COBOL paragraphs after a nested `END PROGRAM` reattach to the enclosing program (#4824); Blade `wire:click` binds the bare method name (#4823); a Pascal record is a type with its own methods (#4825); VB.NET operator declarations are extracted as members with their bodies walked (#4821); and a Fortran call resolves to the subroutine it names (#4795), so cached Markdown/YAML/rationale/Razor/Terraform/COBOL/Blade/Pascal/VB.NET/Fortran extractions re-run; prior (27): VB.NET external namespace/type stubs now carry a `source_file` sentinel (#4725); Python member calls resolve through injected fields and method-result types (#4726); a Rust `use` is scoped to the crate it names (#4699), so cached VB.NET/Python/Rust extractions re-run; prior (26): Zig no longer crosses a call between a method and a same-named free function (#4755), and a Dart unnamed `extension on T` is detected (#4741), so cached Zig and Dart extractions re-run; prior (25): Python/Go/C++/Rust explicit type aliases (and Rust `union` items) are extracted as type nodes so references resolve instead of minting sourceless stubs (#4578/#4579/#4580/#4581); each C# method overload gets its own node bound by arity (#4584); a package.json dependency's manifest entry links to its ref node (#4569), so cached extractions re-run; prior (24): Objective-C `NS_CLOSED_ENUM` declarations are extracted as enums like `NS_ENUM` (#4705), and a `CREATE TABLE` whose column default the SQL grammar rejects (MySQL `DEFAULT current_timestamp()`) is recovered from its ERROR node (#4613), so cached ObjC and SQL extractions re-run; prior (23): `.yaml`/`.yml` files are structurally extracted (keys as nodes, config-vs-data gated) and reclassified from document to code (#2214), so cached YAML re-extracts; prior (22): SQL labels drop T-SQL brackets and routine bodies emit `reads_from`/`writes_to` (#4635), and a `GO` batch separator ends a statement (#4651), so cached `.sql` extractions re-run; prior (21): a CommonJS `const X = require('./m')` binding no longer mints a module-scope node that shadows the class the required file exports, so `new X()` resolves to the required declaration (#4621); prior (20): Obsidian `[[wikilink]]` targets that start with the scan root's own folder names now resolve to the real page (#4559), so cached markdown extractions re-run; prior (19): Dart `typedef` declarations are extracted as aliases (not variables of type `typedef`); C++ Metal/CUDA GPU qualifiers no longer mint sourceless god nodes (#4550); a `.h` header containing `extern "C"` routes to the C++ extractor; prior (18): Kotlin `typealias` (#4553), C# `delegate` (#4552), and Swift `macro` declarations (#4551) are now extracted so references stop minting sourceless stubs; Rust `use` rooted at a `mod` declared in the same scope carries `_rust_use_name` (#4564); prior (17): Python pytest-fixture markers (`_py_fixture`/`_python_fixture_param`, #4332) and module-level class-id collision salting (#2810); TS `this.field` typed from any method incl. static (#4473); Solidity callables carry `metadata.arity` + inherited-call/`super`/modifier raw calls (#4379); Go type-decl and Rust file-item case-distinct node ids (#4444); prior (16): Rust `use` edges carry the imported name as written (`_rusLine 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("."),
|
||||
|
||||
+735
-118
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
|
||||
|
||||
+58
-16
@@ -75,18 +75,25 @@ def backup_if_protected(out_dir: Path) -> "Path | None":
|
||||
backup_dir = out / today
|
||||
graph_src = out / "graph.json"
|
||||
|
||||
# Skip re-copying if today's backup already has identical graph.json content.
|
||||
# If content differs (graph changed since the last backup today), overwrite
|
||||
# the backup in place — one folder per day, always the latest pre-overwrite state.
|
||||
if backup_dir.exists() and (backup_dir / "graph.json").exists():
|
||||
src_hash = hashlib.sha256(graph_src.read_bytes()).hexdigest()
|
||||
bak_hash = hashlib.sha256((backup_dir / "graph.json").read_bytes()).hexdigest()
|
||||
if src_hash == bak_hash:
|
||||
return backup_dir # identical content, nothing to do
|
||||
|
||||
try:
|
||||
# Skip re-copying if today's backup already holds every artifact with an
|
||||
# identical graph.json. graph.json alone is not proof of completeness: a
|
||||
# snapshot missing a sidecar (an earlier copy attempt failed part-way)
|
||||
# must fall through and retry the copy instead of reporting itself
|
||||
# complete forever (#3769). If content differs, overwrite the backup in
|
||||
# place — one folder per day, always the latest pre-overwrite state.
|
||||
if backup_dir.exists() and (backup_dir / "graph.json").exists():
|
||||
src_hash = hashlib.sha256(graph_src.read_bytes()).hexdigest()
|
||||
bak_hash = hashlib.sha256((backup_dir / "graph.json").read_bytes()).hexdigest()
|
||||
if src_hash == bak_hash and all(
|
||||
(backup_dir / name).exists()
|
||||
for name in _BACKUP_ARTIFACTS
|
||||
if (out / name).exists()
|
||||
):
|
||||
return backup_dir # identical content, nothing to do
|
||||
backup_dir.mkdir(parents=True, exist_ok=True)
|
||||
copied = 0
|
||||
failed: list[str] = []
|
||||
for name in _BACKUP_ARTIFACTS:
|
||||
src = out / name
|
||||
if src.exists():
|
||||
@@ -94,12 +101,21 @@ def backup_if_protected(out_dir: Path) -> "Path | None":
|
||||
shutil.copy2(src, backup_dir / name)
|
||||
copied += 1
|
||||
except Exception:
|
||||
pass
|
||||
failed.append(name)
|
||||
if failed:
|
||||
# A partial snapshot reported as a successful backup lets a stale
|
||||
# graph.json survive the next overwrite unnoticed (#3769). Best-effort
|
||||
# is unchanged: warn, report no backup, do not block the write.
|
||||
print(
|
||||
f"[graphify] warning: backup incomplete - could not copy "
|
||||
f"{', '.join(failed)} -> {backup_dir.name}/ - continuing with overwrite",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return None
|
||||
if copied:
|
||||
print(f"[graphify] backed up {reason} graph ({copied} files) -> {backup_dir.name}/")
|
||||
return backup_dir
|
||||
except Exception as exc:
|
||||
import sys
|
||||
print(f"[graphify] warning: backup failed ({exc}) - continuing with overwrite", file=sys.stderr)
|
||||
return None
|
||||
|
||||
@@ -287,8 +303,14 @@ def existing_graph_node_count(path: "str | Path"):
|
||||
def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *, force: bool = False, built_at_commit: str | None = None, community_labels: dict[int, str] | None = None, original_links: "list[dict] | None" = None) -> bool:
|
||||
# Drop #3774 accounting before any write. Extract pops these first; every
|
||||
# other caller of to_json (the documented build_merge persist path) does not.
|
||||
from graphify.build import take_shrink_accounting
|
||||
from graphify.build import take_dedup_remap, take_shrink_accounting
|
||||
# The guard below reads it; it is removed here so node_link_data cannot
|
||||
# write it into graph.json (#4940).
|
||||
dedup_remap = take_dedup_remap(G)
|
||||
take_shrink_accounting(G)
|
||||
# Sources build_merge replaced or pruned this run: their old semantic ids
|
||||
# are not lost. Popped so it is never written into graph.json.
|
||||
replaced_sources = set(G.graph.pop("_replaced_sources", None) or ())
|
||||
# Safety check: refuse to silently shrink an existing graph (#479)
|
||||
existing_path = Path(output_path)
|
||||
if not force and existing_path.exists():
|
||||
@@ -315,7 +337,10 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
|
||||
else:
|
||||
try:
|
||||
existing_data = json.loads(raw)
|
||||
del raw
|
||||
existing_nodes = existing_data.get("nodes", [])
|
||||
# Only the node list is compared; let the links go now.
|
||||
del existing_data
|
||||
if not isinstance(existing_nodes, list):
|
||||
existing_nodes = []
|
||||
existing_n = len(existing_nodes)
|
||||
@@ -335,13 +360,15 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
|
||||
)
|
||||
return False
|
||||
new_n = G.number_of_nodes()
|
||||
from graphify.build import _lost_saved_semantic_nodes
|
||||
from graphify.build import _dedup_shrink_allowance, _lost_saved_semantic_nodes
|
||||
new_node_list = [
|
||||
{"id": node_id, **{key: value for key, value in attrs.items() if key != "id"}}
|
||||
for node_id, attrs in G.nodes(data=True)
|
||||
]
|
||||
folded: dict[str, str] = {}
|
||||
missing = _lost_saved_semantic_nodes(existing_nodes, new_node_list, set(), folded)
|
||||
missing = _lost_saved_semantic_nodes(
|
||||
existing_nodes, new_node_list, replaced_sources, folded, dedup_remap=dedup_remap,
|
||||
)
|
||||
if missing:
|
||||
import sys as _sys
|
||||
ids = ", ".join(str(node.get("id")) for node in missing)
|
||||
@@ -356,6 +383,11 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
|
||||
# A twin new to this run does not offset some other node's loss.
|
||||
existing_ids = {n.get("id") for n in existing_nodes if isinstance(n, dict)}
|
||||
merged = sum(twin in existing_ids for twin in folded.values())
|
||||
# Ids entity dedup folded into a survivor are not lost either (#4940).
|
||||
if dedup_remap:
|
||||
merged += _dedup_shrink_allowance(
|
||||
existing_ids, set(G.nodes), dedup_remap,
|
||||
)
|
||||
if new_n < existing_n - merged:
|
||||
import sys as _sys
|
||||
print(
|
||||
@@ -369,6 +401,8 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
|
||||
file=_sys.stderr,
|
||||
)
|
||||
return False
|
||||
# The guard passed; free its copies of both graphs before export.
|
||||
del existing_nodes, new_node_list, existing_ids
|
||||
|
||||
node_community = _node_community_map(communities)
|
||||
_labels: dict[int, str] = {int(k): v for k, v in (community_labels or {}).items()}
|
||||
@@ -442,8 +476,14 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
|
||||
rest = sorted(k for k in item if k not in leading)
|
||||
return {k: item[k] for k in (*leading, *rest)}
|
||||
|
||||
data["nodes"] = [_canonical(n, ("id", "label")) for n in data["nodes"]]
|
||||
data["links"] = [_canonical(link, ("source", "target", "relation")) for link in data["links"]]
|
||||
def _canonicalize_in_place(items: list, lead: tuple[str, ...]) -> None:
|
||||
# Replace each dict in place so the old one is freed at once, instead
|
||||
# of holding two full copies of the node/link lists.
|
||||
for i, item in enumerate(items):
|
||||
items[i] = _canonical(item, lead)
|
||||
|
||||
_canonicalize_in_place(data["nodes"], ("id", "label"))
|
||||
_canonicalize_in_place(data["links"], ("source", "target", "relation"))
|
||||
data["nodes"].sort(key=_json_sort_key)
|
||||
data["links"].sort(key=_json_sort_key)
|
||||
if "hyperedges" not in getattr(G, "graph", {}):
|
||||
@@ -464,6 +504,8 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
|
||||
_prev = json.loads(existing_path.read_text(encoding="utf-8"))
|
||||
if isinstance(_prev, dict):
|
||||
_prev_hyperedges = _prev.get("hyperedges")
|
||||
# Only the hyperedges are read; do not hold the whole parse.
|
||||
del _prev
|
||||
except Exception:
|
||||
_prev_hyperedges = None
|
||||
if _prev_hyperedges:
|
||||
|
||||
+1671
-76
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, []):
|
||||
|
||||
+37
-27
@@ -203,35 +203,45 @@ def extract_dart(path: Path) -> dict:
|
||||
header_end = len(rest)
|
||||
header = rest[:header_end]
|
||||
|
||||
base_class = None
|
||||
generics = None
|
||||
mixins_list = []
|
||||
interfaces_list = []
|
||||
|
||||
# Parse extends or on
|
||||
extends_m = re.search(r"^\s*(?:extends|on)\s+([a-zA-Z0-9_.]+)", header)
|
||||
def _consume_generic_args(text: str) -> tuple[str | None, str]:
|
||||
if not text.strip().startswith("<"):
|
||||
return None, text
|
||||
start_idx = text.find("<")
|
||||
depth = 1
|
||||
i = start_idx + 1
|
||||
while i < len(text) and depth > 0:
|
||||
if text[i] == "<":
|
||||
depth += 1
|
||||
elif text[i] == ">":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return text[start_idx + 1 : i], text[i + 1:]
|
||||
i += 1
|
||||
return None, text
|
||||
|
||||
# Parse extends or on. A mixin's `on` clause may list several
|
||||
# superclass constraints, comma-separated (`mixin Foo on A, B {}`);
|
||||
# `extends` never does, since Dart classes have single inheritance.
|
||||
base_entries: list[tuple[str, str | None]] = []
|
||||
extends_m = re.search(r"^\s*(extends|on)\s+([a-zA-Z0-9_.]+)", header)
|
||||
if extends_m:
|
||||
base_class = extends_m.group(1)
|
||||
rest_header = header[extends_m.end():]
|
||||
if rest_header.strip().startswith("<"):
|
||||
start_idx = rest_header.find("<")
|
||||
depth = 1
|
||||
i = start_idx + 1
|
||||
while i < len(rest_header) and depth > 0:
|
||||
if rest_header[i] == "<":
|
||||
depth += 1
|
||||
elif rest_header[i] == ">":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
generics = rest_header[start_idx + 1 : i]
|
||||
break
|
||||
i += 1
|
||||
if generics is not None:
|
||||
header = rest_header[i + 1:]
|
||||
else:
|
||||
header = rest_header
|
||||
else:
|
||||
header = rest_header
|
||||
is_on = extends_m.group(1) == "on"
|
||||
base_class = extends_m.group(2)
|
||||
header = header[extends_m.end():]
|
||||
generics, header = _consume_generic_args(header)
|
||||
base_entries.append((base_class, generics))
|
||||
|
||||
if is_on:
|
||||
while True:
|
||||
comma_m = re.match(r"\s*,\s*([a-zA-Z0-9_.]+)", header)
|
||||
if not comma_m:
|
||||
break
|
||||
header = header[comma_m.end():]
|
||||
extra_generics, header = _consume_generic_args(header)
|
||||
base_entries.append((comma_m.group(1), extra_generics))
|
||||
|
||||
# Parse with
|
||||
with_m = re.search(r"^\s*with\s+", header)
|
||||
@@ -251,8 +261,8 @@ def extract_dart(path: Path) -> dict:
|
||||
if impl_m:
|
||||
interfaces_list = _split_types(header[impl_m.end():])
|
||||
|
||||
# Map extends inheritance relation
|
||||
if base_class:
|
||||
# Map extends/on inheritance relation(s)
|
||||
for base_class, generics in base_entries:
|
||||
base_nid = _make_id(base_class)
|
||||
add_node(base_nid, base_class, source_file=None)
|
||||
add_edge(class_nid, base_nid, "inherits", line=class_line)
|
||||
|
||||
@@ -327,9 +327,13 @@ def extract_elixir(path: Path) -> dict:
|
||||
enclosing[func_nid] = parent_module_nid
|
||||
if parent_module_nid:
|
||||
add_edge(parent_module_nid, func_nid, "method", line)
|
||||
module_defs.setdefault((parent_module_nid, func_name), func_nid)
|
||||
else:
|
||||
add_edge(file_nid, func_nid, "contains", line)
|
||||
# Keyed by the def's own container (module, or the file for a
|
||||
# top-level def) so a bare call can be resolved to the def that is
|
||||
# actually in scope for its caller, never to an unrelated
|
||||
# same-named def elsewhere in the file (see walk_calls below).
|
||||
module_defs.setdefault((container, func_name), func_nid)
|
||||
if do_block_node:
|
||||
function_bodies.append((func_nid, do_block_node))
|
||||
else:
|
||||
@@ -359,11 +363,6 @@ def extract_elixir(path: Path) -> dict:
|
||||
|
||||
walk(root)
|
||||
|
||||
label_to_nid: dict[str, str] = {}
|
||||
for n in nodes:
|
||||
normalised = n["label"].strip("()").lstrip(".")
|
||||
label_to_nid[normalised] = n["id"]
|
||||
|
||||
module_nid_by_name = {name: nid for nid, name in module_names.items()}
|
||||
_MODULE_REF = re.compile(r"(__MODULE__|[A-Z]\w*)(\.[A-Z]\w*)*")
|
||||
|
||||
@@ -434,8 +433,26 @@ def extract_elixir(path: Path) -> dict:
|
||||
if receiver_module is not None:
|
||||
mod_nid = module_nid_by_name.get(receiver_module)
|
||||
tgt_nid = module_defs.get((mod_nid, callee_name)) if mod_nid else None
|
||||
elif is_member_call:
|
||||
tgt_nid = None
|
||||
else:
|
||||
tgt_nid = None if is_member_call else label_to_nid.get(callee_name)
|
||||
# A bare call only ever reaches a def that is actually in
|
||||
# scope for this caller: its own module (or the file, for a
|
||||
# top-level caller) first, then each module brought into
|
||||
# scope by `import`/`use`. Without this a same-named def in
|
||||
# an unrelated sibling module in the same file silently won
|
||||
# over the caller's own def, since both shared one flat
|
||||
# name -> id table.
|
||||
own_container = enclosing.get(caller_nid) or file_nid
|
||||
tgt_nid = module_defs.get((own_container, callee_name))
|
||||
if tgt_nid is None:
|
||||
for scope_name in _call_scope_for(caller_nid):
|
||||
scope_nid = module_nid_by_name.get(scope_name)
|
||||
if scope_nid is None:
|
||||
continue
|
||||
tgt_nid = module_defs.get((scope_nid, callee_name))
|
||||
if tgt_nid is not None:
|
||||
break
|
||||
if tgt_nid and tgt_nid != caller_nid:
|
||||
pair = (caller_nid, tgt_nid)
|
||||
if pair not in seen_call_pairs:
|
||||
|
||||
+849
-46
File diff suppressed because it is too large.
Load diff
@@ -314,6 +314,19 @@ def extract_fortran(path: Path) -> dict:
|
||||
line = node.start_point[0] + 1
|
||||
add_node(type_nid, type_name, line)
|
||||
add_edge(scope_nid, type_nid, "defines", line)
|
||||
# `type, extends(base) :: derived` is Fortran's derived-type
|
||||
# inheritance syntax (the `type :: name` bare form has no base).
|
||||
# Without this, every extends() clause was silently dropped and
|
||||
# Fortran OOP hierarchies never got an inherits edge, unlike every
|
||||
# other OOP language extractor.
|
||||
base_spec = next((c for c in stmt.children if c.type == "base_type_specifier"), None)
|
||||
if base_spec is not None:
|
||||
base_name_node = next((c for c in base_spec.children if c.type == "identifier"), None)
|
||||
if base_name_node is not None:
|
||||
base_name = _read_text(base_name_node, source).lower()
|
||||
base_nid = ensure_named_node(base_name, line)
|
||||
if base_nid != type_nid:
|
||||
add_edge(type_nid, base_nid, "inherits", line)
|
||||
# Type-bound procedures in the `contains` section bind the
|
||||
# derived type to the module procedures that implement its
|
||||
# methods. Without this the binding was dropped and the type
|
||||
|
||||
+262
-50
@@ -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,50 +216,95 @@ 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
|
||||
|
||||
|
||||
def _go_struct_field_types(root, source: bytes) -> dict[str, dict[str, str]]:
|
||||
"""``struct name -> {field name -> TypeName}`` for every struct this file declares.
|
||||
|
||||
Only a named field whose type `_go_single_type_name` accepts is kept, the same rule
|
||||
the flat receiver table applies. Unlike that table it stays keyed by the struct, so a
|
||||
method in another file of the package can read the fields of its own receiver.
|
||||
"""
|
||||
fields_by_struct: dict[str, dict[str, str]] = {}
|
||||
stack = [root]
|
||||
while stack:
|
||||
n = stack.pop()
|
||||
if n.type in ("function_declaration", "method_declaration"):
|
||||
continue
|
||||
if n.type == "type_spec":
|
||||
name_node = n.child_by_field_name("name")
|
||||
body = n.child_by_field_name("type")
|
||||
if name_node is not None and body is not None and body.type == "struct_type":
|
||||
fields: dict[str, str] = {}
|
||||
for fdl in body.children:
|
||||
if fdl.type != "field_declaration_list":
|
||||
continue
|
||||
for field in fdl.children:
|
||||
if field.type != "field_declaration":
|
||||
continue
|
||||
type_name = _go_single_type_name(field.child_by_field_name("type"), source)
|
||||
for c in field.children if type_name else ():
|
||||
if c.type == "field_identifier":
|
||||
fields.setdefault(_read_text(c, source), type_name)
|
||||
if fields:
|
||||
fields_by_struct[_read_text(name_node, source)] = fields
|
||||
continue
|
||||
stack.extend(n.children)
|
||||
return fields_by_struct
|
||||
|
||||
|
||||
def extract_go(path: Path) -> dict:
|
||||
"""Extract functions, methods, type declarations, and imports from a .go file."""
|
||||
try:
|
||||
@@ -267,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] = {}
|
||||
|
||||
@@ -382,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
|
||||
@@ -612,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
|
||||
@@ -666,6 +759,17 @@ def extract_go(path: Path) -> dict:
|
||||
elem.start_point[0] + 1, context="generic_arg")
|
||||
return
|
||||
|
||||
if t == "var_declaration" and node.parent is not None and node.parent.type == "source_file":
|
||||
# A package-level `var` initialiser runs at package init and has no enclosing
|
||||
# function, so its calls, including those inside a `var f = func() {...}`
|
||||
# closure, are credited to the file, the owner a module-level call already
|
||||
# gets elsewhere. Without this they were never walked and the callee lost the
|
||||
# caller (#2360).
|
||||
emit_go_package_var_type_refs(node)
|
||||
function_bodies.append(
|
||||
(file_nid, node, None, None, _go_receiver_type_table(node, source)))
|
||||
return
|
||||
|
||||
if t == "import_declaration":
|
||||
for child in node.children:
|
||||
if child.type == "import_spec_list":
|
||||
@@ -703,17 +807,51 @@ def extract_go(path: Path) -> dict:
|
||||
walk(root)
|
||||
|
||||
# A type carries both markers, as in the tree-sitter engine: `_callable_class` is
|
||||
# the narrowing, not a separate kind.
|
||||
# the narrowing, not a separate kind. A type also carries its import path from go.mod:
|
||||
# a `pkg.T` receiver binds only to a `T` declared at the path the caller imports `pkg`
|
||||
# from, and on an incremental rebuild an unchanged declaring file reaches the resolver
|
||||
# only as its nodes.
|
||||
package_path = _go_import_path_for_file(path.absolute(), path.absolute().parent)
|
||||
for n in nodes:
|
||||
if n["id"] in callable_nids or n["id"] in callable_class_nids:
|
||||
n["_callable"] = True
|
||||
if n["id"] in callable_class_nids:
|
||||
n["_callable_class"] = True
|
||||
if package_path:
|
||||
n["_go_package_path"] = package_path
|
||||
if n["id"] in interface_nids:
|
||||
n["metadata"] = {"language": "go", "kind": "interface"}
|
||||
|
||||
# The field types of the structs this file declares ride on the file node, keyed by
|
||||
# struct id, so a method in a sibling file can type `s.field` (#3368). Not on the
|
||||
# struct node: every file holding a method of the struct emits that id too, so an
|
||||
# incremental rebuild of a method file would shadow the declaring file's copy.
|
||||
# A `pkg.T` field is stored as `<import path>.T`: the method file reading it may not
|
||||
# import `pkg` at all, so the qualifier is settled by this file's imports.
|
||||
struct_fields: dict[str, dict[str, str]] = {}
|
||||
for name, fields in _go_struct_field_types(root, source).items():
|
||||
typed: dict[str, str] = {}
|
||||
for field, type_name in fields.items():
|
||||
alias, dot, bare = type_name.partition(".")
|
||||
if not dot:
|
||||
typed[field] = type_name
|
||||
elif alias in go_imported_pkgs:
|
||||
typed[field] = f"{go_imported_pkgs[alias]}.{bare}"
|
||||
if typed:
|
||||
struct_fields[type_symbol_nid(name)] = dict(sorted(typed.items()))
|
||||
if struct_fields:
|
||||
file_node = next(n for n in nodes if n["id"] == file_nid)
|
||||
file_node["_go_fields"] = dict(sorted(struct_fields.items()))
|
||||
|
||||
type_table = _go_receiver_type_table(root, source)
|
||||
package_types = _go_receiver_type_table(root, source, package_only=True)
|
||||
local_type_names = {n["label"] for n in nodes if n["id"] in callable_class_nids}
|
||||
|
||||
method_nids = {e["target"] for e in edges if e["relation"] == "method"}
|
||||
label_to_nid: dict[str, str] = {}
|
||||
for n in nodes:
|
||||
if n["id"] in method_nids:
|
||||
continue
|
||||
raw = n["label"]
|
||||
normalised = raw.strip("()").lstrip(".")
|
||||
label_to_nid[normalised] = n["id"]
|
||||
@@ -722,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
|
||||
@@ -733,6 +879,7 @@ def extract_go(path: Path) -> dict:
|
||||
package_receiver: str | None = None
|
||||
member_receiver: str | None = None
|
||||
member_receiver_type: str | None = None
|
||||
field_owner: str | None = None
|
||||
import_path: str | None = None
|
||||
if func_node:
|
||||
if func_node.type == "identifier":
|
||||
@@ -750,19 +897,32 @@ def extract_go(path: Path) -> dict:
|
||||
import_path = go_imported_pkgs[receiver_name]
|
||||
elif operand is not None and operand.type == "identifier":
|
||||
member_receiver = receiver_name
|
||||
if self_name and receiver_name == self_name:
|
||||
member_receiver_type = self_type
|
||||
else:
|
||||
member_receiver_type = scope_types.get(receiver_name)
|
||||
member_receiver_type = scope_types.get(receiver_name)
|
||||
if receiver_name not in scope_types and receiver_name in local_type_names:
|
||||
member_receiver_type = receiver_name
|
||||
elif operand is not None and operand.type == "parenthesized_expression":
|
||||
expression = operand
|
||||
while (expression.type == "parenthesized_expression"
|
||||
and expression.named_children):
|
||||
expression = expression.named_children[0]
|
||||
if (expression.type == "unary_expression"
|
||||
and _read_text(expression, source).startswith("*")):
|
||||
expression = expression.child_by_field_name("operand")
|
||||
name = _read_text(expression, source) if expression is not None else ""
|
||||
if name in local_type_names and name not in scope_types:
|
||||
member_receiver = name
|
||||
member_receiver_type = name
|
||||
elif operand is not None and operand.type == "selector_expression":
|
||||
# `s.logger.Log()` names the receiver by the field only when `s` is
|
||||
# this method's own receiver; any other head could be a package or
|
||||
# a variable whose type the flat table does not know.
|
||||
inner = operand.child_by_field_name("operand")
|
||||
if (self_name and inner is not None and inner.type == "identifier"
|
||||
and _read_text(inner, source) == self_name):
|
||||
and _read_text(inner, source) == self_name
|
||||
and scope_types.get(self_name) == self_type):
|
||||
member_receiver = _read_text(
|
||||
operand.child_by_field_name("field"), source)
|
||||
field_owner = self_type
|
||||
if field:
|
||||
callee_name = _read_text(field, source)
|
||||
if is_bare_identifier and callee_name in _GO_PREDECLARED_FUNCS:
|
||||
@@ -772,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:
|
||||
@@ -801,16 +962,67 @@ def extract_go(path: Path) -> dict:
|
||||
# `is_member_call` plus `receiver` without checking the language,
|
||||
# so a Go name placed there binds to their types in a mixed corpus.
|
||||
"member_receiver": member_receiver,
|
||||
# The enclosing function's own receiver and parameters/locals, whose
|
||||
# declarations are in scope here; the flat table is the fallback for
|
||||
# a struct field, and must not answer a name this scope rebinds.
|
||||
"receiver_type": member_receiver_type,
|
||||
"receiver_bound": not field_owner and member_receiver in scope_types,
|
||||
# Field ownership remains explicit when the struct is declared
|
||||
# in a sibling file of the package.
|
||||
"field_owner": field_owner,
|
||||
"import_path": import_path,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
})
|
||||
# A method value passed as an argument (`routing.Wrap(s.Handle)`,
|
||||
# `r.Get("/p", s.Handle)`) is how Go registers a handler or callback. It is
|
||||
# not a call here, so it never reached the branch above and the method had
|
||||
# no caller. Record it for the member-call resolver as an indirect call
|
||||
# through the receiver's declared type (#1566). `s.field.Handle` is typed
|
||||
# through the field, as a direct `s.field.M()` is, only when `s` is this
|
||||
# method's own receiver.
|
||||
args = node.child_by_field_name("arguments")
|
||||
for arg in args.children if args is not None else ():
|
||||
if arg.type != "selector_expression":
|
||||
continue
|
||||
operand = arg.child_by_field_name("operand")
|
||||
field = arg.child_by_field_name("field")
|
||||
if operand is None or field is None:
|
||||
continue
|
||||
arg_field_owner: str | None = None
|
||||
if operand.type == "identifier":
|
||||
name = _read_text(operand, source)
|
||||
if name in go_imported_pkgs:
|
||||
continue
|
||||
arg_receiver_type = scope_types.get(name)
|
||||
elif operand.type == "selector_expression":
|
||||
inner = operand.child_by_field_name("operand")
|
||||
if not (self_name and inner is not None and inner.type == "identifier"
|
||||
and _read_text(inner, source) == self_name
|
||||
and scope_types.get(self_name) == self_type):
|
||||
continue
|
||||
name = _read_text(operand.child_by_field_name("field"), source)
|
||||
arg_receiver_type = None
|
||||
arg_field_owner = self_type
|
||||
else:
|
||||
continue
|
||||
raw_calls.append({
|
||||
"caller_nid": caller_nid,
|
||||
"callee": _read_text(field, source),
|
||||
"is_member_call": True,
|
||||
"indirect": True,
|
||||
"context": "argument",
|
||||
"language": "go",
|
||||
"receiver": None,
|
||||
"member_receiver": name,
|
||||
"receiver_type": arg_receiver_type,
|
||||
"receiver_bound": name in scope_types if not arg_field_owner else False,
|
||||
"field_owner": arg_field_owner,
|
||||
"import_path": None,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{arg.start_point[0] + 1}",
|
||||
})
|
||||
for child in node.children:
|
||||
walk_calls(child, caller_nid, self_name, self_type, scope_types)
|
||||
if child.type in ("short_var_declaration", "var_spec", "range_clause"):
|
||||
scope_types.update(_go_receiver_type_table(child, source))
|
||||
|
||||
for caller_nid, body_node, self_name, self_type, scope_types in function_bodies:
|
||||
walk_calls(body_node, caller_nid, self_name, self_type, scope_types)
|
||||
@@ -827,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)
|
||||
|
||||
|
||||
@@ -230,7 +230,10 @@ def extract_r(path: Path) -> dict:
|
||||
key_node = argument.child_by_field_name("name")
|
||||
value = argument_value(argument)
|
||||
key = _read_text(key_node, source) if key_node is not None else ""
|
||||
if key == "inherit" and value is not None:
|
||||
# R6Class spells its superclass argument `inherit`; setClass and
|
||||
# setRefClass both spell the same thing `contains` instead, so a
|
||||
# `contains = "Base"` S4/R5 class silently lost its inheritance edge.
|
||||
if key in {"inherit", "contains"} and value is not None:
|
||||
base_name = string_or_identifier(value).split("$")[-1]
|
||||
if base_name:
|
||||
base_id = classes.get(base_name, _make_id("r", "class", base_name))
|
||||
|
||||
@@ -1213,6 +1213,12 @@ def _disambiguate_colliding_node_ids(
|
||||
raw_call["caller_nid"] = remap[caller_key]
|
||||
elif raw_call.get("caller_nid") in unambiguous_remaps:
|
||||
raw_call["caller_nid"] = unambiguous_remaps[str(raw_call["caller_nid"])]
|
||||
if raw_call.get("evidence_owner"):
|
||||
eo_key = (raw_call.get("evidence_owner", ""), call_source_key)
|
||||
if eo_key in remap:
|
||||
raw_call["evidence_owner"] = remap[eo_key]
|
||||
elif raw_call.get("evidence_owner") in unambiguous_remaps:
|
||||
raw_call["evidence_owner"] = unambiguous_remaps[str(raw_call["evidence_owner"])]
|
||||
|
||||
def _is_type_like_definition(node: dict) -> bool:
|
||||
if node.get("type") == "namespace":
|
||||
@@ -1268,6 +1274,7 @@ def _apply_symbol_resolution_facts(
|
||||
root: Path,
|
||||
facts: _SymbolResolutionFacts,
|
||||
resolution_context_nodes: list[dict] | None = None,
|
||||
raw_calls: list[dict] | None = None,
|
||||
) -> None:
|
||||
"""Apply language-provided import/export/use facts to graph edges."""
|
||||
if not (
|
||||
@@ -1280,6 +1287,9 @@ def _apply_symbol_resolution_facts(
|
||||
or facts.uses
|
||||
or facts.module_imports
|
||||
):
|
||||
for edge in edges:
|
||||
edge.pop("_require_imported_name", None)
|
||||
edge.pop("_require_target_file", None)
|
||||
return
|
||||
|
||||
path_by_resolved = {_resolve_cached(path): path for path in paths}
|
||||
@@ -1388,6 +1398,13 @@ def _apply_symbol_resolution_facts(
|
||||
continue
|
||||
declared.setdefault((node_path, normalize_id(bare)), node["id"])
|
||||
node_by_id = {node.get("id"): node for node in nodes}
|
||||
refs_by_source: dict[Path, list[dict]] = {}
|
||||
for edge in edges:
|
||||
if edge.get("relation") != "references":
|
||||
continue
|
||||
edge_source = _js_source_path(str(edge.get("source_file") or ""), root)
|
||||
if edge_source is not None:
|
||||
refs_by_source.setdefault(edge_source, []).append(edge)
|
||||
for fact in facts.imports:
|
||||
if effective_suffix(fact.file_path).lower() not in (
|
||||
".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs"
|
||||
@@ -1403,11 +1420,7 @@ def _apply_symbol_resolution_facts(
|
||||
)
|
||||
if not target_nid:
|
||||
continue
|
||||
for edge in edges:
|
||||
if _js_source_path(str(edge.get("source_file") or ""), root) != source_path:
|
||||
continue
|
||||
if edge.get("relation") != "references":
|
||||
continue
|
||||
for edge in refs_by_source.get(source_path, ()):
|
||||
if edge.get("target") == target_nid:
|
||||
continue
|
||||
node = node_by_id.get(edge.get("target"))
|
||||
@@ -1630,6 +1643,24 @@ def _apply_symbol_resolution_facts(
|
||||
candidates.add(origin)
|
||||
return candidates, cyclic
|
||||
|
||||
# A destructured `require` names the immediate barrel's symbol. When that
|
||||
# target is not a node (the barrel defines nothing), follow the barrel to
|
||||
# the file that declares the symbol, so cross-file call resolution sees
|
||||
# import evidence instead of a dangling barrel reference.
|
||||
for edge in edges:
|
||||
imported_name = edge.pop("_require_imported_name", None)
|
||||
target_file = edge.pop("_require_target_file", None)
|
||||
if edge.get("relation") != "imports" or not imported_name or not target_file:
|
||||
continue
|
||||
origin_path, origin_symbol = resolve_exported_origin(
|
||||
Path(str(target_file)), str(imported_name)
|
||||
)
|
||||
target_id = symbol_nodes.get((origin_path, origin_symbol))
|
||||
if target_id is None or edge.get("target") == target_id:
|
||||
continue
|
||||
edge["target"] = target_id
|
||||
edge["target_file"] = str(path_by_resolved.get(origin_path, origin_path))
|
||||
|
||||
# The structural extractor names the immediate barrel's symbol. Resolve
|
||||
# that exact authored export site through the shared import/export facts,
|
||||
# including `import {x}; export {x}` bridges with no local declaration.
|
||||
@@ -1687,6 +1718,55 @@ def _apply_symbol_resolution_facts(
|
||||
import_fact.file_path,
|
||||
)
|
||||
|
||||
if raw_calls and any(
|
||||
fact.imported_name == "default"
|
||||
and effective_suffix(fact.file_path) in _JS_CACHE_BYPASS_SUFFIXES
|
||||
for fact in facts.imports
|
||||
):
|
||||
default_imports = {
|
||||
(_resolve_cached(fact.file_path), fact.local_name): _resolve_cached(fact.target_path)
|
||||
for fact in facts.imports
|
||||
if fact.imported_name == "default"
|
||||
and effective_suffix(fact.file_path) in _JS_CACHE_BYPASS_SUFFIXES
|
||||
}
|
||||
member_nodes: dict[tuple[Path, str, str], set[str]] = {}
|
||||
fresh_paths = {_resolve_cached(path) for path in paths}
|
||||
for node in nodes + [
|
||||
node for node in resolution_context_nodes or []
|
||||
if _js_source_path(str(node.get("source_file", "")), root) not in fresh_paths
|
||||
]:
|
||||
if not node.get("_callable"):
|
||||
continue
|
||||
source_path = _js_source_path(str(node.get("source_file", "")), root)
|
||||
if source_path is None:
|
||||
continue
|
||||
key = (source_path, str(node.get("label", "")), str(node.get("source_location", "")))
|
||||
member_nodes.setdefault(key, set()).add(str(node["id"]))
|
||||
default_members: dict[Path, dict[str, tuple[str, str]]] = {}
|
||||
for call in raw_calls:
|
||||
if (not call.get("is_member_call") or call.get("_js_receiver_shadowed")
|
||||
or call.get("_js_construct") or call.get("ts_this_field")):
|
||||
continue
|
||||
source_path = _js_source_path(str(call.get("source_file", "")), root)
|
||||
if source_path is None:
|
||||
continue
|
||||
target_path = default_imports.get((source_path, str(call.get("receiver") or "")))
|
||||
if target_path is None:
|
||||
continue
|
||||
if target_path not in default_members:
|
||||
default_members[target_path] = _js_default_object_members(target_path)
|
||||
member = default_members[target_path].get(str(call.get("callee") or ""))
|
||||
if member is None:
|
||||
continue
|
||||
targets = member_nodes.get((target_path, *member), set())
|
||||
if len(targets) != 1:
|
||||
continue
|
||||
add_edge(
|
||||
call["caller_nid"], next(iter(targets)), "calls", "call",
|
||||
int(str(call["source_location"]).removeprefix("L")),
|
||||
Path(call["source_file"]), target_file=str(target_path),
|
||||
)
|
||||
|
||||
# The structural extractor names the imported symbol on the immediate barrel,
|
||||
# which defines nothing, so its edge dangles and build mints an external stub
|
||||
# beside the edge the loop above added to the defining symbol (#4486). Drop
|
||||
@@ -1815,6 +1895,48 @@ def _apply_symbol_resolution_facts(
|
||||
# survives, and the file id is exactly what the #2231 remap
|
||||
# canonicalizes — or drop it when no file node id is available.
|
||||
owned = {str(n.get("id")) for n in nodes}
|
||||
|
||||
def _collision_aware(source_id: str, file_path: Path, line: int) -> str:
|
||||
"""The declaration node a top-level ``def``'s call actually belongs to.
|
||||
|
||||
``make_id`` strips the underscore edges off each part, so ``_main`` and
|
||||
``main`` mint one plain id. The engine salts the colliding pair apart
|
||||
(#3302) and leaves only the unique public spelling — ``main()`` — on the
|
||||
plain id, while a ``def`` collected by name here can only carry the plain
|
||||
id. So every call inside ``_main`` was being credited to ``main`` (#4994).
|
||||
|
||||
The declarations sharing that plain id sit on distinct lines, so the one
|
||||
enclosing the call line is the caller. Anything the line cannot settle
|
||||
(no candidates, or several) keeps ``source_id`` unchanged, which is what
|
||||
this pass did before.
|
||||
"""
|
||||
if not any(other.startswith(source_id + "_") for other in owned):
|
||||
return source_id
|
||||
candidates = [n for n in nodes if n.get("id") == source_id or (
|
||||
isinstance(n.get("id"), str)
|
||||
and n["id"].startswith(source_id + "_")
|
||||
# Only an underscore-collision salt (`_underscore_salted_nid`, a
|
||||
# 6-char sha1 hex) is a sibling spelling of the same def. A plain
|
||||
# alphanumeric suffix is a child node id (`classid_methodname`), so
|
||||
# matching it would wrongly steal a class member's edge (e.g. a
|
||||
# type-annotated field's reference) onto a preceding method.
|
||||
and re.fullmatch(r"[0-9a-f]{6}", n["id"][len(source_id) + 1:]) is not None
|
||||
and _js_source_path(str(n.get("source_file") or ""), root) == file_path
|
||||
)]
|
||||
if len(candidates) < 2:
|
||||
return source_id
|
||||
|
||||
def _start(node: dict) -> int:
|
||||
try:
|
||||
return int(str(node.get("source_location") or "").removeprefix("L"))
|
||||
except ValueError:
|
||||
return 0
|
||||
|
||||
enclosing = [n for n in candidates if _start(n) <= line]
|
||||
if not enclosing:
|
||||
return source_id
|
||||
return str(max(enclosing, key=_start)["id"])
|
||||
|
||||
for use_fact in facts.uses:
|
||||
file_path = _resolve_cached(use_fact.file_path)
|
||||
target_id = None
|
||||
@@ -1832,7 +1954,7 @@ def _apply_symbol_resolution_facts(
|
||||
target_id = symbol_nodes.get((file_path, use_fact.local_name))
|
||||
if target_id is None:
|
||||
continue
|
||||
source_id = use_fact.source_id
|
||||
source_id = _collision_aware(use_fact.source_id, file_path, use_fact.line)
|
||||
# Structural walking can omit named-function-local declarations while
|
||||
# materializing callback-local ones. Only actual node ownership decides
|
||||
# whether a type relationship has a represented source declaration.
|
||||
@@ -1908,6 +2030,14 @@ def _js_module_specifier(node, source: bytes) -> str | None:
|
||||
if child.type == "string":
|
||||
source_node = child
|
||||
break
|
||||
# TS `import x = require("./m")`: the module string sits inside
|
||||
# import_require_clause, not as a direct child of import_statement
|
||||
# (same dig as `_import_js` in extract.py).
|
||||
if child.type == "import_require_clause":
|
||||
source_node = next(
|
||||
(sub for sub in child.children if sub.type == "string"), None
|
||||
)
|
||||
break
|
||||
if source_node is None:
|
||||
return None
|
||||
raw = _read_text(source_node, source).strip()
|
||||
@@ -2017,7 +2147,8 @@ def _js_default_export_name(node, source: bytes) -> str | None:
|
||||
`export default abstract class Foo {}` (name on the `declaration` field) and
|
||||
`export default Foo` (an identifier on the `value` field). Anonymous defaults
|
||||
(`export default class {}`, `export default {...}`) have no resolvable symbol
|
||||
and return None.
|
||||
and return None; the members of an anonymous default object are resolved
|
||||
separately by :func:`_js_default_object_members`.
|
||||
"""
|
||||
if not any(child.type == "default" for child in node.children):
|
||||
return None
|
||||
@@ -2030,6 +2161,47 @@ def _js_default_export_name(node, source: bytes) -> str | None:
|
||||
return _read_text(value, source)
|
||||
return None
|
||||
|
||||
def _js_default_object_members(path: Path) -> dict[str, tuple[str, str]]:
|
||||
"""Static methods of a direct default-exported object that resolve to an
|
||||
existing node. Only members we can bind to a real node are returned."""
|
||||
parsed = _parse_js_tree(path)
|
||||
if parsed is None:
|
||||
return {}
|
||||
source, root_node = parsed
|
||||
for node in root_node.named_children:
|
||||
if node.type != "export_statement" or not any(
|
||||
child.type == "default" for child in node.children
|
||||
):
|
||||
continue
|
||||
value = node.child_by_field_name("value")
|
||||
if value is None or value.type != "object":
|
||||
continue
|
||||
members: dict[str, tuple[str, str]] = {}
|
||||
seen: set[str] = set()
|
||||
for prop in value.named_children:
|
||||
if prop.type == "comment":
|
||||
continue
|
||||
key = prop.child_by_field_name("name") or prop.child_by_field_name("key")
|
||||
# A spread or computed key can override any method, so do not add an
|
||||
# edge on the strength of a same-named node alone.
|
||||
if key is None or key.type not in ("property_identifier", "string"):
|
||||
return {}
|
||||
raw_name = _read_text(key, source)
|
||||
if "\\" in raw_name:
|
||||
return {}
|
||||
name = raw_name[1:-1] if key.type == "string" else raw_name
|
||||
if name in seen:
|
||||
members.pop(name, None)
|
||||
continue
|
||||
seen.add(name)
|
||||
if prop.type == "method_definition" and not any(
|
||||
child.type in ("get", "set") for child in prop.children
|
||||
):
|
||||
members[name] = (f"{raw_name}()", f"L{prop.start_point[0] + 1}")
|
||||
return members
|
||||
return {}
|
||||
|
||||
|
||||
def _js_top_level_function_bodies(path: Path, root_node, source: bytes) -> list[tuple[str, object]]:
|
||||
bodies: list[tuple[str, object]] = []
|
||||
stem = _file_stem(path)
|
||||
@@ -2263,12 +2435,174 @@ def _ts_walk_class_members(class_node, source: bytes, path: Path, class_nid: str
|
||||
_SymbolUseFact(path, class_nid, name, "references", ctx, m_line)
|
||||
)
|
||||
|
||||
def _js_require_call_and_specifier(value_node, source: bytes):
|
||||
"""Return ``(call_node, raw_specifier)`` for a literal ``require('...')``
|
||||
(or ``require('...').x``), else ``None``.
|
||||
|
||||
Name-checks the callee the same way ``_require_imports_js`` / ``_js_value_is_require``
|
||||
do, so a ``factory()`` call is never treated as an import (#4634).
|
||||
"""
|
||||
if value_node is None:
|
||||
return None
|
||||
node = value_node
|
||||
if node.type == "member_expression":
|
||||
node = node.child_by_field_name("object")
|
||||
if node is None:
|
||||
return None
|
||||
if node.type != "call_expression":
|
||||
return None
|
||||
fn = node.child_by_field_name("function")
|
||||
if fn is None or fn.type != "identifier" or _read_text(fn, source) != "require":
|
||||
return None
|
||||
args = node.child_by_field_name("arguments")
|
||||
if args is None:
|
||||
return None
|
||||
raw = None
|
||||
for arg in args.children:
|
||||
if arg.type == "string":
|
||||
raw = _read_text(arg, source).strip("'\"` ")
|
||||
break
|
||||
if not raw:
|
||||
return None
|
||||
return node, raw
|
||||
|
||||
|
||||
def _js_cjs_require_bindings(declarator, source: bytes) -> list[tuple[str, str]]:
|
||||
"""``(local_name, imported_name)`` for a whole-module ``require`` declarator.
|
||||
|
||||
Only ``const/let/var X = require('./m')`` (not ``require('./m').y`` or
|
||||
``const { X } = require('./m')``). Those other forms already get structural
|
||||
``imports`` edges from ``_require_imports_js``; minting SymbolImportFacts for
|
||||
them would also resolve call-uses through the symbol pass and regress the
|
||||
EXTRACTED ``confidence_score`` path for destructured requires (#4688 / #4634).
|
||||
Whole-module bindings are recorded as default imports, matching ESM
|
||||
``import X from './m'``.
|
||||
"""
|
||||
value = declarator.child_by_field_name("value")
|
||||
if value is None or value.type != "call_expression":
|
||||
return []
|
||||
req = _js_require_call_and_specifier(value, source)
|
||||
if req is None:
|
||||
return []
|
||||
name_node = declarator.child_by_field_name("name")
|
||||
if name_node is None or name_node.type != "identifier":
|
||||
return []
|
||||
local = _read_text(name_node, source)
|
||||
if not local:
|
||||
return []
|
||||
return [(local, "default")]
|
||||
|
||||
|
||||
def _js_cjs_default_export_local(right, source: bytes) -> str | None:
|
||||
"""Local name of a ``module.exports = <expr>`` RHS, if resolvable.
|
||||
|
||||
Walks through chained assignments (``module.exports = exports = Foo``) to the
|
||||
final RHS — an intermediate ``exports = …`` left is not the exported binding.
|
||||
"""
|
||||
node = right
|
||||
while node is not None and node.type == "assignment_expression":
|
||||
node = node.child_by_field_name("right")
|
||||
if node is None:
|
||||
return None
|
||||
if node.type == "identifier":
|
||||
return _read_text(node, source) or None
|
||||
if node.type in (
|
||||
"class", "class_declaration", "function", "function_declaration",
|
||||
"generator_function", "generator_function_declaration",
|
||||
):
|
||||
name_node = node.child_by_field_name("name")
|
||||
if name_node is not None:
|
||||
return _read_text(name_node, source) or None
|
||||
return None
|
||||
|
||||
|
||||
def _js_cjs_export_facts(node, source: bytes, path: Path) -> list[_SymbolExportFact]:
|
||||
"""Export facts for CommonJS ``module.exports`` / ``exports.X`` assignments.
|
||||
|
||||
Whole-module ``module.exports = Name`` is recorded as a default export so a
|
||||
``const X = require('./m')`` import resolves through the same alias path as
|
||||
ESM ``import X from './m'`` (#4688). Named property assignments
|
||||
(``exports.Foo = …`` / ``module.exports.Foo = …``) become named exports.
|
||||
|
||||
Bare ``exports = Name`` is intentionally ignored: in CommonJS that only
|
||||
rebinds the local ``exports`` binding and does not change what ``require()``
|
||||
returns (unlike ``module.exports = Name``).
|
||||
"""
|
||||
if node.type != "expression_statement":
|
||||
return []
|
||||
assign = next((c for c in node.children if c.type == "assignment_expression"), None)
|
||||
if assign is None:
|
||||
return []
|
||||
left = assign.child_by_field_name("left")
|
||||
right = assign.child_by_field_name("right")
|
||||
if left is None or right is None:
|
||||
return []
|
||||
line = node.start_point[0] + 1
|
||||
left_str = _read_text(left, source)
|
||||
out: list[_SymbolExportFact] = []
|
||||
if left_str == "module.exports":
|
||||
local = _js_cjs_default_export_local(right, source)
|
||||
if local:
|
||||
out.append(
|
||||
_SymbolExportFact(path, "default", line, local_name=local)
|
||||
)
|
||||
# Also expose the binding under its own name so a same-named
|
||||
# ``require`` without a default walk still finds it, and so
|
||||
# ``module.exports = Generator`` remains visible as ``Generator``.
|
||||
if local != "default":
|
||||
out.append(
|
||||
_SymbolExportFact(path, local, line, local_name=local)
|
||||
)
|
||||
elif right.type == "object":
|
||||
for prop in right.children:
|
||||
if prop.type == "shorthand_property_identifier":
|
||||
name = _read_text(prop, source)
|
||||
if name:
|
||||
out.append(
|
||||
_SymbolExportFact(path, name, line, local_name=name)
|
||||
)
|
||||
elif prop.type == "pair":
|
||||
key = prop.child_by_field_name("key")
|
||||
val = prop.child_by_field_name("value")
|
||||
if key is None:
|
||||
continue
|
||||
exported = _read_text(key, source)
|
||||
local_name = None
|
||||
if val is not None and val.type == "identifier":
|
||||
local_name = _read_text(val, source) or None
|
||||
if exported:
|
||||
out.append(
|
||||
_SymbolExportFact(
|
||||
path, exported, line, local_name=local_name or exported
|
||||
)
|
||||
)
|
||||
return out
|
||||
if left.type != "member_expression":
|
||||
return []
|
||||
# exports.Foo = ... / module.exports.Foo = ...
|
||||
obj = left.child_by_field_name("object")
|
||||
prop = left.child_by_field_name("property")
|
||||
if obj is None or prop is None:
|
||||
return []
|
||||
exported = _read_text(prop, source)
|
||||
if not exported:
|
||||
return []
|
||||
obj_str = _read_text(obj, source)
|
||||
if obj_str not in ("exports", "module.exports"):
|
||||
return []
|
||||
local = _js_cjs_default_export_local(right, source) or exported
|
||||
out.append(_SymbolExportFact(path, exported, line, local_name=local))
|
||||
return out
|
||||
|
||||
|
||||
# Node types the whole-tree passes of _collect_js_symbol_resolution_facts
|
||||
# filter on.
|
||||
_JS_FACT_NODE_TYPES = frozenset({
|
||||
"export_statement",
|
||||
"import_statement",
|
||||
"lexical_declaration",
|
||||
"variable_declaration",
|
||||
"expression_statement",
|
||||
"class_declaration",
|
||||
"abstract_class_declaration",
|
||||
"interface_declaration",
|
||||
@@ -2283,10 +2617,11 @@ def _collect_js_symbol_resolution_facts(paths: list[Path], facts: _SymbolResolut
|
||||
if not js_paths:
|
||||
return
|
||||
|
||||
trees: dict[Path, tuple[bytes, object, list]] = {}
|
||||
|
||||
# One parse per file, dropped before the next: holding every file's source and syntax tree
|
||||
# across the passes held the whole corpus (1.9 GB on Next.js). Class-member uses still follow
|
||||
# all call uses, so every fact list keeps its order.
|
||||
member_facts = _SymbolResolutionFacts()
|
||||
for path in js_paths:
|
||||
resolved_path = _resolve_cached(path)
|
||||
parsed = _parse_js_tree(path)
|
||||
if parsed is None:
|
||||
continue
|
||||
@@ -2295,7 +2630,6 @@ def _collect_js_symbol_resolution_facts(paths: list[Path], facts: _SymbolResolut
|
||||
node for node in _walk_js_tree(root_node)
|
||||
if node.type in _JS_FACT_NODE_TYPES
|
||||
]
|
||||
trees[resolved_path] = (source, root_node, indexed)
|
||||
|
||||
for node in indexed:
|
||||
if node.type == "export_statement":
|
||||
@@ -2304,6 +2638,44 @@ def _collect_js_symbol_resolution_facts(paths: list[Path], facts: _SymbolResolut
|
||||
_SymbolDeclarationFact(path, name, node.start_point[0] + 1)
|
||||
)
|
||||
|
||||
if node.type == "expression_statement":
|
||||
facts.exports.extend(_js_cjs_export_facts(node, source, path))
|
||||
continue
|
||||
|
||||
if node.type in ("lexical_declaration", "variable_declaration"):
|
||||
# CommonJS `const/let/var X = require('./m')` is an import alias,
|
||||
# not a local declaration. Without a SymbolImportFact here,
|
||||
# `class A extends X` has nothing to resolve through after #4634
|
||||
# stopped minting a shadow binding node (#4688).
|
||||
for child in node.children:
|
||||
if child.type != "variable_declarator":
|
||||
continue
|
||||
bindings = _js_cjs_require_bindings(child, source)
|
||||
if not bindings:
|
||||
continue
|
||||
req = _js_require_call_and_specifier(
|
||||
child.child_by_field_name("value"), source
|
||||
)
|
||||
if req is None:
|
||||
continue
|
||||
_call, raw_module = req
|
||||
target_path = _resolve_js_module_path(raw_module, path.parent)
|
||||
if target_path is None:
|
||||
continue
|
||||
target_path = _resolve_cached(target_path)
|
||||
line = node.start_point[0] + 1
|
||||
for local_name, imported_name in bindings:
|
||||
facts.imports.append(
|
||||
_SymbolImportFact(
|
||||
path,
|
||||
local_name,
|
||||
target_path,
|
||||
imported_name,
|
||||
line,
|
||||
)
|
||||
)
|
||||
continue
|
||||
|
||||
if node.type != "import_statement":
|
||||
continue
|
||||
raw_module = _js_module_specifier(node, source)
|
||||
@@ -2334,6 +2706,27 @@ def _collect_js_symbol_resolution_facts(paths: list[Path], facts: _SymbolResolut
|
||||
node.start_point[0] + 1,
|
||||
)
|
||||
)
|
||||
# TS `import X = require("./m")` — same default-import shape as
|
||||
# `const X = require("./m")` (#4688).
|
||||
for child in node.children:
|
||||
if child.type != "import_require_clause":
|
||||
continue
|
||||
local_node = next(
|
||||
(c for c in child.children if c.type == "identifier"), None
|
||||
)
|
||||
if local_node is None:
|
||||
continue
|
||||
local_name = _read_text(local_node, source)
|
||||
if local_name:
|
||||
facts.imports.append(
|
||||
_SymbolImportFact(
|
||||
path,
|
||||
local_name,
|
||||
target_path,
|
||||
"default",
|
||||
node.start_point[0] + 1,
|
||||
)
|
||||
)
|
||||
|
||||
for node in indexed:
|
||||
for alias, target in _js_lexical_aliases(node, source):
|
||||
@@ -2341,13 +2734,6 @@ def _collect_js_symbol_resolution_facts(paths: list[Path], facts: _SymbolResolut
|
||||
_SymbolAliasFact(path, alias, target, node.start_point[0] + 1)
|
||||
)
|
||||
|
||||
for path in js_paths:
|
||||
resolved_path = _resolve_cached(path)
|
||||
parsed = trees.get(resolved_path)
|
||||
if parsed is None:
|
||||
continue
|
||||
source, _root_node, indexed = parsed
|
||||
|
||||
for node in indexed:
|
||||
if node.type != "export_statement":
|
||||
continue
|
||||
@@ -2437,12 +2823,6 @@ def _collect_js_symbol_resolution_facts(paths: list[Path], facts: _SymbolResolut
|
||||
)
|
||||
)
|
||||
|
||||
for path in js_paths:
|
||||
resolved_path = _resolve_cached(path)
|
||||
parsed = trees.get(resolved_path)
|
||||
if parsed is None:
|
||||
continue
|
||||
source, root_node, _indexed = parsed
|
||||
for source_id, body in _js_top_level_function_bodies(path, root_node, source):
|
||||
for node in _walk_js_tree(body):
|
||||
imported_name = _js_call_identifier(node, source)
|
||||
@@ -2459,12 +2839,6 @@ def _collect_js_symbol_resolution_facts(paths: list[Path], facts: _SymbolResolut
|
||||
)
|
||||
)
|
||||
|
||||
for path in js_paths:
|
||||
resolved_path = _resolve_cached(path)
|
||||
parsed = trees.get(resolved_path)
|
||||
if parsed is None:
|
||||
continue
|
||||
source, _root_node, indexed = parsed
|
||||
stem = _file_stem(path)
|
||||
for node in indexed:
|
||||
if node.type not in (
|
||||
@@ -2480,7 +2854,8 @@ def _collect_js_symbol_resolution_facts(paths: list[Path], facts: _SymbolResolut
|
||||
if not class_name:
|
||||
continue
|
||||
class_nid = _make_id(stem, class_name)
|
||||
_ts_walk_class_members(node, source, path, class_nid, facts)
|
||||
_ts_walk_class_members(node, source, path, class_nid, member_facts)
|
||||
facts.uses.extend(member_facts.uses)
|
||||
|
||||
@functools.lru_cache(maxsize=2048)
|
||||
def _parse_python_tree_cached(path_str: str, _mtime_ns: int, _size: int):
|
||||
@@ -2829,6 +3204,12 @@ def _resolve_python_namespace_dir(module_name: str, current_path: Path, root: Pa
|
||||
return None
|
||||
|
||||
def _python_top_level_function_bodies(path: Path, root_node, source: bytes) -> list[tuple[str, object]]:
|
||||
"""``(plain caller id, body)`` for every top-level ``def`` in the module.
|
||||
|
||||
Deliberately the *unsalted* id: ``_apply_symbol_resolution_facts`` resolves
|
||||
the caller against the final graph, where the underscore-collision spread
|
||||
(#3302) is baked into the ids.
|
||||
"""
|
||||
bodies: list[tuple[str, object]] = []
|
||||
stem = _file_stem(path)
|
||||
for node in root_node.children:
|
||||
@@ -2859,13 +3240,12 @@ def _collect_python_symbol_resolution_facts(
|
||||
if not py_paths:
|
||||
return
|
||||
|
||||
trees: dict[Path, tuple[bytes, object]] = {}
|
||||
# One parse per file, dropped before the next (the same reason as the JS facts above).
|
||||
for path in py_paths:
|
||||
parsed = _parse_python_tree(path)
|
||||
if parsed is None:
|
||||
continue
|
||||
source, root_node = parsed
|
||||
trees[_resolve_cached(path)] = parsed
|
||||
|
||||
for node in _walk_python_tree(root_node):
|
||||
if node.type != "import_from_statement":
|
||||
@@ -2932,11 +3312,6 @@ def _collect_python_symbol_resolution_facts(
|
||||
)
|
||||
)
|
||||
|
||||
for path in py_paths:
|
||||
parsed = trees.get(_resolve_cached(path))
|
||||
if parsed is None:
|
||||
continue
|
||||
source, root_node = parsed
|
||||
for source_id, body in _python_top_level_function_bodies(path, root_node, source):
|
||||
for node in _walk_python_tree(body):
|
||||
imported_name = _python_call_identifier(node, source)
|
||||
@@ -2960,6 +3335,7 @@ def _augment_symbol_resolution_edges(
|
||||
root: Path,
|
||||
ambiguous_python_modules: set[str] | None = None,
|
||||
resolution_context_nodes: list[dict] | None = None,
|
||||
raw_calls: list[dict] | None = None,
|
||||
) -> None:
|
||||
facts = _SymbolResolutionFacts()
|
||||
_collect_js_symbol_resolution_facts(paths, facts)
|
||||
@@ -2971,7 +3347,10 @@ def _augment_symbol_resolution_edges(
|
||||
_apply_symbol_resolution_facts(
|
||||
paths, nodes, edges, root, facts,
|
||||
resolution_context_nodes=resolution_context_nodes,
|
||||
raw_calls=raw_calls,
|
||||
)
|
||||
elif raw_calls:
|
||||
_apply_symbol_resolution_facts(paths, nodes, edges, root, facts, raw_calls=raw_calls)
|
||||
else:
|
||||
_apply_symbol_resolution_facts(paths, nodes, edges, root, facts)
|
||||
|
||||
@@ -3042,6 +3421,13 @@ def _resolve_cross_file_imports(
|
||||
node_by_id = {node["id"]: node for node in all_nodes if node.get("id")} if all_nodes else {}
|
||||
repointed_from: set[str] = set()
|
||||
TYPE_REPOINT_RELATIONS = frozenset({"references", "inherits", "implements", "extends"})
|
||||
# The #3252 repoint below only ever touches an edge whose source_file belongs
|
||||
# to the importing file. Index the edges by source_file once, when the first
|
||||
# file needs it, instead of scanning all of them per file (files x edges,
|
||||
# #4980). Each entry keeps the edge's position in all_edges, so a file's
|
||||
# edges are visited in the same order as before.
|
||||
edges_by_source: dict[object, list[tuple[int, dict]]] = {}
|
||||
edges_indexed = False
|
||||
|
||||
for file_result, path in zip(per_file, paths):
|
||||
str_path = str(path)
|
||||
@@ -3219,9 +3605,15 @@ def _resolve_cross_file_imports(
|
||||
# Repoint AST type-reference and inheritance edges from sourceless stubs
|
||||
# to the exact imported target definition (#3252).
|
||||
if all_edges and import_targets:
|
||||
for edge in all_edges:
|
||||
if edge.get("source_file") not in file_srcs:
|
||||
continue
|
||||
if not edges_indexed:
|
||||
for position, edge in enumerate(all_edges):
|
||||
edges_by_source.setdefault(edge.get("source_file"), []).append((position, edge))
|
||||
edges_indexed = True
|
||||
file_edges = sorted(
|
||||
(entry for src in file_srcs for entry in edges_by_source.get(src, ())),
|
||||
key=lambda entry: entry[0],
|
||||
)
|
||||
for _, edge in file_edges:
|
||||
if edge.get("relation") not in TYPE_REPOINT_RELATIONS:
|
||||
continue
|
||||
tgt = edge.get("target")
|
||||
@@ -3520,9 +3912,9 @@ def _resolve_cross_file_java_imports(
|
||||
language = Language(tsjava.language())
|
||||
parser = Parser(language)
|
||||
|
||||
# Pre-pass: declared package per source_file string (and parsed trees for
|
||||
# pass 2, so each file is only parsed once).
|
||||
parsed: dict[str, tuple[bytes, object]] = {}
|
||||
# Pre-pass: declared package per source_file string and each file's imports,
|
||||
# so pass 2 needs no syntax tree: holding every tree held the whole corpus.
|
||||
imports_by_path: dict[str, list[tuple[str, str, int]]] = {}
|
||||
pkg_by_src: dict[str, str] = {}
|
||||
for path, file_result in zip(paths, per_file):
|
||||
try:
|
||||
@@ -3530,7 +3922,7 @@ def _resolve_cross_file_java_imports(
|
||||
tree = parser.parse(source)
|
||||
except Exception:
|
||||
continue
|
||||
parsed[str(path)] = (source, tree)
|
||||
imports_by_path[str(path)] = _java_import_rows(tree.root_node, source)
|
||||
pkg = ""
|
||||
for child in tree.root_node.children:
|
||||
if child.type == "package_declaration":
|
||||
@@ -3577,55 +3969,56 @@ def _resolve_cross_file_java_imports(
|
||||
seen_pairs: set[tuple[str, str]] = set()
|
||||
for path in paths:
|
||||
file_nid = _make_id(str(path))
|
||||
entry = parsed.get(str(path))
|
||||
if entry is None:
|
||||
continue
|
||||
source, tree = entry
|
||||
|
||||
def walk(n) -> None:
|
||||
if n.type == "import_declaration":
|
||||
raw = _read_text(n, source).strip()
|
||||
body = raw[len("import"):].strip().rstrip(";").strip()
|
||||
if body.startswith("static "):
|
||||
body = body[len("static "):].strip()
|
||||
if body.endswith(".*"):
|
||||
return
|
||||
parts = body.split(".")
|
||||
if not parts:
|
||||
return
|
||||
last = parts[-1]
|
||||
imp_pkg = ".".join(parts[:-1])
|
||||
if last and last[0].islower() and len(parts) >= 2:
|
||||
last = parts[-2]
|
||||
imp_pkg = ".".join(parts[:-2])
|
||||
at_line = n.start_point[0] + 1
|
||||
for tgt_nid, tgt_pkg in name_to_ids.get(last, []):
|
||||
if tgt_nid == file_nid:
|
||||
continue
|
||||
if not _pkg_matches(imp_pkg, tgt_pkg):
|
||||
continue
|
||||
key = (file_nid, tgt_nid)
|
||||
if key in seen_pairs:
|
||||
continue
|
||||
seen_pairs.add(key)
|
||||
new_edges.append({
|
||||
"source": file_nid,
|
||||
"target": tgt_nid,
|
||||
"relation": "imports",
|
||||
"confidence": "EXTRACTED",
|
||||
"confidence_score": 1.0,
|
||||
"source_file": str(path),
|
||||
"source_location": f"L{at_line}",
|
||||
"weight": 1.0,
|
||||
})
|
||||
for child in n.children:
|
||||
walk(child)
|
||||
|
||||
walk(tree.root_node)
|
||||
for last, imp_pkg, at_line in imports_by_path.get(str(path), ()):
|
||||
for tgt_nid, tgt_pkg in name_to_ids.get(last, []):
|
||||
if tgt_nid == file_nid:
|
||||
continue
|
||||
if not _pkg_matches(imp_pkg, tgt_pkg):
|
||||
continue
|
||||
key = (file_nid, tgt_nid)
|
||||
if key in seen_pairs:
|
||||
continue
|
||||
seen_pairs.add(key)
|
||||
new_edges.append({
|
||||
"source": file_nid,
|
||||
"target": tgt_nid,
|
||||
"relation": "imports",
|
||||
"confidence": "EXTRACTED",
|
||||
"confidence_score": 1.0,
|
||||
"source_file": str(path),
|
||||
"source_location": f"L{at_line}",
|
||||
"weight": 1.0,
|
||||
})
|
||||
|
||||
return new_edges
|
||||
|
||||
|
||||
def _java_import_rows(root_node, source: bytes) -> list[tuple[str, str, int]]:
|
||||
"""Each non-wildcard import in a Java tree as (name, package, line), in source order."""
|
||||
rows: list[tuple[str, str, int]] = []
|
||||
|
||||
def walk(n) -> None:
|
||||
if n.type == "import_declaration":
|
||||
raw = _read_text(n, source).strip()
|
||||
body = raw[len("import"):].strip().rstrip(";").strip()
|
||||
if body.startswith("static "):
|
||||
body = body[len("static "):].strip()
|
||||
if body.endswith(".*"):
|
||||
return
|
||||
parts = body.split(".")
|
||||
last = parts[-1]
|
||||
imp_pkg = ".".join(parts[:-1])
|
||||
if last and last[0].islower() and len(parts) >= 2:
|
||||
last = parts[-2]
|
||||
imp_pkg = ".".join(parts[:-2])
|
||||
rows.append((last, imp_pkg, n.start_point[0] + 1))
|
||||
for child in n.children:
|
||||
walk(child)
|
||||
|
||||
walk(root_node)
|
||||
return rows
|
||||
|
||||
|
||||
def _go_import_path_for_file(
|
||||
source_file: str | Path,
|
||||
root: Path,
|
||||
|
||||
+136
-5
@@ -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
@@ -79,13 +79,17 @@ def _scope_id(directory: str) -> str:
|
||||
|
||||
|
||||
def prepare_terraform(result: dict, path: Path, root: Path) -> None:
|
||||
"""Make cached directory-scoped IDs portable before the common merge passes."""
|
||||
"""Make cached directory-scoped IDs portable before the common merge passes.
|
||||
|
||||
Consume the internal scope metadata even when the file is outside root.
|
||||
"""
|
||||
directory = path.parent.resolve()
|
||||
old = result.pop("_terraform_scope", _scope_id(directory.as_posix()))
|
||||
try:
|
||||
relative = directory.relative_to(root).as_posix()
|
||||
except ValueError:
|
||||
return
|
||||
old, new = _scope_id(directory.as_posix()), _scope_id(relative)
|
||||
new = _scope_id(relative)
|
||||
for node in result.get("nodes", []):
|
||||
nid = node["id"]
|
||||
if nid.startswith(old + "_"):
|
||||
@@ -508,4 +512,4 @@ def extract_terraform(path: Path) -> dict:
|
||||
nodes_by_id[owner]["attributes"] = attrs
|
||||
_collect_refs(blk_body, owner, "references")
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
return {"nodes": nodes, "edges": edges, "_terraform_scope": scope}
|
||||
@@ -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):])
|
||||
+4
-4
@@ -405,8 +405,8 @@ def _detached_launch(rebuild_body: str) -> str:
|
||||
# absolute while --git-common-dir is the relative ".git", and a raw compare would
|
||||
# false-positive on the PRIMARY checkout and wrongly skip it.
|
||||
_WORKTREE_GUARD = """\
|
||||
_GFY_GITDIR=$(cd "$(git rev-parse --git-dir 2>/dev/null)" 2>/dev/null && pwd)
|
||||
_GFY_COMMONDIR=$(cd "$(git rev-parse --git-common-dir 2>/dev/null)" 2>/dev/null && pwd)
|
||||
_GFY_GITDIR=$(CDPATH= cd "$(git rev-parse --git-dir 2>/dev/null)" 2>/dev/null && pwd)
|
||||
_GFY_COMMONDIR=$(CDPATH= cd "$(git rev-parse --git-common-dir 2>/dev/null)" 2>/dev/null && pwd)
|
||||
if [ -n "$_GFY_COMMONDIR" ] && [ "$_GFY_GITDIR" != "$_GFY_COMMONDIR" ]; then
|
||||
exit 0
|
||||
fi
|
||||
@@ -776,7 +776,7 @@ def _rev_parse_path(root: Path, flag: str) -> Path | None:
|
||||
try:
|
||||
res = _sp.run(
|
||||
["git", "-C", str(root), "rev-parse", flag],
|
||||
capture_output=True, text=True,
|
||||
capture_output=True, text=True, encoding="utf-8",
|
||||
)
|
||||
except (OSError, FileNotFoundError):
|
||||
return None
|
||||
@@ -838,7 +838,7 @@ def _hooks_dir(root: Path) -> Path:
|
||||
try:
|
||||
res = _sp.run(
|
||||
["git", "-C", str(root), "rev-parse", "--git-path", "hooks"],
|
||||
capture_output=True, text=True,
|
||||
capture_output=True, text=True, encoding="utf-8",
|
||||
)
|
||||
if res.returncode != 0:
|
||||
# git failing here is a real signal (corrupt .git/config, tampering,
|
||||
|
||||
+16
-2
@@ -108,6 +108,7 @@ class DeclIdRegistry:
|
||||
}
|
||||
self._by_name: dict[tuple[str, str], set[str]] = {}
|
||||
self._salted: set[str] = set()
|
||||
self._spelled: dict[str, str] = {}
|
||||
|
||||
def resolve(self, nid: str, name: str, kind: str, taken) -> str:
|
||||
key = (kind, nid)
|
||||
@@ -117,6 +118,7 @@ class DeclIdRegistry:
|
||||
if nid not in taken and owner is None:
|
||||
self._owners[nid] = key
|
||||
self._assigned[key] = nid
|
||||
self._spelled[nid] = name
|
||||
self._by_name.setdefault((kind, normalize_id(name)), set()).add(nid)
|
||||
return nid
|
||||
assigned = self._assigned.get(key)
|
||||
@@ -125,9 +127,12 @@ class DeclIdRegistry:
|
||||
# An id already used by a real declaration is a duplicate reference to
|
||||
# that declaration (prototype owner, same name re-declared); reuse it
|
||||
# instead of minting a second node. Only a salted id, whose owner stole
|
||||
# the spelling from this declaration, forces a counter-salt (#4854).
|
||||
# the spelling from this declaration, forces a counter-salt (#4854). A
|
||||
# different kind only counts as a duplicate when spelled the same (TS
|
||||
# `class Foo` + `namespace Foo`): `class Foo` + `function foo` are two (#4904).
|
||||
if (nid in taken and owner is not None and owner[0] != "file"
|
||||
and nid not in self._salted):
|
||||
and nid not in self._salted
|
||||
and (owner[0] == kind or self._spelled.get(nid) == name)):
|
||||
return nid
|
||||
base = make_id(nid, decl_salt(name))
|
||||
candidate = base
|
||||
@@ -138,11 +143,20 @@ class DeclIdRegistry:
|
||||
self._owners[candidate] = key
|
||||
self._assigned[key] = candidate
|
||||
self._salted.add(candidate)
|
||||
self._spelled[candidate] = name
|
||||
self._by_name.setdefault((kind, normalize_id(name)), set()).add(candidate)
|
||||
return candidate
|
||||
|
||||
def lookup(self, name: str, kinds=("type", "fn", "var", "ns", "alias")) -> str | None:
|
||||
norm = normalize_id(name)
|
||||
# A declaration spelled exactly like the reference wins over one that
|
||||
# only normalizes alike: once #4904 keeps `Session` and `session()`
|
||||
# apart, `Session s;` names the declaration spelled `Session`, whatever
|
||||
# its kind. Without an exact spelling the kind order decides, as before.
|
||||
exact = {i for kind in kinds for i in self._by_name.get((kind, norm), ())
|
||||
if self._spelled.get(i) == name}
|
||||
if len(exact) == 1:
|
||||
return next(iter(exact))
|
||||
for kind in kinds:
|
||||
ids = self._by_name.get((kind, norm))
|
||||
if ids:
|
||||
|
||||
+30
-7
@@ -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
|
||||
|
||||
|
||||
+236
-68
@@ -208,8 +208,9 @@ def _platform_skill_destination(platform_name: str, *, project: bool = False, pr
|
||||
if platform_name == "gemini":
|
||||
if project:
|
||||
return (project_dir or Path(".")) / ".gemini" / "skills" / "graphify" / "SKILL.md"
|
||||
if platform.system() == "Windows":
|
||||
return Path.home() / ".agents" / "skills" / "graphify" / "SKILL.md"
|
||||
# Gemini CLI reads ~/.gemini/skills on every OS. ~/.agents/skills is the
|
||||
# `agents` platform's destination, and sharing it let each platform
|
||||
# overwrite and uninstall the other's skill (#2800).
|
||||
return Path.home() / ".gemini" / "skills" / "graphify" / "SKILL.md"
|
||||
|
||||
if platform_name == "opencode":
|
||||
@@ -236,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
|
||||
@@ -437,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:
|
||||
@@ -487,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
|
||||
@@ -503,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
|
||||
@@ -1010,7 +1119,7 @@ def install(platform: str = "claude", *, project: bool = False, project_dir: Pat
|
||||
)
|
||||
|
||||
if platform == "opencode":
|
||||
_install_opencode_plugin(project_dir if project else Path("."))
|
||||
_install_opencode_plugin(_opencode_dir(project=project, project_dir=project_dir))
|
||||
|
||||
if project:
|
||||
_print_project_git_add_hint([_project_scope_root(skill_dst, project_dir)])
|
||||
@@ -1027,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"
|
||||
@@ -1054,10 +1164,22 @@ def _gemini_hook(project: bool = False) -> dict:
|
||||
"matcher": "read_file|list_directory",
|
||||
"hooks": [{"type": "command", "command": f"{exe} hook-guard gemini"}],
|
||||
}
|
||||
def _warn_shadowing_agents_skill() -> None:
|
||||
"""Gemini CLI prefers ~/.agents/skills over ~/.gemini/skills for a skill of
|
||||
the same name. Before #2800 a Windows gemini install wrote there, so an old
|
||||
copy can hide the one just installed. It may belong to the `agents`
|
||||
platform, so point at it rather than delete it."""
|
||||
shadow = _platform_skill_destination("agents")
|
||||
if shadow.exists():
|
||||
print(f" note: Gemini CLI loads {shadow} ahead of this install. If an older")
|
||||
print(" `graphify install --platform gemini` wrote it, delete that folder;")
|
||||
print(" if you use the `agents` platform, keep it.")
|
||||
def gemini_install(project_dir: Path | None = None, *, project: bool = False) -> None:
|
||||
"""Copy skill file, write GEMINI.md section, and install BeforeTool hook."""
|
||||
project_dir = project_dir or Path(".")
|
||||
skill_dst = _copy_skill_file("gemini", project=project, project_dir=project_dir)
|
||||
if not project:
|
||||
_warn_shadowing_agents_skill()
|
||||
|
||||
target = project_dir / "GEMINI.md"
|
||||
|
||||
@@ -1765,6 +1887,18 @@ export default {
|
||||
"""
|
||||
_OPENCODE_PLUGIN_PATH = Path(".opencode") / "plugins" / "graphify.js"
|
||||
_OPENCODE_CONFIG_PATH = Path(".opencode") / "opencode.json"
|
||||
|
||||
|
||||
def _opencode_dir(*, project: bool, project_dir: Path | None = None) -> Path:
|
||||
"""OpenCode's config dir: <project>/.opencode, or ~/.config/opencode globally.
|
||||
|
||||
OpenCode loads plugins from <dir>/plugins/ in both. The global dir has no
|
||||
.opencode/ segment, so it cannot be built by joining _OPENCODE_PLUGIN_PATH
|
||||
onto a base the way the project one is (#3398).
|
||||
"""
|
||||
if project:
|
||||
return (project_dir or Path(".")) / ".opencode"
|
||||
return Path.home() / ".config" / "opencode"
|
||||
# First line of every plugin graphify has written, back to the first one (#71).
|
||||
_OPENCODE_PLUGIN_HEADER = "// graphify OpenCode plugin"
|
||||
def _opencode_plugin_is_v1_only(body: str) -> bool:
|
||||
@@ -1775,14 +1909,14 @@ def _opencode_plugin_is_v1_only(body: str) -> bool:
|
||||
with "Plugin must export a default definition" (#3554, #3732).
|
||||
"""
|
||||
return body.startswith(_OPENCODE_PLUGIN_HEADER) and "export default" not in body
|
||||
def _opencode_config_names_plugin(project_dir: Path) -> bool:
|
||||
def _opencode_config_names_plugin(opencode_dir: Path) -> bool:
|
||||
"""True when opencode.json still mentions the bare plugin path."""
|
||||
try:
|
||||
raw = (project_dir / _OPENCODE_CONFIG_PATH).read_text(encoding="utf-8")
|
||||
raw = (opencode_dir / _OPENCODE_CONFIG_PATH.name).read_text(encoding="utf-8")
|
||||
except (OSError, UnicodeDecodeError):
|
||||
return False
|
||||
return f'"{_OPENCODE_PLUGIN_PATH.as_posix()}"' in raw
|
||||
def _drop_opencode_config_entry(project_dir: Path) -> bool:
|
||||
def _drop_opencode_config_entry(opencode_dir: Path) -> bool:
|
||||
"""Remove the plugin entry older releases wrote into opencode.json.
|
||||
|
||||
The entry was the bare path ``.opencode/plugins/graphify.js``. OpenCode
|
||||
@@ -1790,7 +1924,7 @@ def _drop_opencode_config_entry(project_dir: Path) -> bool:
|
||||
never needed, and OpenCode 2 reads a bare path as an npm package name and
|
||||
fails to install it (#3732). Returns True when the config changed.
|
||||
"""
|
||||
config_file = project_dir / _OPENCODE_CONFIG_PATH
|
||||
config_file = opencode_dir / _OPENCODE_CONFIG_PATH.name
|
||||
entry = _OPENCODE_PLUGIN_PATH.as_posix()
|
||||
try:
|
||||
raw = config_file.read_text(encoding="utf-8")
|
||||
@@ -1803,7 +1937,7 @@ def _drop_opencode_config_entry(project_dir: Path) -> bool:
|
||||
# would drop them, so say what to remove instead.
|
||||
if f'"{entry}"' in raw:
|
||||
print(
|
||||
f" {_OPENCODE_CONFIG_PATH} -> not plain JSON, left as is; "
|
||||
f" {config_file} -> not plain JSON, left as is; "
|
||||
f'remove "{entry}" from its plugin list by hand'
|
||||
)
|
||||
return False
|
||||
@@ -1821,27 +1955,28 @@ def _drop_opencode_config_entry(project_dir: Path) -> bool:
|
||||
# ensure_ascii=False: keep the user's non-ASCII values readable.
|
||||
_write_text_atomic(config_file, json.dumps(config, indent=2, ensure_ascii=False))
|
||||
return changed
|
||||
def _install_opencode_plugin(project_dir: Path) -> None:
|
||||
"""Write graphify.js into .opencode/plugins/, where OpenCode discovers it.
|
||||
def _install_opencode_plugin(opencode_dir: Path) -> None:
|
||||
"""Write graphify.js into <opencode_dir>/plugins/, where OpenCode discovers it.
|
||||
|
||||
Both files are replaced atomically. The CLI refresh can run this while
|
||||
OpenCode is watching them, and it must never see half a plugin.
|
||||
``opencode_dir`` comes from _opencode_dir. Both files are replaced
|
||||
atomically. The CLI refresh can run this while OpenCode is watching them,
|
||||
and it must never see half a plugin.
|
||||
"""
|
||||
plugin_file = project_dir / _OPENCODE_PLUGIN_PATH
|
||||
plugin_file = opencode_dir / _OPENCODE_PLUGIN_PATH.relative_to(".opencode")
|
||||
_write_text_atomic(plugin_file, _OPENCODE_PLUGIN_JS)
|
||||
print(f" {_OPENCODE_PLUGIN_PATH} -> tool.execute.before hook written")
|
||||
print(f" {plugin_file} -> tool.execute.before hook written")
|
||||
|
||||
if _drop_opencode_config_entry(project_dir):
|
||||
print(f" {_OPENCODE_CONFIG_PATH} -> stale plugin entry removed")
|
||||
def _uninstall_opencode_plugin(project_dir: Path) -> None:
|
||||
if _drop_opencode_config_entry(opencode_dir):
|
||||
print(f" {opencode_dir / _OPENCODE_CONFIG_PATH.name} -> stale plugin entry removed")
|
||||
def _uninstall_opencode_plugin(opencode_dir: Path) -> None:
|
||||
"""Remove graphify.js plugin and deregister from opencode.json."""
|
||||
plugin_file = project_dir / _OPENCODE_PLUGIN_PATH
|
||||
plugin_file = opencode_dir / _OPENCODE_PLUGIN_PATH.relative_to(".opencode")
|
||||
if plugin_file.exists():
|
||||
plugin_file.unlink()
|
||||
print(f" {_OPENCODE_PLUGIN_PATH} -> removed")
|
||||
print(f" {plugin_file} -> removed")
|
||||
|
||||
if _drop_opencode_config_entry(project_dir):
|
||||
print(f" {_OPENCODE_CONFIG_PATH} -> plugin deregistered")
|
||||
if _drop_opencode_config_entry(opencode_dir):
|
||||
print(f" {opencode_dir / _OPENCODE_CONFIG_PATH.name} -> plugin deregistered")
|
||||
def _resolve_graphify_exe(project: bool = False) -> str:
|
||||
"""Return the absolute path to the graphify executable, with forward slashes.
|
||||
|
||||
@@ -1963,7 +2098,7 @@ def _agents_install(project_dir: Path, platform: str, project: bool = False) ->
|
||||
if platform == "codex":
|
||||
_install_codex_hook(project_dir or Path("."), project=project)
|
||||
elif platform == "opencode":
|
||||
_install_opencode_plugin(project_dir or Path("."))
|
||||
_install_opencode_plugin(_opencode_dir(project=True, project_dir=project_dir))
|
||||
elif platform == "kilo":
|
||||
_install_kilo_plugin(project_dir or Path("."))
|
||||
|
||||
@@ -2114,7 +2249,7 @@ def _agents_uninstall(project_dir: Path, platform: str = "") -> None:
|
||||
if not target.exists():
|
||||
print("No AGENTS.md found in current directory - nothing to do")
|
||||
if platform == "opencode":
|
||||
_uninstall_opencode_plugin(project_dir or Path("."))
|
||||
_uninstall_opencode_plugin(_opencode_dir(project=True, project_dir=project_dir))
|
||||
elif platform == "kilo":
|
||||
_uninstall_kilo_plugin(project_dir or Path("."))
|
||||
return
|
||||
@@ -2124,7 +2259,7 @@ def _agents_uninstall(project_dir: Path, platform: str = "") -> None:
|
||||
if cleaned is None:
|
||||
print("graphify section not found in AGENTS.md - nothing to do")
|
||||
if platform == "opencode":
|
||||
_uninstall_opencode_plugin(project_dir or Path("."))
|
||||
_uninstall_opencode_plugin(_opencode_dir(project=True, project_dir=project_dir))
|
||||
elif platform == "kilo":
|
||||
_uninstall_kilo_plugin(project_dir or Path("."))
|
||||
return
|
||||
@@ -2138,7 +2273,7 @@ def _agents_uninstall(project_dir: Path, platform: str = "") -> None:
|
||||
print(f"AGENTS.md was empty after removal - deleted {target.resolve()}")
|
||||
|
||||
if platform == "opencode":
|
||||
_uninstall_opencode_plugin(project_dir or Path("."))
|
||||
_uninstall_opencode_plugin(_opencode_dir(project=True, project_dir=project_dir))
|
||||
elif platform == "kilo":
|
||||
_uninstall_kilo_plugin(project_dir or Path("."))
|
||||
def _kilo_uninstall_global() -> list[str]:
|
||||
@@ -2160,6 +2295,9 @@ def _kilo_uninstall_global() -> list[str]:
|
||||
version_file = skill_dst.parent / ".graphify_version"
|
||||
if version_file.exists():
|
||||
version_file.unlink()
|
||||
refs_dir = skill_dst.parent / "references"
|
||||
if refs_dir.exists():
|
||||
shutil.rmtree(refs_dir)
|
||||
for d in (
|
||||
skill_dst.parent,
|
||||
skill_dst.parent.parent,
|
||||
@@ -2207,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.
|
||||
|
||||
@@ -2227,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.
|
||||
@@ -2243,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:
|
||||
@@ -2308,13 +2463,17 @@ def uninstall_all(project_dir: Path | None = None, purge: bool = False) -> None:
|
||||
_antigravity_uninstall(pd)
|
||||
# AGENTS.md covers: codex, aider, opencode, claw, droid, trae, trae-cn, hermes, copilot
|
||||
_agents_uninstall(pd)
|
||||
# Amp also drops a user-scope skill at ~/.config/agents/skills, which the
|
||||
# AGENTS.md cleanup above does not touch.
|
||||
_remove_skill_file("amp")
|
||||
# The generic agents platform's user-scope skill lives at ~/.agents/skills,
|
||||
# which neither the AGENTS.md cleanup nor amp's removal reaches.
|
||||
_remove_skill_file("agents")
|
||||
_uninstall_opencode_plugin(pd)
|
||||
# `install --platform X` drops a user-scope skill (~/.codex/skills,
|
||||
# ~/.config/agents/skills for amp, ~/.agents/skills, ...) that the AGENTS.md
|
||||
# cleanup above does not touch, so remove every platform's.
|
||||
for platform_name in _PLATFORM_CONFIG:
|
||||
_remove_skill_file(platform_name)
|
||||
# Kilo's global command sits outside its skill dir.
|
||||
for line in _kilo_uninstall_global():
|
||||
print(f" {line}")
|
||||
_uninstall_opencode_plugin(_opencode_dir(project=True, project_dir=pd))
|
||||
# `graphify install --platform opencode` writes the plugin here (#3398).
|
||||
_uninstall_opencode_plugin(_opencode_dir(project=False))
|
||||
_uninstall_codex_hook(pd)
|
||||
|
||||
# Git hook
|
||||
@@ -2360,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",
|
||||
@@ -2482,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
|
||||
|
||||
+124
-14
@@ -22,6 +22,7 @@ from graphify.file_slice import (
|
||||
FileSlice,
|
||||
bisect_slice,
|
||||
expand_oversized_files,
|
||||
make_full_slice,
|
||||
read_slice_text,
|
||||
unit_path,
|
||||
)
|
||||
@@ -364,6 +365,34 @@ def _openai_max_tokens_kwarg(backend: str, max_tokens: int) -> dict[str, int]:
|
||||
return {key: max_tokens}
|
||||
|
||||
|
||||
def _provider_extra_headers(raw: object, name: str = "") -> dict[str, str] | None:
|
||||
"""Validate a custom provider's providers.json ``extra_headers`` map (#3680).
|
||||
|
||||
Some OpenAI-compatible gateways need request headers beyond Authorization
|
||||
(OpenCode Go rejects a request without ``x-opencode-session``). They are
|
||||
passed to the OpenAI client as ``default_headers``, the header counterpart
|
||||
of ``extra_body``. Only string-to-string entries are kept, and an
|
||||
``Authorization`` entry is dropped: the API key always comes from the
|
||||
provider's ``env_key``, so the config cannot swap in a different credential.
|
||||
Returns None when nothing usable remains.
|
||||
"""
|
||||
if raw is None:
|
||||
return None
|
||||
if not isinstance(raw, dict):
|
||||
print(f"[graphify] WARNING: provider {name!r} extra_headers is not an object; ignoring.", file=sys.stderr)
|
||||
return None
|
||||
headers: dict[str, str] = {}
|
||||
for key, value in raw.items():
|
||||
if not (isinstance(key, str) and isinstance(value, str)):
|
||||
print(f"[graphify] WARNING: provider {name!r} extra_headers entry {key!r} is not a string pair; ignoring it.", file=sys.stderr)
|
||||
continue
|
||||
if key.strip().lower() == "authorization":
|
||||
print(f"[graphify] WARNING: provider {name!r} extra_headers cannot set Authorization; ignoring it.", file=sys.stderr)
|
||||
continue
|
||||
headers[key] = value
|
||||
return headers or None
|
||||
|
||||
|
||||
# Model-name fragments for OpenAI-compatible "reasoning" models that reject an
|
||||
# explicit temperature: the API returns 400 "Unsupported value: 'temperature'
|
||||
# does not support 0 with this model. Only the default (1) value is supported."
|
||||
@@ -552,7 +581,7 @@ solely for such a cross-document reference. Never add this marker to a node
|
||||
defined by the enclosing source. Never invent, shorten or rewrite a path, and
|
||||
never omit source_file.
|
||||
|
||||
Node ID format: lowercase, only [a-z0-9_], no dots or slashes.
|
||||
Node ID format: lowercase, word characters only (`[^\\W]` after casefolding, i.e. `[a-z0-9_]` for ASCII input but non-ASCII letters and digits are kept as-is), no dots or slashes.
|
||||
Format: {stem}_{entity} where stem = full repo-relative path with the extension dropped, every segment joined with _ (e.g. src/auth/session.py -> src_auth_session); entity = symbol name (both normalised). Top-level files use just the filename stem (setup.py -> setup).
|
||||
|
||||
Edge direction rule — source is always the ACTOR, target is the ACTED-UPON:
|
||||
@@ -1557,6 +1586,7 @@ def _call_openai_compat(
|
||||
deep_mode: bool = False,
|
||||
images: list[_ImageRef] | None = None,
|
||||
extra_body: dict | None = None,
|
||||
extra_headers: dict[str, str] | None = None,
|
||||
) -> dict:
|
||||
"""Call any OpenAI-compatible API (Kimi, OpenAI, etc.) and return parsed JSON."""
|
||||
ollama_seed = _resolve_ollama_seed() if backend == "ollama" else None
|
||||
@@ -1582,7 +1612,8 @@ def _call_openai_compat(
|
||||
if backend == "ollama" and not os.environ.get("GRAPHIFY_MAX_RETRIES", "").strip():
|
||||
_retries = 0
|
||||
client = OpenAI(api_key=api_key, base_url=base_url, timeout=_resolve_api_timeout(),
|
||||
max_retries=_retries)
|
||||
max_retries=_retries,
|
||||
**({"default_headers": extra_headers} if extra_headers else {}))
|
||||
kwargs: dict = {
|
||||
"model": model,
|
||||
"messages": [
|
||||
@@ -1665,6 +1696,18 @@ def _call_openai_compat(
|
||||
return result
|
||||
|
||||
|
||||
def _claude_prompt_cache_enabled() -> bool:
|
||||
"""Keep prompt caching on by default; allow incompatible endpoints to opt out."""
|
||||
raw = os.environ.get("GRAPHIFY_CLAUDE_PROMPT_CACHE", "").strip().lower()
|
||||
if raw in ("", "1", "true", "yes", "on"):
|
||||
return True
|
||||
if raw in ("0", "false", "no", "off"):
|
||||
return False
|
||||
raise ValueError(
|
||||
"GRAPHIFY_CLAUDE_PROMPT_CACHE must be 1/true/yes/on or 0/false/no/off"
|
||||
)
|
||||
|
||||
|
||||
def _call_claude(api_key: str, model: str, user_message: str, max_tokens: int = 8192, *, deep_mode: bool = False, images: list[_ImageRef] | None = None) -> dict:
|
||||
"""Call Anthropic Claude directly (not via OpenAI compat layer)."""
|
||||
try:
|
||||
@@ -1672,6 +1715,7 @@ def _call_claude(api_key: str, model: str, user_message: str, max_tokens: int =
|
||||
except ImportError as exc:
|
||||
raise ImportError(_backend_pkg_hint("anthropic", "anthropic")) from exc
|
||||
|
||||
cache_enabled = _claude_prompt_cache_enabled()
|
||||
client = anthropic.Anthropic(
|
||||
api_key=api_key,
|
||||
base_url=BACKENDS["claude"]["base_url"],
|
||||
@@ -1681,13 +1725,26 @@ def _call_claude(api_key: str, model: str, user_message: str, max_tokens: int =
|
||||
resp = client.messages.create(
|
||||
model=model,
|
||||
max_tokens=max_tokens,
|
||||
system=_extraction_system(deep=deep_mode),
|
||||
# The system prompt is identical on every per-file call, so mark it
|
||||
# cacheable: later calls bill it as a cache read, not full input (#4835).
|
||||
system=[{
|
||||
"type": "text",
|
||||
"text": _extraction_system(deep=deep_mode),
|
||||
"cache_control": {"type": "ephemeral"},
|
||||
}] if cache_enabled else _extraction_system(deep=deep_mode),
|
||||
messages=[{"role": "user", "content": _anthropic_content(user_message, images or [])}],
|
||||
)
|
||||
raw_content = _anthropic_response_text(resp.content)
|
||||
result = _parse_llm_json(raw_content or "{}")
|
||||
result["input_tokens"] = (resp.usage.input_tokens or 0) if resp.usage else 0
|
||||
result["output_tokens"] = (resp.usage.output_tokens or 0) if resp.usage else 0
|
||||
# Anthropic reports the cached system prompt in its own cache_* fields, not
|
||||
# in input_tokens; add them back so cost.json still counts the whole prompt.
|
||||
usage = resp.usage
|
||||
result["input_tokens"] = (
|
||||
(usage.input_tokens or 0)
|
||||
+ (getattr(usage, "cache_read_input_tokens", 0) or 0)
|
||||
+ (getattr(usage, "cache_creation_input_tokens", 0) or 0)
|
||||
) if usage else 0
|
||||
result["output_tokens"] = (usage.output_tokens or 0) if usage else 0
|
||||
result["model"] = model
|
||||
# Normalise Anthropic's `stop_reason` to the OpenAI-compat `finish_reason`
|
||||
# vocabulary so the adaptive-retry layer doesn't have to know which
|
||||
@@ -2214,6 +2271,7 @@ def extract_files_direct(
|
||||
deep_mode=deep_mode,
|
||||
images=image_refs,
|
||||
extra_body=cfg.get("extra_body"),
|
||||
extra_headers=_provider_extra_headers(cfg.get("extra_headers"), backend),
|
||||
)
|
||||
|
||||
# Verify code-typed nodes against the source the model read and downgrade the
|
||||
@@ -2549,10 +2607,17 @@ def _extract_with_adaptive_retry(
|
||||
}
|
||||
|
||||
def _split_lone_slice() -> "tuple[FileSlice, FileSlice] | None":
|
||||
# When a single-unit chunk is a slice, bisect the slice so we can retry
|
||||
# on a smaller range rather than give up (#1369).
|
||||
if len(chunk) == 1 and isinstance(chunk[0], FileSlice) and _depth < max_depth:
|
||||
return bisect_slice(chunk[0])
|
||||
# When a single-unit chunk is a slice (or an eligible splittable text file
|
||||
# below the char cap), bisect the slice so we can retry on a smaller
|
||||
# range rather than give up (#1369, #5072).
|
||||
if len(chunk) == 1 and _depth < max_depth:
|
||||
unit = chunk[0]
|
||||
if isinstance(unit, FileSlice):
|
||||
return bisect_slice(unit)
|
||||
if isinstance(unit, (Path, str)):
|
||||
fs = make_full_slice(Path(unit))
|
||||
if fs is not None:
|
||||
return bisect_slice(fs)
|
||||
return None
|
||||
|
||||
try:
|
||||
@@ -2838,7 +2903,39 @@ def extract_corpus_parallel(
|
||||
# over session state. Force serial unless the user explicitly opts in.
|
||||
if backend == "claude-cli" and os.environ.get("GRAPHIFY_CLAUDE_CLI_PARALLEL", "").strip() != "1":
|
||||
max_concurrency = 1
|
||||
def _checkpoint_chunk(result: dict, chunk: "list[Path | FileSlice]") -> None:
|
||||
# A file split into slices is complete only once every slice has returned
|
||||
# (#4943). Checkpointing each slice as it lands stamped the parent's entry
|
||||
# complete after its first slice, so an interrupted run served the head of
|
||||
# the file as the whole file. Its results wait here until the last slice
|
||||
# succeeds, then go out in one write; a slice that fails keeps it unsaved.
|
||||
slices_left: dict[Path, int] = {}
|
||||
for _chunk in chunks:
|
||||
for _unit in _chunk:
|
||||
if isinstance(_unit, FileSlice):
|
||||
slices_left[unit_path(_unit)] = slices_left.get(unit_path(_unit), 0) + 1
|
||||
held_results: dict[Path, list[tuple[int, dict]]] = {}
|
||||
|
||||
def _checkpoint_chunk(idx: int, result: dict, chunk: "list[Path | FileSlice]") -> None:
|
||||
sliced = [unit_path(u) for u in chunk if isinstance(u, FileSlice)]
|
||||
for parent in sliced:
|
||||
slices_left[parent] -= 1
|
||||
whole = [unit_path(u) for u in chunk if not isinstance(u, FileSlice)]
|
||||
if whole:
|
||||
_save_checkpoint(result, whole)
|
||||
for parent in dict.fromkeys(sliced):
|
||||
held_results.setdefault(parent, []).append((idx, result))
|
||||
if slices_left[parent] == 0:
|
||||
# Chunk order, not completion order, so the entry is the same
|
||||
# whichever slice returned first (#1632).
|
||||
held = [r for _, r in sorted(held_results.pop(parent), key=lambda p: p[0])]
|
||||
combined: dict = {
|
||||
bucket: [item for r in held for item in r.get(bucket, [])]
|
||||
for bucket in ("nodes", "edges", "hyperedges")
|
||||
}
|
||||
combined["_partial_files"] = _merged_partial_files(*held)
|
||||
_save_checkpoint(combined, [parent])
|
||||
|
||||
def _save_checkpoint(result: dict, allowed: "list[Path]") -> None:
|
||||
# Persist each chunk's semantic results to the cache as soon as it
|
||||
# completes. Without this, the semantic cache is only written once, at
|
||||
# the very end of the run (in __main__), so a run interrupted partway
|
||||
@@ -2858,7 +2955,6 @@ def extract_corpus_parallel(
|
||||
# old `.rel` attribute does not exist on FileSlice, so every sliced
|
||||
# chunk leaked the FileSlice object into the allowlist and the write
|
||||
# raised TypeError, silently defeating the checkpoint.)
|
||||
allowed = [unit_path(item) for item in chunk]
|
||||
# Deep-mode results checkpoint into their own namespace
|
||||
# (cache/semantic-deep/) so a deep run never overwrites standard
|
||||
# entries — and a later standard run never serves deep ones (#1894).
|
||||
@@ -2896,7 +2992,7 @@ def extract_corpus_parallel(
|
||||
continue
|
||||
assert result is not None
|
||||
_merge_into(merged, result)
|
||||
_checkpoint_chunk(result, chunk)
|
||||
_checkpoint_chunk(idx, result, chunk)
|
||||
if callable(on_chunk_done):
|
||||
on_chunk_done(idx, total, result)
|
||||
else:
|
||||
@@ -2922,12 +3018,24 @@ def extract_corpus_parallel(
|
||||
continue
|
||||
assert result is not None
|
||||
results_by_idx[idx] = result
|
||||
_checkpoint_chunk(result, chunks[idx])
|
||||
_checkpoint_chunk(idx, result, chunks[idx])
|
||||
if callable(on_chunk_done):
|
||||
on_chunk_done(idx, total, result)
|
||||
for idx in sorted(results_by_idx):
|
||||
_merge_into(merged, results_by_idx[idx])
|
||||
|
||||
# A failed slice leaves its parent with nodes from the other slices, so the
|
||||
# parent looks covered and the caller's final save would write it complete
|
||||
# (#4943). Name it partial so that save stamps it and the next run retries.
|
||||
failed_parents = {
|
||||
unit_path(u) for chunk in chunks for u in chunk
|
||||
if isinstance(u, FileSlice) and unit_path(u) in failed_files
|
||||
}
|
||||
if failed_parents:
|
||||
merged["_partial_files"] = sorted(
|
||||
set(merged.get("_partial_files", []) or []) | {str(p) for p in failed_parents}
|
||||
)
|
||||
|
||||
# Loud failure summary — surface chunk failures at end so they're never
|
||||
# buried mid-log. Exit 0 preserved for caller compatibility; the
|
||||
# summary block makes the problem visible.
|
||||
@@ -3260,7 +3368,9 @@ def _call_llm(
|
||||
from openai import OpenAI
|
||||
except ImportError as exc:
|
||||
raise ImportError(_backend_pkg_hint("openai", "openai")) from exc
|
||||
client = OpenAI(api_key=key, base_url=cfg["base_url"], timeout=_resolve_api_timeout(), max_retries=_resolve_max_retries())
|
||||
_headers = _provider_extra_headers(cfg.get("extra_headers"), backend)
|
||||
client = OpenAI(api_key=key, base_url=cfg["base_url"], timeout=_resolve_api_timeout(), max_retries=_resolve_max_retries(),
|
||||
**({"default_headers": _headers} if _headers else {}))
|
||||
kwargs: dict = {
|
||||
"model": mdl,
|
||||
"messages": [{"role": "user", "content": prompt}],
|
||||
|
||||
+282
-28
@@ -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
|
||||
|
||||
|
||||
+332
-33
@@ -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.
|
||||
|
||||
@@ -2259,16 +2476,14 @@ def _path_search_graph(G: nx.Graph, undirected: bool) -> nx.Graph:
|
||||
return H
|
||||
|
||||
|
||||
def _path_confidence_line(hop_datas: list[list[dict]]) -> str:
|
||||
"""Overall confidence of a path: its weakest hop (#4885).
|
||||
def _path_weakest(hop_datas: list[list[dict]]):
|
||||
"""The weakest hop of a path, or None when no hop carries confidence.
|
||||
|
||||
A path is only as sure as its least certain hop. Each hop is ranked by
|
||||
the weakest evidence it carries (`_CONFIDENCE_RANK`, then the lowest
|
||||
`confidence_score`; a missing score never counts as weaker than a present
|
||||
one), and the first weakest hop is named. A hop with no recognised
|
||||
confidence tag ranks below AMBIGUOUS and makes the whole path unknown.
|
||||
EXTRACTED is 1.0 by definition, so its score is neither ranked nor
|
||||
printed, matching the per-hop tags.
|
||||
Each hop is ranked by the weakest evidence it carries (`_CONFIDENCE_RANK`,
|
||||
then the lowest `confidence_score`; a missing score never counts as weaker
|
||||
than a present one). EXTRACTED is 1.0 by definition, so its score is neither
|
||||
ranked nor printed, matching the per-hop tags. Returns
|
||||
`(key, hop, rel, conf, score)` where `key` sorts weakest-first.
|
||||
"""
|
||||
weakest = None
|
||||
for hop, datas in enumerate(hop_datas, 1):
|
||||
@@ -2287,6 +2502,17 @@ def _path_confidence_line(hop_datas: list[list[dict]]) -> str:
|
||||
key = (rank, score is None, score or 0.0, hop)
|
||||
if weakest is None or key < weakest[0]:
|
||||
weakest = (key, hop, d.get("relation") or "related", conf if rank else None, score)
|
||||
return weakest
|
||||
|
||||
|
||||
def _path_confidence_line(hop_datas: list[list[dict]]) -> str:
|
||||
"""Overall confidence of a path: its weakest hop (#4885).
|
||||
|
||||
A path is only as sure as its least certain hop (see `_path_weakest`). A hop
|
||||
with no recognised confidence tag ranks below AMBIGUOUS and makes the whole
|
||||
path unknown.
|
||||
"""
|
||||
weakest = _path_weakest(hop_datas)
|
||||
if weakest is None:
|
||||
return ""
|
||||
_, hop, rel, conf, score = weakest
|
||||
@@ -2296,6 +2522,73 @@ def _path_confidence_line(hop_datas: list[list[dict]]) -> str:
|
||||
return f"Path confidence: {conf} (weakest hop {hop}: {rel}{score_str})"
|
||||
|
||||
|
||||
# Enough equal-length routes to find the weakest among them without letting a
|
||||
# pathological graph enumerate an exponential number of shortest paths (#4881).
|
||||
_MAX_SHORTEST_PATHS = 256
|
||||
|
||||
|
||||
def _path_hop_datas(G: nx.Graph, path_nodes: list[str]) -> list[list[dict]]:
|
||||
"""Per-hop edge-data lists for a node path, honouring `_src` direction
|
||||
markers (#2309) the same way the path renderer does."""
|
||||
hop_datas: list[list[dict]] = []
|
||||
for i in range(len(path_nodes) - 1):
|
||||
u, v = path_nodes[i], path_nodes[i + 1]
|
||||
fwd, bwd = [], []
|
||||
for a, b in ((u, v), (v, u)):
|
||||
if G.has_edge(a, b):
|
||||
for d in edge_datas(G, a, b):
|
||||
(fwd if d.get("_src", a) == u else bwd).append(d)
|
||||
hop_datas.append(fwd or bwd)
|
||||
return hop_datas
|
||||
|
||||
|
||||
def _path_confidence_key(hop_datas: list[list[dict]]):
|
||||
"""Sortable, weakest-first key for a whole path. A path that carries no
|
||||
confidence evidence at all is 'unknown' and sorts below any tagged path."""
|
||||
weakest = _path_weakest(hop_datas)
|
||||
return weakest[0] if weakest is not None else (-1, True, 0.0, 0)
|
||||
|
||||
|
||||
def _weakest_shortest_path(search_graph: nx.Graph, G: nx.Graph, src_nid: str, tgt_nid: str):
|
||||
"""Among all shortest paths `src_nid` -> `tgt_nid`, the most conservative one.
|
||||
|
||||
A path is only as sure as its weakest hop, so when several routes tie on
|
||||
length the reported confidence should reflect the weakest of them, not an
|
||||
arbitrary route networkx happens to return first (#4881). Enumeration is
|
||||
bounded by `_MAX_SHORTEST_PATHS`. Raises `nx.NetworkXNoPath` /
|
||||
`nx.NodeNotFound` exactly like `nx.shortest_path`, so callers keep their
|
||||
existing error handling. Returns `(path_nodes, n_routes, capped)`.
|
||||
"""
|
||||
paths: list[list[str]] = []
|
||||
for p in nx.all_shortest_paths(search_graph, src_nid, tgt_nid):
|
||||
paths.append(p)
|
||||
if len(paths) > _MAX_SHORTEST_PATHS:
|
||||
break
|
||||
capped = len(paths) > _MAX_SHORTEST_PATHS
|
||||
if capped:
|
||||
paths = paths[:_MAX_SHORTEST_PATHS]
|
||||
chosen = min(paths, key=lambda p: _path_confidence_key(_path_hop_datas(G, p)))
|
||||
return chosen, len(paths), capped
|
||||
|
||||
|
||||
def _confidence_tag(d: dict) -> str:
|
||||
"""An edge's confidence label, with its stored score when it carries one.
|
||||
|
||||
Renders ``INFERRED 0.75`` for a scored non-EXTRACTED edge (#4882).
|
||||
EXTRACTED is 1.0 by definition, so it stays bare; a missing, boolean or
|
||||
non-finite score keeps the bare label rather than printing a guess.
|
||||
"""
|
||||
conf = str(d.get("confidence") or "")
|
||||
score = d.get("confidence_score")
|
||||
if (
|
||||
conf and conf != "EXTRACTED"
|
||||
and isinstance(score, (int, float)) and not isinstance(score, bool)
|
||||
and math.isfinite(score)
|
||||
):
|
||||
return f"{conf} {score:.2f}"
|
||||
return conf
|
||||
|
||||
|
||||
def _shortest_path_text(G: nx.Graph, arguments: dict) -> str:
|
||||
"""Body of the `shortest_path` MCP tool (module-level so tests can call it
|
||||
without an mcp install).
|
||||
@@ -2338,7 +2631,9 @@ def _shortest_path_text(G: nx.Graph, arguments: dict) -> str:
|
||||
max_hops = int(arguments.get("max_hops", 8))
|
||||
undirected = bool(arguments.get("undirected", False))
|
||||
try:
|
||||
path_nodes = nx.shortest_path(_path_search_graph(G, undirected), src_nid, tgt_nid)
|
||||
path_nodes, n_routes, routes_capped = _weakest_shortest_path(
|
||||
_path_search_graph(G, undirected), G, src_nid, tgt_nid
|
||||
)
|
||||
except (nx.NetworkXNoPath, nx.NodeNotFound):
|
||||
src_label = G.nodes[src_nid].get("label", src_nid)
|
||||
tgt_label = G.nodes[tgt_nid].get("label", tgt_nid)
|
||||
@@ -2370,7 +2665,7 @@ def _shortest_path_text(G: nx.Graph, arguments: dict) -> str:
|
||||
forward = bool(fwd)
|
||||
rels = sorted({d.get("relation") for d in datas if d.get("relation")})
|
||||
rel = "/".join(rels) if rels else "related"
|
||||
confs = sorted({e["confidence"] for d in datas for e in edge_evidence(d) if e.get("confidence")})
|
||||
confs = sorted({_confidence_tag(e) for d in datas for e in edge_evidence(d) if e.get("confidence")})
|
||||
conf_str = f" [{'/'.join(confs)}]" if confs else ""
|
||||
if i == 0:
|
||||
segments.append(G.nodes[u].get("label", u))
|
||||
@@ -2380,6 +2675,10 @@ def _shortest_path_text(G: nx.Graph, arguments: dict) -> str:
|
||||
segments.append(f"<--{rel}{conf_str}-- {G.nodes[v].get('label', v)}")
|
||||
prefix = ("\n".join(warnings) + "\n") if warnings else ""
|
||||
summary = _path_confidence_line(hop_datas)
|
||||
if n_routes > 1 and summary:
|
||||
# Several routes tie on length; the confidence shown is the weakest of
|
||||
# them (#4881), so it never overstates how sure the connection is.
|
||||
summary += f" (weakest of {'256+' if routes_capped else n_routes} equal-length routes)"
|
||||
return (
|
||||
prefix + f"Shortest path ({hops} hops):\n " + " ".join(segments)
|
||||
+ (f"\n{summary}" if summary else "")
|
||||
@@ -2450,7 +2749,7 @@ def _neighbor_lines(G: nx.Graph, nid: str, rel_filter: str = "") -> list[str]:
|
||||
continue
|
||||
lines.append(
|
||||
f" --> {sanitize_label(G.nodes[nb].get('label', nb))} "
|
||||
f"[{sanitize_label(str(rel))}] [{sanitize_label(str(d.get('confidence', '')))}]{_edge_at(d)}"
|
||||
f"[{sanitize_label(str(rel))}] [{sanitize_label(_confidence_tag(d))}]{_edge_at(d)}"
|
||||
)
|
||||
for nb in G.predecessors(nid):
|
||||
for d in edge_datas(G, nb, nid):
|
||||
@@ -2459,7 +2758,7 @@ def _neighbor_lines(G: nx.Graph, nid: str, rel_filter: str = "") -> list[str]:
|
||||
continue
|
||||
lines.append(
|
||||
f" <-- {sanitize_label(G.nodes[nb].get('label', nb))} "
|
||||
f"[{sanitize_label(str(rel))}] [{sanitize_label(str(d.get('confidence', '')))}]{_edge_at(d)}"
|
||||
f"[{sanitize_label(str(rel))}] [{sanitize_label(_confidence_tag(d))}]{_edge_at(d)}"
|
||||
)
|
||||
return lines
|
||||
|
||||
|
||||
+34
-20
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
|
||||
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
|
||||
/graphify <path> --update # incremental - re-extract only new/changed files
|
||||
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
|
||||
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
|
||||
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
|
||||
/graphify <path> --cluster-only # rerun clustering on existing graph
|
||||
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
|
||||
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
|
||||
|
||||
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
|
||||
|
||||
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
|
||||
|
||||
## What You Must Do When Invoked
|
||||
|
||||
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
|
||||
@@ -56,7 +61,7 @@ If no path was given, use `.` (current directory). Do not ask the user for a pat
|
||||
|
||||
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.
|
||||
|
||||
Follow these steps in order. Do not skip steps.
|
||||
Follow these steps in order unless the fast path above applies.
|
||||
|
||||
### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths)
|
||||
|
||||
@@ -119,7 +124,8 @@ from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
# Write the sidecar from Python, not a shell redirect, so the same block renders
|
||||
# on PowerShell hosts without console-encoding drift (#2528).
|
||||
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
|
||||
@@ -127,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
|
||||
"
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
|
||||
```
|
||||
Corpus: X files · ~Y words
|
||||
@@ -188,6 +194,7 @@ import json
|
||||
|
||||
code_files = []
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
for f in detect.get('files', {}).get('code', []):
|
||||
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
|
||||
|
||||
@@ -195,7 +202,7 @@ if code_files:
|
||||
# root= anchors node ids and source_file on the scan root; cache_root only says
|
||||
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
|
||||
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
|
||||
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
|
||||
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
|
||||
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
|
||||
else:
|
||||
@@ -242,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
|
||||
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
|
||||
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
|
||||
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
|
||||
|
||||
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
|
||||
# run so Part C never merges a stale .graphify_cached.json (#1392).
|
||||
@@ -309,6 +317,7 @@ $(cat graphify-out/.graphify_python) -c "
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
covered = {}
|
||||
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
|
||||
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
|
||||
@@ -319,7 +328,7 @@ partial = []
|
||||
for src, n in sorted(covered.items()):
|
||||
p = Path(src)
|
||||
if not p.is_absolute():
|
||||
p = Path('INPUT_PATH') / src
|
||||
p = Path(INPUT_PATH) / src
|
||||
if not p.is_file():
|
||||
continue
|
||||
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
|
||||
@@ -375,7 +384,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
|
||||
# so the next --update re-dispatches it instead of serving a truncated extraction forever
|
||||
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
|
||||
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
note = f' ({len(partial)} left partial for retry)' if partial else ''
|
||||
print(f'Cached {saved} files' + note)
|
||||
"
|
||||
@@ -461,7 +471,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
|
||||
|
||||
### Step 4 - Build graph, cluster, analyze, generate outputs
|
||||
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Substitute it the same way you substitute `INPUT_PATH` — do not leave the literal `IS_DIRECTED` in the code.
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
|
||||
|
||||
```bash
|
||||
mkdir -p graphify-out
|
||||
@@ -476,10 +486,11 @@ from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= mirrors the --update runbook (#1361): relativize source_file to the same
|
||||
# base so the full build and incremental --update never drift apart on re-extract.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
|
||||
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
|
||||
if G.number_of_nodes() == 0:
|
||||
@@ -499,12 +510,12 @@ questions = suggest_questions(G, communities, labels)
|
||||
# nothing) when the new graph is smaller than the existing graph.json. Only write
|
||||
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
|
||||
# they never describe a graph that graph.json doesn't contain (#1392).
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json')
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
|
||||
if not wrote:
|
||||
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
|
||||
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
|
||||
raise SystemExit(1)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
analysis = {
|
||||
'communities': {str(k): v for k, v in communities.items()},
|
||||
@@ -520,7 +531,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
|
||||
|
||||
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
|
||||
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 4.5 - Graph health check (read-only integrity gate)
|
||||
|
||||
@@ -533,7 +544,8 @@ from pathlib import Path
|
||||
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
|
||||
print(format_diagnostic_report(summary))
|
||||
flags = [f'{summary[k]} {label}' for k, label in (
|
||||
('dangling_endpoint_edges', 'dangling-endpoint edges'),
|
||||
@@ -546,7 +558,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
|
||||
"
|
||||
```
|
||||
|
||||
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
|
||||
### Step 5 - Label communities
|
||||
|
||||
@@ -567,9 +579,10 @@ from pathlib import Path
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
|
||||
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
|
||||
@@ -580,7 +593,7 @@ labels = LABELS_DICT
|
||||
# Regenerate questions with real community labels (labels affect question phrasing)
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
|
||||
# Re-export so graph.json nodes carry the curated community_name (#2490).
|
||||
@@ -595,7 +608,7 @@ print('Report updated with community labels')
|
||||
```
|
||||
|
||||
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 6 - Generate Obsidian vault (opt-in) + HTML
|
||||
|
||||
@@ -635,6 +648,7 @@ from graphify.detect import save_manifest
|
||||
# Save manifest for --update
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
|
||||
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
|
||||
# root= relativizes the manifest keys to the scan root (same base as the build),
|
||||
@@ -656,7 +670,7 @@ _corpus = detect.get('all_files') or detect['files']
|
||||
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
|
||||
_pf = Path('graphify-out/.graphify_partial.txt')
|
||||
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
|
||||
# Files dispatched this run (the changed subset) but NOT stamped above still carry
|
||||
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
|
||||
# them instead of reading them as unchanged (#1948).
|
||||
@@ -668,7 +682,7 @@ _cleared = _dispatched - _stamped
|
||||
# files newly excluded since last run are dropped rather than masquerading as
|
||||
# deletions; untouched files' prior rows are still preserved (#1908).
|
||||
_scan = {f for fl in _corpus.values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
|
||||
# Update cumulative cost tracker
|
||||
input_tok = extract.get('input_tokens', 0)
|
||||
@@ -698,7 +712,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
|
||||
|
||||
Tell the user (omit the obsidian line unless --obsidian was given):
|
||||
```
|
||||
|
||||
+22
-11
@@ -48,13 +48,17 @@ Use it for:
|
||||
- A research corpus (citation graph + concept graph in one)
|
||||
- Your personal /raw folder (drop everything in, let it grow, query it)
|
||||
|
||||
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
|
||||
|
||||
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
|
||||
|
||||
## What You Must Do When Invoked
|
||||
|
||||
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
|
||||
|
||||
If no path was given, use `.` (current directory). Do not ask the user for a path.
|
||||
|
||||
Follow these steps in order. Do not skip steps.
|
||||
Follow these steps in order unless the fast path above applies.
|
||||
|
||||
### Step 1 - Ensure graphify is installed
|
||||
|
||||
@@ -113,12 +117,13 @@ from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
print(json.dumps(result))
|
||||
" > .graphify_detect.json
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
|
||||
```
|
||||
Corpus: X files · ~Y words
|
||||
@@ -417,7 +422,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
|
||||
|
||||
### Step 4 - Build graph, cluster, analyze, generate outputs
|
||||
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source->target), otherwise `False` (the default undirected `Graph`). Substitute it everywhere it appears, the same way you substitute `INPUT_PATH` - do not leave the literal `IS_DIRECTED` in the code.
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source->target), otherwise `False` (the default undirected `Graph`). Substitute it everywhere it appears - do not leave the literal `IS_DIRECTED` in the code. INPUT_PATH is not substituted - each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
|
||||
|
||||
```bash
|
||||
mkdir -p graphify-out
|
||||
@@ -432,6 +437,7 @@ from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
detection = json.loads(Path('.graphify_detect.json').read_text())
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
G = build_from_json(extraction, directed=IS_DIRECTED)
|
||||
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
|
||||
@@ -456,7 +462,7 @@ wrote = to_json(G, communities, 'graphify-out/graph.json')
|
||||
if not wrote:
|
||||
print('ERROR: refused to shrink graphify-out/graph.json (fewer nodes than the existing graph). Run a full rebuild to be safe.')
|
||||
raise SystemExit(1)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
|
||||
|
||||
analysis = {
|
||||
@@ -473,7 +479,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
|
||||
|
||||
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
|
||||
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 5 - Label communities
|
||||
|
||||
@@ -494,6 +500,7 @@ from pathlib import Path
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
detection = json.loads(Path('.graphify_detect.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
G = build_from_json(extraction, directed=IS_DIRECTED)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
@@ -506,7 +513,7 @@ labels = LABELS_DICT
|
||||
# Regenerate questions with real community labels (labels affect question phrasing)
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
|
||||
Path('.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}))
|
||||
# Re-export so graph.json nodes carry the curated community_name (#2490).
|
||||
@@ -520,7 +527,7 @@ print('Report updated with community labels')
|
||||
```
|
||||
|
||||
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 6 - Generate Obsidian vault (opt-in) + HTML
|
||||
|
||||
@@ -715,16 +722,17 @@ from graphify.detect import save_manifest
|
||||
# Save manifest for --update
|
||||
detect = json.loads(Path('.graphify_detect.json').read_text())
|
||||
extract = json.loads(Path('.graphify_extract.json').read_text())
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
# Stamp only semantic files that produced output so a failed chunk is re-queued next run, not lost (#2015).
|
||||
from graphify.cli import _stamped_manifest_files
|
||||
_corpus = detect.get('all_files') or detect['files']
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'))
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH))
|
||||
_sem_types = ('document', 'paper', 'image')
|
||||
_dispatched = {f for t, fl in detect['files'].items() if t in _sem_types for f in fl}
|
||||
_stamped = {f for fl in _manifest_files.values() for f in fl}
|
||||
_cleared = _dispatched - _stamped
|
||||
_scan = {f for fl in _corpus.values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
|
||||
# Update cumulative cost tracker
|
||||
input_tok = extract.get('input_tokens', 0)
|
||||
@@ -798,7 +806,8 @@ from pathlib import Path
|
||||
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
new_total = result.get('new_total', 0)
|
||||
print(json.dumps(result, indent=2))
|
||||
Path('.graphify_incremental.json').write_text(json.dumps(result))
|
||||
@@ -1091,6 +1100,8 @@ print(output)
|
||||
|
||||
Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above.
|
||||
|
||||
**Bypass check (hub/bridge questions only, #4426).** If the question is about why a node bridges communities or has unusually many edges (a hub/god node), the neighbour listing above only shows code that already has an edge to it — it cannot show code that does the hub's job without ever calling it. Before finalizing the answer: pick one or two literal, distinctive things the hub does (a hard-coded constant it wraps, a specific string it returns, the exact computation in its body), then grep the corpus for that literal text in files that have no edge to the hub node in the subgraph above. Report any hits separately, labeled "Bypasses", distinct from the normal neighbour list — each is a file that reimplements the hub instead of using it. Also check whether the hub's own community label names a different node: a shared utility is often clustered into its heaviest consumer's community, so the label can read as if that consumer were the bridge. If so, say so plainly in the answer rather than letting the label stand unquestioned.
|
||||
|
||||
After writing the answer, save it back into the graph so it improves future queries:
|
||||
|
||||
```bash
|
||||
|
||||
+34
-20
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
|
||||
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
|
||||
/graphify <path> --update # incremental - re-extract only new/changed files
|
||||
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
|
||||
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
|
||||
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
|
||||
/graphify <path> --cluster-only # rerun clustering on existing graph
|
||||
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
|
||||
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
|
||||
|
||||
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
|
||||
|
||||
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
|
||||
|
||||
## What You Must Do When Invoked
|
||||
|
||||
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
|
||||
@@ -56,7 +61,7 @@ If no path was given, use `.` (current directory). Do not ask the user for a pat
|
||||
|
||||
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.
|
||||
|
||||
Follow these steps in order. Do not skip steps.
|
||||
Follow these steps in order unless the fast path above applies.
|
||||
|
||||
### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths)
|
||||
|
||||
@@ -119,7 +124,8 @@ from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
# Write the sidecar from Python, not a shell redirect, so the same block renders
|
||||
# on PowerShell hosts without console-encoding drift (#2528).
|
||||
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
|
||||
@@ -127,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
|
||||
"
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
|
||||
```
|
||||
Corpus: X files · ~Y words
|
||||
@@ -188,6 +194,7 @@ import json
|
||||
|
||||
code_files = []
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
for f in detect.get('files', {}).get('code', []):
|
||||
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
|
||||
|
||||
@@ -195,7 +202,7 @@ if code_files:
|
||||
# root= anchors node ids and source_file on the scan root; cache_root only says
|
||||
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
|
||||
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
|
||||
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
|
||||
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
|
||||
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
|
||||
else:
|
||||
@@ -242,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
|
||||
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
|
||||
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
|
||||
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
|
||||
|
||||
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
|
||||
# run so Part C never merges a stale .graphify_cached.json (#1392).
|
||||
@@ -309,6 +317,7 @@ $(cat graphify-out/.graphify_python) -c "
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
covered = {}
|
||||
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
|
||||
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
|
||||
@@ -319,7 +328,7 @@ partial = []
|
||||
for src, n in sorted(covered.items()):
|
||||
p = Path(src)
|
||||
if not p.is_absolute():
|
||||
p = Path('INPUT_PATH') / src
|
||||
p = Path(INPUT_PATH) / src
|
||||
if not p.is_file():
|
||||
continue
|
||||
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
|
||||
@@ -375,7 +384,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
|
||||
# so the next --update re-dispatches it instead of serving a truncated extraction forever
|
||||
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
|
||||
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
note = f' ({len(partial)} left partial for retry)' if partial else ''
|
||||
print(f'Cached {saved} files' + note)
|
||||
"
|
||||
@@ -461,7 +471,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
|
||||
|
||||
### Step 4 - Build graph, cluster, analyze, generate outputs
|
||||
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Substitute it the same way you substitute `INPUT_PATH` — do not leave the literal `IS_DIRECTED` in the code.
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
|
||||
|
||||
```bash
|
||||
mkdir -p graphify-out
|
||||
@@ -476,10 +486,11 @@ from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= mirrors the --update runbook (#1361): relativize source_file to the same
|
||||
# base so the full build and incremental --update never drift apart on re-extract.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
|
||||
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
|
||||
if G.number_of_nodes() == 0:
|
||||
@@ -499,12 +510,12 @@ questions = suggest_questions(G, communities, labels)
|
||||
# nothing) when the new graph is smaller than the existing graph.json. Only write
|
||||
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
|
||||
# they never describe a graph that graph.json doesn't contain (#1392).
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json')
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
|
||||
if not wrote:
|
||||
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
|
||||
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
|
||||
raise SystemExit(1)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
analysis = {
|
||||
'communities': {str(k): v for k, v in communities.items()},
|
||||
@@ -520,7 +531,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
|
||||
|
||||
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
|
||||
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 4.5 - Graph health check (read-only integrity gate)
|
||||
|
||||
@@ -533,7 +544,8 @@ from pathlib import Path
|
||||
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
|
||||
print(format_diagnostic_report(summary))
|
||||
flags = [f'{summary[k]} {label}' for k, label in (
|
||||
('dangling_endpoint_edges', 'dangling-endpoint edges'),
|
||||
@@ -546,7 +558,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
|
||||
"
|
||||
```
|
||||
|
||||
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
|
||||
### Step 5 - Label communities
|
||||
|
||||
@@ -567,9 +579,10 @@ from pathlib import Path
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
|
||||
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
|
||||
@@ -580,7 +593,7 @@ labels = LABELS_DICT
|
||||
# Regenerate questions with real community labels (labels affect question phrasing)
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
|
||||
# Re-export so graph.json nodes carry the curated community_name (#2490).
|
||||
@@ -595,7 +608,7 @@ print('Report updated with community labels')
|
||||
```
|
||||
|
||||
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 6 - Generate Obsidian vault (opt-in) + HTML
|
||||
|
||||
@@ -635,6 +648,7 @@ from graphify.detect import save_manifest
|
||||
# Save manifest for --update
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
|
||||
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
|
||||
# root= relativizes the manifest keys to the scan root (same base as the build),
|
||||
@@ -656,7 +670,7 @@ _corpus = detect.get('all_files') or detect['files']
|
||||
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
|
||||
_pf = Path('graphify-out/.graphify_partial.txt')
|
||||
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
|
||||
# Files dispatched this run (the changed subset) but NOT stamped above still carry
|
||||
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
|
||||
# them instead of reading them as unchanged (#1948).
|
||||
@@ -668,7 +682,7 @@ _cleared = _dispatched - _stamped
|
||||
# files newly excluded since last run are dropped rather than masquerading as
|
||||
# deletions; untouched files' prior rows are still preserved (#1908).
|
||||
_scan = {f for fl in _corpus.values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
|
||||
# Update cumulative cost tracker
|
||||
input_tok = extract.get('input_tokens', 0)
|
||||
@@ -698,7 +712,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
|
||||
|
||||
Tell the user (omit the obsidian line unless --obsidian was given):
|
||||
```
|
||||
|
||||
+34
-20
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
|
||||
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
|
||||
/graphify <path> --update # incremental - re-extract only new/changed files
|
||||
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
|
||||
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
|
||||
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
|
||||
/graphify <path> --cluster-only # rerun clustering on existing graph
|
||||
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
|
||||
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
|
||||
|
||||
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
|
||||
|
||||
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
|
||||
|
||||
## What You Must Do When Invoked
|
||||
|
||||
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
|
||||
@@ -56,7 +61,7 @@ If no path was given, use `.` (current directory). Do not ask the user for a pat
|
||||
|
||||
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.
|
||||
|
||||
Follow these steps in order. Do not skip steps.
|
||||
Follow these steps in order unless the fast path above applies.
|
||||
|
||||
### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths)
|
||||
|
||||
@@ -119,7 +124,8 @@ from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
# Write the sidecar from Python, not a shell redirect, so the same block renders
|
||||
# on PowerShell hosts without console-encoding drift (#2528).
|
||||
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
|
||||
@@ -127,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
|
||||
"
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
|
||||
```
|
||||
Corpus: X files · ~Y words
|
||||
@@ -188,6 +194,7 @@ import json
|
||||
|
||||
code_files = []
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
for f in detect.get('files', {}).get('code', []):
|
||||
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
|
||||
|
||||
@@ -195,7 +202,7 @@ if code_files:
|
||||
# root= anchors node ids and source_file on the scan root; cache_root only says
|
||||
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
|
||||
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
|
||||
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
|
||||
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
|
||||
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
|
||||
else:
|
||||
@@ -242,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
|
||||
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
|
||||
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
|
||||
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
|
||||
|
||||
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
|
||||
# run so Part C never merges a stale .graphify_cached.json (#1392).
|
||||
@@ -312,6 +320,7 @@ $(cat graphify-out/.graphify_python) -c "
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
covered = {}
|
||||
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
|
||||
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
|
||||
@@ -322,7 +331,7 @@ partial = []
|
||||
for src, n in sorted(covered.items()):
|
||||
p = Path(src)
|
||||
if not p.is_absolute():
|
||||
p = Path('INPUT_PATH') / src
|
||||
p = Path(INPUT_PATH) / src
|
||||
if not p.is_file():
|
||||
continue
|
||||
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
|
||||
@@ -378,7 +387,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
|
||||
# so the next --update re-dispatches it instead of serving a truncated extraction forever
|
||||
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
|
||||
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
note = f' ({len(partial)} left partial for retry)' if partial else ''
|
||||
print(f'Cached {saved} files' + note)
|
||||
"
|
||||
@@ -464,7 +474,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
|
||||
|
||||
### Step 4 - Build graph, cluster, analyze, generate outputs
|
||||
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Substitute it the same way you substitute `INPUT_PATH` — do not leave the literal `IS_DIRECTED` in the code.
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
|
||||
|
||||
```bash
|
||||
mkdir -p graphify-out
|
||||
@@ -479,10 +489,11 @@ from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= mirrors the --update runbook (#1361): relativize source_file to the same
|
||||
# base so the full build and incremental --update never drift apart on re-extract.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
|
||||
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
|
||||
if G.number_of_nodes() == 0:
|
||||
@@ -502,12 +513,12 @@ questions = suggest_questions(G, communities, labels)
|
||||
# nothing) when the new graph is smaller than the existing graph.json. Only write
|
||||
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
|
||||
# they never describe a graph that graph.json doesn't contain (#1392).
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json')
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
|
||||
if not wrote:
|
||||
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
|
||||
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
|
||||
raise SystemExit(1)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
analysis = {
|
||||
'communities': {str(k): v for k, v in communities.items()},
|
||||
@@ -523,7 +534,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
|
||||
|
||||
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
|
||||
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 4.5 - Graph health check (read-only integrity gate)
|
||||
|
||||
@@ -536,7 +547,8 @@ from pathlib import Path
|
||||
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
|
||||
print(format_diagnostic_report(summary))
|
||||
flags = [f'{summary[k]} {label}' for k, label in (
|
||||
('dangling_endpoint_edges', 'dangling-endpoint edges'),
|
||||
@@ -549,7 +561,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
|
||||
"
|
||||
```
|
||||
|
||||
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
|
||||
### Step 5 - Label communities
|
||||
|
||||
@@ -570,9 +582,10 @@ from pathlib import Path
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
|
||||
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
|
||||
@@ -583,7 +596,7 @@ labels = LABELS_DICT
|
||||
# Regenerate questions with real community labels (labels affect question phrasing)
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
|
||||
# Re-export so graph.json nodes carry the curated community_name (#2490).
|
||||
@@ -598,7 +611,7 @@ print('Report updated with community labels')
|
||||
```
|
||||
|
||||
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 6 - Generate Obsidian vault (opt-in) + HTML
|
||||
|
||||
@@ -638,6 +651,7 @@ from graphify.detect import save_manifest
|
||||
# Save manifest for --update
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
|
||||
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
|
||||
# root= relativizes the manifest keys to the scan root (same base as the build),
|
||||
@@ -659,7 +673,7 @@ _corpus = detect.get('all_files') or detect['files']
|
||||
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
|
||||
_pf = Path('graphify-out/.graphify_partial.txt')
|
||||
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
|
||||
# Files dispatched this run (the changed subset) but NOT stamped above still carry
|
||||
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
|
||||
# them instead of reading them as unchanged (#1948).
|
||||
@@ -671,7 +685,7 @@ _cleared = _dispatched - _stamped
|
||||
# files newly excluded since last run are dropped rather than masquerading as
|
||||
# deletions; untouched files' prior rows are still preserved (#1908).
|
||||
_scan = {f for fl in _corpus.values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
|
||||
# Update cumulative cost tracker
|
||||
input_tok = extract.get('input_tokens', 0)
|
||||
@@ -701,7 +715,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
|
||||
|
||||
Tell the user (omit the obsidian line unless --obsidian was given):
|
||||
```
|
||||
|
||||
+34
-20
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
|
||||
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
|
||||
/graphify <path> --update # incremental - re-extract only new/changed files
|
||||
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
|
||||
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
|
||||
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
|
||||
/graphify <path> --cluster-only # rerun clustering on existing graph
|
||||
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
|
||||
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
|
||||
|
||||
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
|
||||
|
||||
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
|
||||
|
||||
## What You Must Do When Invoked
|
||||
|
||||
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
|
||||
@@ -56,7 +61,7 @@ If no path was given, use `.` (current directory). Do not ask the user for a pat
|
||||
|
||||
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.
|
||||
|
||||
Follow these steps in order. Do not skip steps.
|
||||
Follow these steps in order unless the fast path above applies.
|
||||
|
||||
### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths)
|
||||
|
||||
@@ -119,7 +124,8 @@ from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
# Write the sidecar from Python, not a shell redirect, so the same block renders
|
||||
# on PowerShell hosts without console-encoding drift (#2528).
|
||||
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
|
||||
@@ -127,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
|
||||
"
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
|
||||
```
|
||||
Corpus: X files · ~Y words
|
||||
@@ -188,6 +194,7 @@ import json
|
||||
|
||||
code_files = []
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
for f in detect.get('files', {}).get('code', []):
|
||||
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
|
||||
|
||||
@@ -195,7 +202,7 @@ if code_files:
|
||||
# root= anchors node ids and source_file on the scan root; cache_root only says
|
||||
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
|
||||
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
|
||||
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
|
||||
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
|
||||
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
|
||||
else:
|
||||
@@ -242,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
|
||||
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
|
||||
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
|
||||
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
|
||||
|
||||
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
|
||||
# run so Part C never merges a stale .graphify_cached.json (#1392).
|
||||
@@ -313,6 +321,7 @@ $(cat graphify-out/.graphify_python) -c "
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
covered = {}
|
||||
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
|
||||
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
|
||||
@@ -323,7 +332,7 @@ partial = []
|
||||
for src, n in sorted(covered.items()):
|
||||
p = Path(src)
|
||||
if not p.is_absolute():
|
||||
p = Path('INPUT_PATH') / src
|
||||
p = Path(INPUT_PATH) / src
|
||||
if not p.is_file():
|
||||
continue
|
||||
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
|
||||
@@ -379,7 +388,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
|
||||
# so the next --update re-dispatches it instead of serving a truncated extraction forever
|
||||
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
|
||||
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
note = f' ({len(partial)} left partial for retry)' if partial else ''
|
||||
print(f'Cached {saved} files' + note)
|
||||
"
|
||||
@@ -465,7 +475,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
|
||||
|
||||
### Step 4 - Build graph, cluster, analyze, generate outputs
|
||||
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Substitute it the same way you substitute `INPUT_PATH` — do not leave the literal `IS_DIRECTED` in the code.
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
|
||||
|
||||
```bash
|
||||
mkdir -p graphify-out
|
||||
@@ -480,10 +490,11 @@ from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= mirrors the --update runbook (#1361): relativize source_file to the same
|
||||
# base so the full build and incremental --update never drift apart on re-extract.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
|
||||
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
|
||||
if G.number_of_nodes() == 0:
|
||||
@@ -503,12 +514,12 @@ questions = suggest_questions(G, communities, labels)
|
||||
# nothing) when the new graph is smaller than the existing graph.json. Only write
|
||||
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
|
||||
# they never describe a graph that graph.json doesn't contain (#1392).
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json')
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
|
||||
if not wrote:
|
||||
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
|
||||
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
|
||||
raise SystemExit(1)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
analysis = {
|
||||
'communities': {str(k): v for k, v in communities.items()},
|
||||
@@ -524,7 +535,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
|
||||
|
||||
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
|
||||
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 4.5 - Graph health check (read-only integrity gate)
|
||||
|
||||
@@ -537,7 +548,8 @@ from pathlib import Path
|
||||
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
|
||||
print(format_diagnostic_report(summary))
|
||||
flags = [f'{summary[k]} {label}' for k, label in (
|
||||
('dangling_endpoint_edges', 'dangling-endpoint edges'),
|
||||
@@ -550,7 +562,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
|
||||
"
|
||||
```
|
||||
|
||||
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
|
||||
### Step 5 - Label communities
|
||||
|
||||
@@ -571,9 +583,10 @@ from pathlib import Path
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
|
||||
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
|
||||
@@ -584,7 +597,7 @@ labels = LABELS_DICT
|
||||
# Regenerate questions with real community labels (labels affect question phrasing)
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
|
||||
# Re-export so graph.json nodes carry the curated community_name (#2490).
|
||||
@@ -599,7 +612,7 @@ print('Report updated with community labels')
|
||||
```
|
||||
|
||||
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 6 - Generate Obsidian vault (opt-in) + HTML
|
||||
|
||||
@@ -639,6 +652,7 @@ from graphify.detect import save_manifest
|
||||
# Save manifest for --update
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
|
||||
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
|
||||
# root= relativizes the manifest keys to the scan root (same base as the build),
|
||||
@@ -660,7 +674,7 @@ _corpus = detect.get('all_files') or detect['files']
|
||||
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
|
||||
_pf = Path('graphify-out/.graphify_partial.txt')
|
||||
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
|
||||
# Files dispatched this run (the changed subset) but NOT stamped above still carry
|
||||
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
|
||||
# them instead of reading them as unchanged (#1948).
|
||||
@@ -672,7 +686,7 @@ _cleared = _dispatched - _stamped
|
||||
# files newly excluded since last run are dropped rather than masquerading as
|
||||
# deletions; untouched files' prior rows are still preserved (#1908).
|
||||
_scan = {f for fl in _corpus.values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
|
||||
# Update cumulative cost tracker
|
||||
input_tok = extract.get('input_tokens', 0)
|
||||
@@ -702,7 +716,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
|
||||
|
||||
Tell the user (omit the obsidian line unless --obsidian was given):
|
||||
```
|
||||
|
||||
+34
-20
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
|
||||
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
|
||||
/graphify <path> --update # incremental - re-extract only new/changed files
|
||||
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
|
||||
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
|
||||
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
|
||||
/graphify <path> --cluster-only # rerun clustering on existing graph
|
||||
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
|
||||
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
|
||||
|
||||
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
|
||||
|
||||
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
|
||||
|
||||
## What You Must Do When Invoked
|
||||
|
||||
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
|
||||
@@ -56,7 +61,7 @@ If no path was given, use `.` (current directory). Do not ask the user for a pat
|
||||
|
||||
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.
|
||||
|
||||
Follow these steps in order. Do not skip steps.
|
||||
Follow these steps in order unless the fast path above applies.
|
||||
|
||||
### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths)
|
||||
|
||||
@@ -119,7 +124,8 @@ from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
# Write the sidecar from Python, not a shell redirect, so the same block renders
|
||||
# on PowerShell hosts without console-encoding drift (#2528).
|
||||
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
|
||||
@@ -127,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
|
||||
"
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
|
||||
```
|
||||
Corpus: X files · ~Y words
|
||||
@@ -188,6 +194,7 @@ import json
|
||||
|
||||
code_files = []
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
for f in detect.get('files', {}).get('code', []):
|
||||
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
|
||||
|
||||
@@ -195,7 +202,7 @@ if code_files:
|
||||
# root= anchors node ids and source_file on the scan root; cache_root only says
|
||||
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
|
||||
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
|
||||
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
|
||||
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
|
||||
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
|
||||
else:
|
||||
@@ -242,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
|
||||
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
|
||||
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
|
||||
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
|
||||
|
||||
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
|
||||
# run so Part C never merges a stale .graphify_cached.json (#1392).
|
||||
@@ -312,6 +320,7 @@ $(cat graphify-out/.graphify_python) -c "
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
covered = {}
|
||||
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
|
||||
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
|
||||
@@ -322,7 +331,7 @@ partial = []
|
||||
for src, n in sorted(covered.items()):
|
||||
p = Path(src)
|
||||
if not p.is_absolute():
|
||||
p = Path('INPUT_PATH') / src
|
||||
p = Path(INPUT_PATH) / src
|
||||
if not p.is_file():
|
||||
continue
|
||||
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
|
||||
@@ -378,7 +387,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
|
||||
# so the next --update re-dispatches it instead of serving a truncated extraction forever
|
||||
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
|
||||
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
note = f' ({len(partial)} left partial for retry)' if partial else ''
|
||||
print(f'Cached {saved} files' + note)
|
||||
"
|
||||
@@ -464,7 +474,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
|
||||
|
||||
### Step 4 - Build graph, cluster, analyze, generate outputs
|
||||
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Substitute it the same way you substitute `INPUT_PATH` — do not leave the literal `IS_DIRECTED` in the code.
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
|
||||
|
||||
```bash
|
||||
mkdir -p graphify-out
|
||||
@@ -479,10 +489,11 @@ from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= mirrors the --update runbook (#1361): relativize source_file to the same
|
||||
# base so the full build and incremental --update never drift apart on re-extract.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
|
||||
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
|
||||
if G.number_of_nodes() == 0:
|
||||
@@ -502,12 +513,12 @@ questions = suggest_questions(G, communities, labels)
|
||||
# nothing) when the new graph is smaller than the existing graph.json. Only write
|
||||
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
|
||||
# they never describe a graph that graph.json doesn't contain (#1392).
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json')
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
|
||||
if not wrote:
|
||||
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
|
||||
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
|
||||
raise SystemExit(1)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
analysis = {
|
||||
'communities': {str(k): v for k, v in communities.items()},
|
||||
@@ -523,7 +534,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
|
||||
|
||||
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
|
||||
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 4.5 - Graph health check (read-only integrity gate)
|
||||
|
||||
@@ -536,7 +547,8 @@ from pathlib import Path
|
||||
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
|
||||
print(format_diagnostic_report(summary))
|
||||
flags = [f'{summary[k]} {label}' for k, label in (
|
||||
('dangling_endpoint_edges', 'dangling-endpoint edges'),
|
||||
@@ -549,7 +561,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
|
||||
"
|
||||
```
|
||||
|
||||
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
|
||||
### Step 5 - Label communities
|
||||
|
||||
@@ -570,9 +582,10 @@ from pathlib import Path
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
|
||||
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
|
||||
@@ -583,7 +596,7 @@ labels = LABELS_DICT
|
||||
# Regenerate questions with real community labels (labels affect question phrasing)
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
|
||||
# Re-export so graph.json nodes carry the curated community_name (#2490).
|
||||
@@ -598,7 +611,7 @@ print('Report updated with community labels')
|
||||
```
|
||||
|
||||
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 6 - Generate Obsidian vault (opt-in) + HTML
|
||||
|
||||
@@ -638,6 +651,7 @@ from graphify.detect import save_manifest
|
||||
# Save manifest for --update
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
|
||||
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
|
||||
# root= relativizes the manifest keys to the scan root (same base as the build),
|
||||
@@ -659,7 +673,7 @@ _corpus = detect.get('all_files') or detect['files']
|
||||
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
|
||||
_pf = Path('graphify-out/.graphify_partial.txt')
|
||||
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
|
||||
# Files dispatched this run (the changed subset) but NOT stamped above still carry
|
||||
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
|
||||
# them instead of reading them as unchanged (#1948).
|
||||
@@ -671,7 +685,7 @@ _cleared = _dispatched - _stamped
|
||||
# files newly excluded since last run are dropped rather than masquerading as
|
||||
# deletions; untouched files' prior rows are still preserved (#1908).
|
||||
_scan = {f for fl in _corpus.values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
|
||||
# Update cumulative cost tracker
|
||||
input_tok = extract.get('input_tokens', 0)
|
||||
@@ -701,7 +715,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
|
||||
|
||||
Tell the user (omit the obsidian line unless --obsidian was given):
|
||||
```
|
||||
|
||||
+22
-11
@@ -59,13 +59,17 @@ Use it for:
|
||||
- A research corpus (citation graph + concept graph in one)
|
||||
- Your personal /raw folder (drop everything in, let it grow, query it)
|
||||
|
||||
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
|
||||
|
||||
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
|
||||
|
||||
## What You Must Do When Invoked
|
||||
|
||||
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
|
||||
|
||||
If no path was given, use `.` (current directory). Do not ask the user for a path.
|
||||
|
||||
Follow these steps in order. Do not skip steps.
|
||||
Follow these steps in order unless the fast path above applies.
|
||||
|
||||
### Step 1 - Ensure graphify is installed
|
||||
|
||||
@@ -126,12 +130,13 @@ from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
print(json.dumps(result))
|
||||
" > graphify-out/.graphify_detect.json
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
|
||||
```
|
||||
Corpus: X files · ~Y words
|
||||
@@ -482,7 +487,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
|
||||
|
||||
### Step 4 - Build graph, cluster, analyze, generate outputs
|
||||
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source->target), otherwise `False` (the default undirected `Graph`). Substitute it everywhere it appears, the same way you substitute `INPUT_PATH` - do not leave the literal `IS_DIRECTED` in the code.
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source->target), otherwise `False` (the default undirected `Graph`). Substitute it everywhere it appears - do not leave the literal `IS_DIRECTED` in the code. INPUT_PATH is not substituted - each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
|
||||
|
||||
```bash
|
||||
mkdir -p graphify-out
|
||||
@@ -497,6 +502,7 @@ from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
G = build_from_json(extraction, directed=IS_DIRECTED)
|
||||
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
|
||||
@@ -521,7 +527,7 @@ wrote = to_json(G, communities, 'graphify-out/graph.json')
|
||||
if not wrote:
|
||||
print('ERROR: refused to shrink graphify-out/graph.json (fewer nodes than the existing graph). Run a full rebuild to be safe.')
|
||||
raise SystemExit(1)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
|
||||
|
||||
analysis = {
|
||||
@@ -538,7 +544,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
|
||||
|
||||
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
|
||||
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 5 - Label communities
|
||||
|
||||
@@ -571,7 +577,8 @@ labels = LABELS_DICT
|
||||
# Regenerate questions with real community labels (labels affect question phrasing)
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
|
||||
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}))
|
||||
# Re-export so graph.json nodes carry the curated community_name (#2490).
|
||||
@@ -585,7 +592,7 @@ print('Report updated with community labels')
|
||||
```
|
||||
|
||||
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 6 - Generate Obsidian vault (opt-in) + HTML
|
||||
|
||||
@@ -833,16 +840,17 @@ from graphify.detect import save_manifest
|
||||
# Save manifest for --update
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
# Stamp only semantic files that produced output so a failed chunk is re-queued next run, not lost (#2015).
|
||||
from graphify.cli import _stamped_manifest_files
|
||||
_corpus = detect.get('all_files') or detect['files']
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'))
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH))
|
||||
_sem_types = ('document', 'paper', 'image')
|
||||
_dispatched = {f for t, fl in detect['files'].items() if t in _sem_types for f in fl}
|
||||
_stamped = {f for fl in _manifest_files.values() for f in fl}
|
||||
_cleared = _dispatched - _stamped
|
||||
_scan = {f for fl in _corpus.values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
|
||||
# Update cumulative cost tracker
|
||||
input_tok = extract.get('input_tokens', 0)
|
||||
@@ -937,7 +945,8 @@ from pathlib import Path
|
||||
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
new_total = result.get('new_total', 0)
|
||||
print(json.dumps(result, indent=2))
|
||||
Path('graphify-out/.graphify_incremental.json').write_text(json.dumps(result))
|
||||
@@ -1227,6 +1236,8 @@ print(output)
|
||||
|
||||
Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above.
|
||||
|
||||
**Bypass check (hub/bridge questions only, #4426).** If the question is about why a node bridges communities or has unusually many edges (a hub/god node), the neighbour listing above only shows code that already has an edge to it — it cannot show code that does the hub's job without ever calling it. Before finalizing the answer: pick one or two literal, distinctive things the hub does (a hard-coded constant it wraps, a specific string it returns, the exact computation in its body), then grep the corpus for that literal text in files that have no edge to the hub node in the subgraph above. Report any hits separately, labeled "Bypasses", distinct from the normal neighbour list — each is a file that reimplements the hub instead of using it. Also check whether the hub's own community label names a different node: a shared utility is often clustered into its heaviest consumer's community, so the label can read as if that consumer were the bridge. If so, say so plainly in the answer rather than letting the label stand unquestioned.
|
||||
|
||||
After writing the answer, save it back into the graph so it improves future queries:
|
||||
|
||||
```bash
|
||||
|
||||
+34
-20
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
|
||||
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
|
||||
/graphify <path> --update # incremental - re-extract only new/changed files
|
||||
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
|
||||
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
|
||||
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
|
||||
/graphify <path> --cluster-only # rerun clustering on existing graph
|
||||
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
|
||||
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
|
||||
|
||||
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
|
||||
|
||||
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
|
||||
|
||||
## What You Must Do When Invoked
|
||||
|
||||
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
|
||||
@@ -56,7 +61,7 @@ If no path was given, use `.` (current directory). Do not ask the user for a pat
|
||||
|
||||
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.
|
||||
|
||||
Follow these steps in order. Do not skip steps.
|
||||
Follow these steps in order unless the fast path above applies.
|
||||
|
||||
### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths)
|
||||
|
||||
@@ -119,7 +124,8 @@ from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
# Write the sidecar from Python, not a shell redirect, so the same block renders
|
||||
# on PowerShell hosts without console-encoding drift (#2528).
|
||||
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
|
||||
@@ -127,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
|
||||
"
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
|
||||
```
|
||||
Corpus: X files · ~Y words
|
||||
@@ -188,6 +194,7 @@ import json
|
||||
|
||||
code_files = []
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
for f in detect.get('files', {}).get('code', []):
|
||||
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
|
||||
|
||||
@@ -195,7 +202,7 @@ if code_files:
|
||||
# root= anchors node ids and source_file on the scan root; cache_root only says
|
||||
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
|
||||
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
|
||||
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
|
||||
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
|
||||
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
|
||||
else:
|
||||
@@ -242,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
|
||||
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
|
||||
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
|
||||
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
|
||||
|
||||
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
|
||||
# run so Part C never merges a stale .graphify_cached.json (#1392).
|
||||
@@ -309,6 +317,7 @@ $(cat graphify-out/.graphify_python) -c "
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
covered = {}
|
||||
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
|
||||
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
|
||||
@@ -319,7 +328,7 @@ partial = []
|
||||
for src, n in sorted(covered.items()):
|
||||
p = Path(src)
|
||||
if not p.is_absolute():
|
||||
p = Path('INPUT_PATH') / src
|
||||
p = Path(INPUT_PATH) / src
|
||||
if not p.is_file():
|
||||
continue
|
||||
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
|
||||
@@ -375,7 +384,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
|
||||
# so the next --update re-dispatches it instead of serving a truncated extraction forever
|
||||
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
|
||||
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
note = f' ({len(partial)} left partial for retry)' if partial else ''
|
||||
print(f'Cached {saved} files' + note)
|
||||
"
|
||||
@@ -461,7 +471,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
|
||||
|
||||
### Step 4 - Build graph, cluster, analyze, generate outputs
|
||||
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Substitute it the same way you substitute `INPUT_PATH` — do not leave the literal `IS_DIRECTED` in the code.
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
|
||||
|
||||
```bash
|
||||
mkdir -p graphify-out
|
||||
@@ -476,10 +486,11 @@ from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= mirrors the --update runbook (#1361): relativize source_file to the same
|
||||
# base so the full build and incremental --update never drift apart on re-extract.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
|
||||
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
|
||||
if G.number_of_nodes() == 0:
|
||||
@@ -499,12 +510,12 @@ questions = suggest_questions(G, communities, labels)
|
||||
# nothing) when the new graph is smaller than the existing graph.json. Only write
|
||||
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
|
||||
# they never describe a graph that graph.json doesn't contain (#1392).
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json')
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
|
||||
if not wrote:
|
||||
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
|
||||
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
|
||||
raise SystemExit(1)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
analysis = {
|
||||
'communities': {str(k): v for k, v in communities.items()},
|
||||
@@ -520,7 +531,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
|
||||
|
||||
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
|
||||
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 4.5 - Graph health check (read-only integrity gate)
|
||||
|
||||
@@ -533,7 +544,8 @@ from pathlib import Path
|
||||
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
|
||||
print(format_diagnostic_report(summary))
|
||||
flags = [f'{summary[k]} {label}' for k, label in (
|
||||
('dangling_endpoint_edges', 'dangling-endpoint edges'),
|
||||
@@ -546,7 +558,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
|
||||
"
|
||||
```
|
||||
|
||||
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
|
||||
### Step 5 - Label communities
|
||||
|
||||
@@ -567,9 +579,10 @@ from pathlib import Path
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
|
||||
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
|
||||
@@ -580,7 +593,7 @@ labels = LABELS_DICT
|
||||
# Regenerate questions with real community labels (labels affect question phrasing)
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
|
||||
# Re-export so graph.json nodes carry the curated community_name (#2490).
|
||||
@@ -595,7 +608,7 @@ print('Report updated with community labels')
|
||||
```
|
||||
|
||||
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 6 - Generate Obsidian vault (opt-in) + HTML
|
||||
|
||||
@@ -635,6 +648,7 @@ from graphify.detect import save_manifest
|
||||
# Save manifest for --update
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
|
||||
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
|
||||
# root= relativizes the manifest keys to the scan root (same base as the build),
|
||||
@@ -656,7 +670,7 @@ _corpus = detect.get('all_files') or detect['files']
|
||||
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
|
||||
_pf = Path('graphify-out/.graphify_partial.txt')
|
||||
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
|
||||
# Files dispatched this run (the changed subset) but NOT stamped above still carry
|
||||
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
|
||||
# them instead of reading them as unchanged (#1948).
|
||||
@@ -668,7 +682,7 @@ _cleared = _dispatched - _stamped
|
||||
# files newly excluded since last run are dropped rather than masquerading as
|
||||
# deletions; untouched files' prior rows are still preserved (#1908).
|
||||
_scan = {f for fl in _corpus.values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
|
||||
# Update cumulative cost tracker
|
||||
input_tok = extract.get('input_tokens', 0)
|
||||
@@ -698,7 +712,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
|
||||
|
||||
Tell the user (omit the obsidian line unless --obsidian was given):
|
||||
```
|
||||
|
||||
+34
-20
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
|
||||
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
|
||||
/graphify <path> --update # incremental - re-extract only new/changed files
|
||||
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
|
||||
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
|
||||
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
|
||||
/graphify <path> --cluster-only # rerun clustering on existing graph
|
||||
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
|
||||
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
|
||||
|
||||
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
|
||||
|
||||
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
|
||||
|
||||
## What You Must Do When Invoked
|
||||
|
||||
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
|
||||
@@ -56,7 +61,7 @@ If no path was given, use `.` (current directory). Do not ask the user for a pat
|
||||
|
||||
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.
|
||||
|
||||
Follow these steps in order. Do not skip steps.
|
||||
Follow these steps in order unless the fast path above applies.
|
||||
|
||||
### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths)
|
||||
|
||||
@@ -119,7 +124,8 @@ from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
# Write the sidecar from Python, not a shell redirect, so the same block renders
|
||||
# on PowerShell hosts without console-encoding drift (#2528).
|
||||
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
|
||||
@@ -127,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
|
||||
"
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
|
||||
```
|
||||
Corpus: X files · ~Y words
|
||||
@@ -188,6 +194,7 @@ import json
|
||||
|
||||
code_files = []
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
for f in detect.get('files', {}).get('code', []):
|
||||
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
|
||||
|
||||
@@ -195,7 +202,7 @@ if code_files:
|
||||
# root= anchors node ids and source_file on the scan root; cache_root only says
|
||||
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
|
||||
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
|
||||
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
|
||||
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
|
||||
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
|
||||
else:
|
||||
@@ -242,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
|
||||
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
|
||||
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
|
||||
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
|
||||
|
||||
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
|
||||
# run so Part C never merges a stale .graphify_cached.json (#1392).
|
||||
@@ -312,6 +320,7 @@ $(cat graphify-out/.graphify_python) -c "
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
covered = {}
|
||||
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
|
||||
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
|
||||
@@ -322,7 +331,7 @@ partial = []
|
||||
for src, n in sorted(covered.items()):
|
||||
p = Path(src)
|
||||
if not p.is_absolute():
|
||||
p = Path('INPUT_PATH') / src
|
||||
p = Path(INPUT_PATH) / src
|
||||
if not p.is_file():
|
||||
continue
|
||||
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
|
||||
@@ -378,7 +387,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
|
||||
# so the next --update re-dispatches it instead of serving a truncated extraction forever
|
||||
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
|
||||
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
note = f' ({len(partial)} left partial for retry)' if partial else ''
|
||||
print(f'Cached {saved} files' + note)
|
||||
"
|
||||
@@ -464,7 +474,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
|
||||
|
||||
### Step 4 - Build graph, cluster, analyze, generate outputs
|
||||
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Substitute it the same way you substitute `INPUT_PATH` — do not leave the literal `IS_DIRECTED` in the code.
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
|
||||
|
||||
```bash
|
||||
mkdir -p graphify-out
|
||||
@@ -479,10 +489,11 @@ from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= mirrors the --update runbook (#1361): relativize source_file to the same
|
||||
# base so the full build and incremental --update never drift apart on re-extract.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
|
||||
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
|
||||
if G.number_of_nodes() == 0:
|
||||
@@ -502,12 +513,12 @@ questions = suggest_questions(G, communities, labels)
|
||||
# nothing) when the new graph is smaller than the existing graph.json. Only write
|
||||
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
|
||||
# they never describe a graph that graph.json doesn't contain (#1392).
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json')
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
|
||||
if not wrote:
|
||||
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
|
||||
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
|
||||
raise SystemExit(1)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
analysis = {
|
||||
'communities': {str(k): v for k, v in communities.items()},
|
||||
@@ -523,7 +534,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
|
||||
|
||||
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
|
||||
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 4.5 - Graph health check (read-only integrity gate)
|
||||
|
||||
@@ -536,7 +547,8 @@ from pathlib import Path
|
||||
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
|
||||
print(format_diagnostic_report(summary))
|
||||
flags = [f'{summary[k]} {label}' for k, label in (
|
||||
('dangling_endpoint_edges', 'dangling-endpoint edges'),
|
||||
@@ -549,7 +561,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
|
||||
"
|
||||
```
|
||||
|
||||
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
|
||||
### Step 5 - Label communities
|
||||
|
||||
@@ -570,9 +582,10 @@ from pathlib import Path
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
|
||||
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
|
||||
@@ -583,7 +596,7 @@ labels = LABELS_DICT
|
||||
# Regenerate questions with real community labels (labels affect question phrasing)
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
|
||||
# Re-export so graph.json nodes carry the curated community_name (#2490).
|
||||
@@ -598,7 +611,7 @@ print('Report updated with community labels')
|
||||
```
|
||||
|
||||
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 6 - Generate Obsidian vault (opt-in) + HTML
|
||||
|
||||
@@ -638,6 +651,7 @@ from graphify.detect import save_manifest
|
||||
# Save manifest for --update
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
|
||||
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
|
||||
# root= relativizes the manifest keys to the scan root (same base as the build),
|
||||
@@ -659,7 +673,7 @@ _corpus = detect.get('all_files') or detect['files']
|
||||
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
|
||||
_pf = Path('graphify-out/.graphify_partial.txt')
|
||||
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
|
||||
# Files dispatched this run (the changed subset) but NOT stamped above still carry
|
||||
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
|
||||
# them instead of reading them as unchanged (#1948).
|
||||
@@ -671,7 +685,7 @@ _cleared = _dispatched - _stamped
|
||||
# files newly excluded since last run are dropped rather than masquerading as
|
||||
# deletions; untouched files' prior rows are still preserved (#1908).
|
||||
_scan = {f for fl in _corpus.values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
|
||||
# Update cumulative cost tracker
|
||||
input_tok = extract.get('input_tokens', 0)
|
||||
@@ -701,7 +715,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
|
||||
|
||||
Tell the user (omit the obsidian line unless --obsidian was given):
|
||||
```
|
||||
|
||||
+34
-20
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
|
||||
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
|
||||
/graphify <path> --update # incremental - re-extract only new/changed files
|
||||
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
|
||||
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
|
||||
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
|
||||
/graphify <path> --cluster-only # rerun clustering on existing graph
|
||||
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
|
||||
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
|
||||
|
||||
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
|
||||
|
||||
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
|
||||
|
||||
## What You Must Do When Invoked
|
||||
|
||||
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
|
||||
@@ -56,7 +61,7 @@ If no path was given, use `.` (current directory). Do not ask the user for a pat
|
||||
|
||||
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.
|
||||
|
||||
Follow these steps in order. Do not skip steps.
|
||||
Follow these steps in order unless the fast path above applies.
|
||||
|
||||
### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths)
|
||||
|
||||
@@ -119,7 +124,8 @@ from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
# Write the sidecar from Python, not a shell redirect, so the same block renders
|
||||
# on PowerShell hosts without console-encoding drift (#2528).
|
||||
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
|
||||
@@ -127,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
|
||||
"
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
|
||||
```
|
||||
Corpus: X files · ~Y words
|
||||
@@ -188,6 +194,7 @@ import json
|
||||
|
||||
code_files = []
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
for f in detect.get('files', {}).get('code', []):
|
||||
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
|
||||
|
||||
@@ -195,7 +202,7 @@ if code_files:
|
||||
# root= anchors node ids and source_file on the scan root; cache_root only says
|
||||
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
|
||||
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
|
||||
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
|
||||
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
|
||||
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
|
||||
else:
|
||||
@@ -242,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
|
||||
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
|
||||
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
|
||||
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
|
||||
|
||||
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
|
||||
# run so Part C never merges a stale .graphify_cached.json (#1392).
|
||||
@@ -312,6 +320,7 @@ $(cat graphify-out/.graphify_python) -c "
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
covered = {}
|
||||
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
|
||||
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
|
||||
@@ -322,7 +331,7 @@ partial = []
|
||||
for src, n in sorted(covered.items()):
|
||||
p = Path(src)
|
||||
if not p.is_absolute():
|
||||
p = Path('INPUT_PATH') / src
|
||||
p = Path(INPUT_PATH) / src
|
||||
if not p.is_file():
|
||||
continue
|
||||
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
|
||||
@@ -378,7 +387,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
|
||||
# so the next --update re-dispatches it instead of serving a truncated extraction forever
|
||||
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
|
||||
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
note = f' ({len(partial)} left partial for retry)' if partial else ''
|
||||
print(f'Cached {saved} files' + note)
|
||||
"
|
||||
@@ -464,7 +474,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
|
||||
|
||||
### Step 4 - Build graph, cluster, analyze, generate outputs
|
||||
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Substitute it the same way you substitute `INPUT_PATH` — do not leave the literal `IS_DIRECTED` in the code.
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
|
||||
|
||||
```bash
|
||||
mkdir -p graphify-out
|
||||
@@ -479,10 +489,11 @@ from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= mirrors the --update runbook (#1361): relativize source_file to the same
|
||||
# base so the full build and incremental --update never drift apart on re-extract.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
|
||||
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
|
||||
if G.number_of_nodes() == 0:
|
||||
@@ -502,12 +513,12 @@ questions = suggest_questions(G, communities, labels)
|
||||
# nothing) when the new graph is smaller than the existing graph.json. Only write
|
||||
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
|
||||
# they never describe a graph that graph.json doesn't contain (#1392).
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json')
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
|
||||
if not wrote:
|
||||
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
|
||||
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
|
||||
raise SystemExit(1)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
analysis = {
|
||||
'communities': {str(k): v for k, v in communities.items()},
|
||||
@@ -523,7 +534,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
|
||||
|
||||
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
|
||||
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 4.5 - Graph health check (read-only integrity gate)
|
||||
|
||||
@@ -536,7 +547,8 @@ from pathlib import Path
|
||||
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
|
||||
print(format_diagnostic_report(summary))
|
||||
flags = [f'{summary[k]} {label}' for k, label in (
|
||||
('dangling_endpoint_edges', 'dangling-endpoint edges'),
|
||||
@@ -549,7 +561,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
|
||||
"
|
||||
```
|
||||
|
||||
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
|
||||
### Step 5 - Label communities
|
||||
|
||||
@@ -570,9 +582,10 @@ from pathlib import Path
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
|
||||
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
|
||||
@@ -583,7 +596,7 @@ labels = LABELS_DICT
|
||||
# Regenerate questions with real community labels (labels affect question phrasing)
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
|
||||
# Re-export so graph.json nodes carry the curated community_name (#2490).
|
||||
@@ -598,7 +611,7 @@ print('Report updated with community labels')
|
||||
```
|
||||
|
||||
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 6 - Generate Obsidian vault (opt-in) + HTML
|
||||
|
||||
@@ -638,6 +651,7 @@ from graphify.detect import save_manifest
|
||||
# Save manifest for --update
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
|
||||
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
|
||||
# root= relativizes the manifest keys to the scan root (same base as the build),
|
||||
@@ -659,7 +673,7 @@ _corpus = detect.get('all_files') or detect['files']
|
||||
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
|
||||
_pf = Path('graphify-out/.graphify_partial.txt')
|
||||
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
|
||||
# Files dispatched this run (the changed subset) but NOT stamped above still carry
|
||||
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
|
||||
# them instead of reading them as unchanged (#1948).
|
||||
@@ -671,7 +685,7 @@ _cleared = _dispatched - _stamped
|
||||
# files newly excluded since last run are dropped rather than masquerading as
|
||||
# deletions; untouched files' prior rows are still preserved (#1908).
|
||||
_scan = {f for fl in _corpus.values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
|
||||
# Update cumulative cost tracker
|
||||
input_tok = extract.get('input_tokens', 0)
|
||||
@@ -701,7 +715,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
|
||||
|
||||
Tell the user (omit the obsidian line unless --obsidian was given):
|
||||
```
|
||||
|
||||
+34
-20
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
|
||||
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
|
||||
/graphify <path> --update # incremental - re-extract only new/changed files
|
||||
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
|
||||
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
|
||||
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
|
||||
/graphify <path> --cluster-only # rerun clustering on existing graph
|
||||
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
|
||||
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
|
||||
|
||||
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
|
||||
|
||||
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
|
||||
|
||||
## What You Must Do When Invoked
|
||||
|
||||
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
|
||||
@@ -56,7 +61,7 @@ If no path was given, use `.` (current directory). Do not ask the user for a pat
|
||||
|
||||
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.
|
||||
|
||||
Follow these steps in order. Do not skip steps.
|
||||
Follow these steps in order unless the fast path above applies.
|
||||
|
||||
### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths)
|
||||
|
||||
@@ -119,7 +124,8 @@ from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
# Write the sidecar from Python, not a shell redirect, so the same block renders
|
||||
# on PowerShell hosts without console-encoding drift (#2528).
|
||||
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
|
||||
@@ -127,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
|
||||
"
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
|
||||
```
|
||||
Corpus: X files · ~Y words
|
||||
@@ -188,6 +194,7 @@ import json
|
||||
|
||||
code_files = []
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
for f in detect.get('files', {}).get('code', []):
|
||||
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
|
||||
|
||||
@@ -195,7 +202,7 @@ if code_files:
|
||||
# root= anchors node ids and source_file on the scan root; cache_root only says
|
||||
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
|
||||
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
|
||||
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
|
||||
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
|
||||
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
|
||||
else:
|
||||
@@ -242,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
|
||||
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
|
||||
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
|
||||
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
|
||||
|
||||
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
|
||||
# run so Part C never merges a stale .graphify_cached.json (#1392).
|
||||
@@ -304,6 +312,7 @@ $(cat graphify-out/.graphify_python) -c "
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
covered = {}
|
||||
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
|
||||
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
|
||||
@@ -314,7 +323,7 @@ partial = []
|
||||
for src, n in sorted(covered.items()):
|
||||
p = Path(src)
|
||||
if not p.is_absolute():
|
||||
p = Path('INPUT_PATH') / src
|
||||
p = Path(INPUT_PATH) / src
|
||||
if not p.is_file():
|
||||
continue
|
||||
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
|
||||
@@ -370,7 +379,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
|
||||
# so the next --update re-dispatches it instead of serving a truncated extraction forever
|
||||
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
|
||||
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
note = f' ({len(partial)} left partial for retry)' if partial else ''
|
||||
print(f'Cached {saved} files' + note)
|
||||
"
|
||||
@@ -456,7 +466,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
|
||||
|
||||
### Step 4 - Build graph, cluster, analyze, generate outputs
|
||||
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Substitute it the same way you substitute `INPUT_PATH` — do not leave the literal `IS_DIRECTED` in the code.
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
|
||||
|
||||
```bash
|
||||
mkdir -p graphify-out
|
||||
@@ -471,10 +481,11 @@ from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= mirrors the --update runbook (#1361): relativize source_file to the same
|
||||
# base so the full build and incremental --update never drift apart on re-extract.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
|
||||
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
|
||||
if G.number_of_nodes() == 0:
|
||||
@@ -494,12 +505,12 @@ questions = suggest_questions(G, communities, labels)
|
||||
# nothing) when the new graph is smaller than the existing graph.json. Only write
|
||||
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
|
||||
# they never describe a graph that graph.json doesn't contain (#1392).
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json')
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
|
||||
if not wrote:
|
||||
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
|
||||
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
|
||||
raise SystemExit(1)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
analysis = {
|
||||
'communities': {str(k): v for k, v in communities.items()},
|
||||
@@ -515,7 +526,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
|
||||
|
||||
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
|
||||
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 4.5 - Graph health check (read-only integrity gate)
|
||||
|
||||
@@ -528,7 +539,8 @@ from pathlib import Path
|
||||
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
|
||||
print(format_diagnostic_report(summary))
|
||||
flags = [f'{summary[k]} {label}' for k, label in (
|
||||
('dangling_endpoint_edges', 'dangling-endpoint edges'),
|
||||
@@ -541,7 +553,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
|
||||
"
|
||||
```
|
||||
|
||||
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
|
||||
### Step 5 - Label communities
|
||||
|
||||
@@ -562,9 +574,10 @@ from pathlib import Path
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
|
||||
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
|
||||
@@ -575,7 +588,7 @@ labels = LABELS_DICT
|
||||
# Regenerate questions with real community labels (labels affect question phrasing)
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
|
||||
# Re-export so graph.json nodes carry the curated community_name (#2490).
|
||||
@@ -590,7 +603,7 @@ print('Report updated with community labels')
|
||||
```
|
||||
|
||||
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 6 - Generate Obsidian vault (opt-in) + HTML
|
||||
|
||||
@@ -630,6 +643,7 @@ from graphify.detect import save_manifest
|
||||
# Save manifest for --update
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
|
||||
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
|
||||
# root= relativizes the manifest keys to the scan root (same base as the build),
|
||||
@@ -651,7 +665,7 @@ _corpus = detect.get('all_files') or detect['files']
|
||||
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
|
||||
_pf = Path('graphify-out/.graphify_partial.txt')
|
||||
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
|
||||
# Files dispatched this run (the changed subset) but NOT stamped above still carry
|
||||
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
|
||||
# them instead of reading them as unchanged (#1948).
|
||||
@@ -663,7 +677,7 @@ _cleared = _dispatched - _stamped
|
||||
# files newly excluded since last run are dropped rather than masquerading as
|
||||
# deletions; untouched files' prior rows are still preserved (#1908).
|
||||
_scan = {f for fl in _corpus.values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
|
||||
# Update cumulative cost tracker
|
||||
input_tok = extract.get('input_tokens', 0)
|
||||
@@ -693,7 +707,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
|
||||
|
||||
Tell the user (omit the obsidian line unless --obsidian was given):
|
||||
```
|
||||
|
||||
+34
-20
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
|
||||
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
|
||||
/graphify <path> --update # incremental - re-extract only new/changed files
|
||||
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
|
||||
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
|
||||
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
|
||||
/graphify <path> --cluster-only # rerun clustering on existing graph
|
||||
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
|
||||
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
|
||||
|
||||
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
|
||||
|
||||
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
|
||||
|
||||
## What You Must Do When Invoked
|
||||
|
||||
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
|
||||
@@ -56,7 +61,7 @@ If no path was given, use `.` (current directory). Do not ask the user for a pat
|
||||
|
||||
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.
|
||||
|
||||
Follow these steps in order. Do not skip steps.
|
||||
Follow these steps in order unless the fast path above applies.
|
||||
|
||||
### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths)
|
||||
|
||||
@@ -119,7 +124,8 @@ from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
# Write the sidecar from Python, not a shell redirect, so the same block renders
|
||||
# on PowerShell hosts without console-encoding drift (#2528).
|
||||
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
|
||||
@@ -127,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
|
||||
"
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
|
||||
```
|
||||
Corpus: X files · ~Y words
|
||||
@@ -188,6 +194,7 @@ import json
|
||||
|
||||
code_files = []
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
for f in detect.get('files', {}).get('code', []):
|
||||
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
|
||||
|
||||
@@ -195,7 +202,7 @@ if code_files:
|
||||
# root= anchors node ids and source_file on the scan root; cache_root only says
|
||||
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
|
||||
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
|
||||
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
|
||||
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
|
||||
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
|
||||
else:
|
||||
@@ -242,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
|
||||
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
|
||||
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
|
||||
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
|
||||
|
||||
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
|
||||
# run so Part C never merges a stale .graphify_cached.json (#1392).
|
||||
@@ -306,6 +314,7 @@ $(cat graphify-out/.graphify_python) -c "
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
covered = {}
|
||||
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
|
||||
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
|
||||
@@ -316,7 +325,7 @@ partial = []
|
||||
for src, n in sorted(covered.items()):
|
||||
p = Path(src)
|
||||
if not p.is_absolute():
|
||||
p = Path('INPUT_PATH') / src
|
||||
p = Path(INPUT_PATH) / src
|
||||
if not p.is_file():
|
||||
continue
|
||||
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
|
||||
@@ -372,7 +381,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
|
||||
# so the next --update re-dispatches it instead of serving a truncated extraction forever
|
||||
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
|
||||
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
note = f' ({len(partial)} left partial for retry)' if partial else ''
|
||||
print(f'Cached {saved} files' + note)
|
||||
"
|
||||
@@ -458,7 +468,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
|
||||
|
||||
### Step 4 - Build graph, cluster, analyze, generate outputs
|
||||
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Substitute it the same way you substitute `INPUT_PATH` — do not leave the literal `IS_DIRECTED` in the code.
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
|
||||
|
||||
```bash
|
||||
mkdir -p graphify-out
|
||||
@@ -473,10 +483,11 @@ from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= mirrors the --update runbook (#1361): relativize source_file to the same
|
||||
# base so the full build and incremental --update never drift apart on re-extract.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
|
||||
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
|
||||
if G.number_of_nodes() == 0:
|
||||
@@ -496,12 +507,12 @@ questions = suggest_questions(G, communities, labels)
|
||||
# nothing) when the new graph is smaller than the existing graph.json. Only write
|
||||
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
|
||||
# they never describe a graph that graph.json doesn't contain (#1392).
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json')
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
|
||||
if not wrote:
|
||||
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
|
||||
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
|
||||
raise SystemExit(1)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
analysis = {
|
||||
'communities': {str(k): v for k, v in communities.items()},
|
||||
@@ -517,7 +528,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
|
||||
|
||||
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
|
||||
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 4.5 - Graph health check (read-only integrity gate)
|
||||
|
||||
@@ -530,7 +541,8 @@ from pathlib import Path
|
||||
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
|
||||
print(format_diagnostic_report(summary))
|
||||
flags = [f'{summary[k]} {label}' for k, label in (
|
||||
('dangling_endpoint_edges', 'dangling-endpoint edges'),
|
||||
@@ -543,7 +555,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
|
||||
"
|
||||
```
|
||||
|
||||
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
|
||||
### Step 5 - Label communities
|
||||
|
||||
@@ -564,9 +576,10 @@ from pathlib import Path
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
|
||||
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
|
||||
@@ -577,7 +590,7 @@ labels = LABELS_DICT
|
||||
# Regenerate questions with real community labels (labels affect question phrasing)
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
|
||||
# Re-export so graph.json nodes carry the curated community_name (#2490).
|
||||
@@ -592,7 +605,7 @@ print('Report updated with community labels')
|
||||
```
|
||||
|
||||
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 6 - Generate Obsidian vault (opt-in) + HTML
|
||||
|
||||
@@ -632,6 +645,7 @@ from graphify.detect import save_manifest
|
||||
# Save manifest for --update
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
|
||||
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
|
||||
# root= relativizes the manifest keys to the scan root (same base as the build),
|
||||
@@ -653,7 +667,7 @@ _corpus = detect.get('all_files') or detect['files']
|
||||
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
|
||||
_pf = Path('graphify-out/.graphify_partial.txt')
|
||||
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
|
||||
# Files dispatched this run (the changed subset) but NOT stamped above still carry
|
||||
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
|
||||
# them instead of reading them as unchanged (#1948).
|
||||
@@ -665,7 +679,7 @@ _cleared = _dispatched - _stamped
|
||||
# files newly excluded since last run are dropped rather than masquerading as
|
||||
# deletions; untouched files' prior rows are still preserved (#1908).
|
||||
_scan = {f for fl in _corpus.values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
|
||||
# Update cumulative cost tracker
|
||||
input_tok = extract.get('input_tokens', 0)
|
||||
@@ -695,7 +709,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
|
||||
|
||||
Tell the user (omit the obsidian line unless --obsidian was given):
|
||||
```
|
||||
|
||||
+34
-20
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
|
||||
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
|
||||
/graphify <path> --update # incremental - re-extract only new/changed files
|
||||
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
|
||||
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
|
||||
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
|
||||
/graphify <path> --cluster-only # rerun clustering on existing graph
|
||||
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
|
||||
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
|
||||
|
||||
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
|
||||
|
||||
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
|
||||
|
||||
## What You Must Do When Invoked
|
||||
|
||||
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
|
||||
@@ -56,7 +61,7 @@ If no path was given, use `.` (current directory). Do not ask the user for a pat
|
||||
|
||||
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.
|
||||
|
||||
Follow these steps in order. Do not skip steps.
|
||||
Follow these steps in order unless the fast path above applies.
|
||||
|
||||
### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths)
|
||||
|
||||
@@ -119,7 +124,8 @@ from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
# Write the sidecar from Python, not a shell redirect, so the same block renders
|
||||
# on PowerShell hosts without console-encoding drift (#2528).
|
||||
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
|
||||
@@ -127,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
|
||||
"
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
|
||||
```
|
||||
Corpus: X files · ~Y words
|
||||
@@ -188,6 +194,7 @@ import json
|
||||
|
||||
code_files = []
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
for f in detect.get('files', {}).get('code', []):
|
||||
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
|
||||
|
||||
@@ -195,7 +202,7 @@ if code_files:
|
||||
# root= anchors node ids and source_file on the scan root; cache_root only says
|
||||
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
|
||||
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
|
||||
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
|
||||
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
|
||||
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
|
||||
else:
|
||||
@@ -242,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
|
||||
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
|
||||
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
|
||||
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
|
||||
|
||||
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
|
||||
# run so Part C never merges a stale .graphify_cached.json (#1392).
|
||||
@@ -310,6 +318,7 @@ $(cat graphify-out/.graphify_python) -c "
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
covered = {}
|
||||
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
|
||||
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
|
||||
@@ -320,7 +329,7 @@ partial = []
|
||||
for src, n in sorted(covered.items()):
|
||||
p = Path(src)
|
||||
if not p.is_absolute():
|
||||
p = Path('INPUT_PATH') / src
|
||||
p = Path(INPUT_PATH) / src
|
||||
if not p.is_file():
|
||||
continue
|
||||
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
|
||||
@@ -376,7 +385,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
|
||||
# so the next --update re-dispatches it instead of serving a truncated extraction forever
|
||||
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
|
||||
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
note = f' ({len(partial)} left partial for retry)' if partial else ''
|
||||
print(f'Cached {saved} files' + note)
|
||||
"
|
||||
@@ -462,7 +472,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
|
||||
|
||||
### Step 4 - Build graph, cluster, analyze, generate outputs
|
||||
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Substitute it the same way you substitute `INPUT_PATH` — do not leave the literal `IS_DIRECTED` in the code.
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
|
||||
|
||||
```bash
|
||||
mkdir -p graphify-out
|
||||
@@ -477,10 +487,11 @@ from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= mirrors the --update runbook (#1361): relativize source_file to the same
|
||||
# base so the full build and incremental --update never drift apart on re-extract.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
|
||||
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
|
||||
if G.number_of_nodes() == 0:
|
||||
@@ -500,12 +511,12 @@ questions = suggest_questions(G, communities, labels)
|
||||
# nothing) when the new graph is smaller than the existing graph.json. Only write
|
||||
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
|
||||
# they never describe a graph that graph.json doesn't contain (#1392).
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json')
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
|
||||
if not wrote:
|
||||
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
|
||||
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
|
||||
raise SystemExit(1)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
analysis = {
|
||||
'communities': {str(k): v for k, v in communities.items()},
|
||||
@@ -521,7 +532,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
|
||||
|
||||
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
|
||||
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 4.5 - Graph health check (read-only integrity gate)
|
||||
|
||||
@@ -534,7 +545,8 @@ from pathlib import Path
|
||||
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
|
||||
print(format_diagnostic_report(summary))
|
||||
flags = [f'{summary[k]} {label}' for k, label in (
|
||||
('dangling_endpoint_edges', 'dangling-endpoint edges'),
|
||||
@@ -547,7 +559,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
|
||||
"
|
||||
```
|
||||
|
||||
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
|
||||
### Step 5 - Label communities
|
||||
|
||||
@@ -568,9 +580,10 @@ from pathlib import Path
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
|
||||
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
|
||||
@@ -581,7 +594,7 @@ labels = LABELS_DICT
|
||||
# Regenerate questions with real community labels (labels affect question phrasing)
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
|
||||
# Re-export so graph.json nodes carry the curated community_name (#2490).
|
||||
@@ -596,7 +609,7 @@ print('Report updated with community labels')
|
||||
```
|
||||
|
||||
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 6 - Generate Obsidian vault (opt-in) + HTML
|
||||
|
||||
@@ -636,6 +649,7 @@ from graphify.detect import save_manifest
|
||||
# Save manifest for --update
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
|
||||
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
|
||||
# root= relativizes the manifest keys to the scan root (same base as the build),
|
||||
@@ -657,7 +671,7 @@ _corpus = detect.get('all_files') or detect['files']
|
||||
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
|
||||
_pf = Path('graphify-out/.graphify_partial.txt')
|
||||
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
|
||||
# Files dispatched this run (the changed subset) but NOT stamped above still carry
|
||||
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
|
||||
# them instead of reading them as unchanged (#1948).
|
||||
@@ -669,7 +683,7 @@ _cleared = _dispatched - _stamped
|
||||
# files newly excluded since last run are dropped rather than masquerading as
|
||||
# deletions; untouched files' prior rows are still preserved (#1908).
|
||||
_scan = {f for fl in _corpus.values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
|
||||
# Update cumulative cost tracker
|
||||
input_tok = extract.get('input_tokens', 0)
|
||||
@@ -699,7 +713,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
|
||||
|
||||
Tell the user (omit the obsidian line unless --obsidian was given):
|
||||
```
|
||||
|
||||
+34
-20
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
|
||||
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
|
||||
/graphify <path> --update # incremental - re-extract only new/changed files
|
||||
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
|
||||
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
|
||||
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
|
||||
/graphify <path> --cluster-only # rerun clustering on existing graph
|
||||
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
|
||||
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
|
||||
|
||||
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
|
||||
|
||||
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
|
||||
|
||||
## What You Must Do When Invoked
|
||||
|
||||
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
|
||||
@@ -56,7 +61,7 @@ If no path was given, use `.` (current directory). Do not ask the user for a pat
|
||||
|
||||
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.
|
||||
|
||||
Follow these steps in order. Do not skip steps.
|
||||
Follow these steps in order unless the fast path above applies.
|
||||
|
||||
### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths)
|
||||
|
||||
@@ -119,7 +124,8 @@ from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
# Write the sidecar from Python, not a shell redirect, so the same block renders
|
||||
# on PowerShell hosts without console-encoding drift (#2528).
|
||||
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
|
||||
@@ -127,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
|
||||
"
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
|
||||
```
|
||||
Corpus: X files · ~Y words
|
||||
@@ -188,6 +194,7 @@ import json
|
||||
|
||||
code_files = []
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
for f in detect.get('files', {}).get('code', []):
|
||||
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
|
||||
|
||||
@@ -195,7 +202,7 @@ if code_files:
|
||||
# root= anchors node ids and source_file on the scan root; cache_root only says
|
||||
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
|
||||
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
|
||||
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
|
||||
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
|
||||
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
|
||||
else:
|
||||
@@ -242,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
|
||||
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
|
||||
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
|
||||
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
|
||||
|
||||
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
|
||||
# run so Part C never merges a stale .graphify_cached.json (#1392).
|
||||
@@ -308,6 +316,7 @@ $(cat graphify-out/.graphify_python) -c "
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
covered = {}
|
||||
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
|
||||
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
|
||||
@@ -318,7 +327,7 @@ partial = []
|
||||
for src, n in sorted(covered.items()):
|
||||
p = Path(src)
|
||||
if not p.is_absolute():
|
||||
p = Path('INPUT_PATH') / src
|
||||
p = Path(INPUT_PATH) / src
|
||||
if not p.is_file():
|
||||
continue
|
||||
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
|
||||
@@ -374,7 +383,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
|
||||
# so the next --update re-dispatches it instead of serving a truncated extraction forever
|
||||
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
|
||||
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
note = f' ({len(partial)} left partial for retry)' if partial else ''
|
||||
print(f'Cached {saved} files' + note)
|
||||
"
|
||||
@@ -460,7 +470,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
|
||||
|
||||
### Step 4 - Build graph, cluster, analyze, generate outputs
|
||||
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Substitute it the same way you substitute `INPUT_PATH` — do not leave the literal `IS_DIRECTED` in the code.
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
|
||||
|
||||
```bash
|
||||
mkdir -p graphify-out
|
||||
@@ -475,10 +485,11 @@ from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= mirrors the --update runbook (#1361): relativize source_file to the same
|
||||
# base so the full build and incremental --update never drift apart on re-extract.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
|
||||
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
|
||||
if G.number_of_nodes() == 0:
|
||||
@@ -498,12 +509,12 @@ questions = suggest_questions(G, communities, labels)
|
||||
# nothing) when the new graph is smaller than the existing graph.json. Only write
|
||||
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
|
||||
# they never describe a graph that graph.json doesn't contain (#1392).
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json')
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
|
||||
if not wrote:
|
||||
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
|
||||
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
|
||||
raise SystemExit(1)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
analysis = {
|
||||
'communities': {str(k): v for k, v in communities.items()},
|
||||
@@ -519,7 +530,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
|
||||
|
||||
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
|
||||
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 4.5 - Graph health check (read-only integrity gate)
|
||||
|
||||
@@ -532,7 +543,8 @@ from pathlib import Path
|
||||
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
|
||||
print(format_diagnostic_report(summary))
|
||||
flags = [f'{summary[k]} {label}' for k, label in (
|
||||
('dangling_endpoint_edges', 'dangling-endpoint edges'),
|
||||
@@ -545,7 +557,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
|
||||
"
|
||||
```
|
||||
|
||||
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
|
||||
### Step 5 - Label communities
|
||||
|
||||
@@ -566,9 +578,10 @@ from pathlib import Path
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
|
||||
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
|
||||
@@ -579,7 +592,7 @@ labels = LABELS_DICT
|
||||
# Regenerate questions with real community labels (labels affect question phrasing)
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
|
||||
# Re-export so graph.json nodes carry the curated community_name (#2490).
|
||||
@@ -594,7 +607,7 @@ print('Report updated with community labels')
|
||||
```
|
||||
|
||||
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 6 - Generate Obsidian vault (opt-in) + HTML
|
||||
|
||||
@@ -634,6 +647,7 @@ from graphify.detect import save_manifest
|
||||
# Save manifest for --update
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
|
||||
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
|
||||
# root= relativizes the manifest keys to the scan root (same base as the build),
|
||||
@@ -655,7 +669,7 @@ _corpus = detect.get('all_files') or detect['files']
|
||||
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
|
||||
_pf = Path('graphify-out/.graphify_partial.txt')
|
||||
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
|
||||
# Files dispatched this run (the changed subset) but NOT stamped above still carry
|
||||
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
|
||||
# them instead of reading them as unchanged (#1948).
|
||||
@@ -667,7 +681,7 @@ _cleared = _dispatched - _stamped
|
||||
# files newly excluded since last run are dropped rather than masquerading as
|
||||
# deletions; untouched files' prior rows are still preserved (#1908).
|
||||
_scan = {f for fl in _corpus.values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
|
||||
# Update cumulative cost tracker
|
||||
input_tok = extract.get('input_tokens', 0)
|
||||
@@ -697,7 +711,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
|
||||
|
||||
Tell the user (omit the obsidian line unless --obsidian was given):
|
||||
```
|
||||
|
||||
+34
-20
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
|
||||
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
|
||||
/graphify <path> --update # incremental - re-extract only new/changed files
|
||||
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
|
||||
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
|
||||
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
|
||||
/graphify <path> --cluster-only # rerun clustering on existing graph
|
||||
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
|
||||
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
|
||||
|
||||
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
|
||||
|
||||
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
|
||||
|
||||
## What You Must Do When Invoked
|
||||
|
||||
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
|
||||
@@ -56,7 +61,7 @@ If no path was given, use `.` (current directory). Do not ask the user for a pat
|
||||
|
||||
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.
|
||||
|
||||
Follow these steps in order. Do not skip steps.
|
||||
Follow these steps in order unless the fast path above applies.
|
||||
|
||||
### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths)
|
||||
|
||||
@@ -147,7 +152,8 @@ from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding="utf-8-sig").strip()
|
||||
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
# Write the sidecar from Python, not a shell redirect, so the same block renders
|
||||
# on PowerShell hosts without console-encoding drift (#2528).
|
||||
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8")
|
||||
@@ -155,7 +161,7 @@ print(f'Detected {result["total_files"]} files')
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
|
||||
```
|
||||
Corpus: X files · ~Y words
|
||||
@@ -216,6 +222,7 @@ import json
|
||||
|
||||
code_files = []
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding="utf-8-sig").strip()
|
||||
for f in detect.get('files', {}).get('code', []):
|
||||
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
|
||||
|
||||
@@ -223,7 +230,7 @@ if code_files:
|
||||
# root= anchors node ids and source_file on the scan root; cache_root only says
|
||||
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
|
||||
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
|
||||
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
|
||||
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
print(f'AST: {len(result["nodes"])} nodes, {len(result["edges"])} edges')
|
||||
else:
|
||||
@@ -270,7 +277,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
|
||||
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
|
||||
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
|
||||
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding="utf-8-sig").strip()
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
|
||||
|
||||
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
|
||||
# run so Part C never merges a stale .graphify_cached.json (#1392).
|
||||
@@ -340,6 +348,7 @@ A subagent that only read the first Read call's worth of a long file still write
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding="utf-8-sig").strip()
|
||||
covered = {}
|
||||
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
|
||||
d = json.loads(Path(c).read_text(encoding="utf-8"))
|
||||
@@ -350,7 +359,7 @@ partial = []
|
||||
for src, n in sorted(covered.items()):
|
||||
p = Path(src)
|
||||
if not p.is_absolute():
|
||||
p = Path('INPUT_PATH') / src
|
||||
p = Path(INPUT_PATH) / src
|
||||
if not p.is_file():
|
||||
continue
|
||||
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
|
||||
@@ -406,7 +415,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
|
||||
# so the next --update re-dispatches it instead of serving a truncated extraction forever
|
||||
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
|
||||
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding="utf-8").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding="utf-8-sig").strip()
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
note = f' ({len(partial)} left partial for retry)' if partial else ''
|
||||
print(f'Cached {saved} files' + note)
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
@@ -492,7 +502,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast["nodes"])} AST + {len(sem
|
||||
|
||||
### Step 4 - Build graph, cluster, analyze, generate outputs
|
||||
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Substitute it the same way you substitute `INPUT_PATH` — do not leave the literal `IS_DIRECTED` in the code.
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
|
||||
|
||||
```powershell
|
||||
New-Item -ItemType Directory -Force -Path graphify-out | Out-Null
|
||||
@@ -507,10 +517,11 @@ from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding="utf-8-sig").strip()
|
||||
|
||||
# root= mirrors the --update runbook (#1361): relativize source_file to the same
|
||||
# base so the full build and incremental --update never drift apart on re-extract.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
|
||||
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
|
||||
if G.number_of_nodes() == 0:
|
||||
@@ -530,12 +541,12 @@ questions = suggest_questions(G, communities, labels)
|
||||
# nothing) when the new graph is smaller than the existing graph.json. Only write
|
||||
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
|
||||
# they never describe a graph that graph.json doesn't contain (#1392).
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json')
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
|
||||
if not wrote:
|
||||
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
|
||||
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
|
||||
raise SystemExit(1)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding="utf-8")
|
||||
analysis = {
|
||||
'communities': {str(k): v for k, v in communities.items()},
|
||||
@@ -551,7 +562,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
|
||||
|
||||
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
|
||||
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 4.5 - Graph health check (read-only integrity gate)
|
||||
|
||||
@@ -564,7 +575,8 @@ from pathlib import Path
|
||||
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding="utf-8-sig").strip()
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
|
||||
print(format_diagnostic_report(summary))
|
||||
flags = [f'{summary[k]} {label}' for k, label in (
|
||||
('dangling_endpoint_edges', 'dangling-endpoint edges'),
|
||||
@@ -577,7 +589,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
|
||||
'@ | & (Get-Content graphify-out\.graphify_python) -
|
||||
```
|
||||
|
||||
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
|
||||
### Step 5 - Label communities
|
||||
|
||||
@@ -598,9 +610,10 @@ from pathlib import Path
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding="utf-8"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding="utf-8-sig").strip()
|
||||
|
||||
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
|
||||
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
|
||||
@@ -611,7 +624,7 @@ labels = LABELS_DICT
|
||||
# Regenerate questions with real community labels (labels affect question phrasing)
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding="utf-8")
|
||||
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding="utf-8")
|
||||
# Re-export so graph.json nodes carry the curated community_name (#2490).
|
||||
@@ -626,7 +639,7 @@ print('Report updated with community labels')
|
||||
```
|
||||
|
||||
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 6 - Generate Obsidian vault (opt-in) + HTML
|
||||
|
||||
@@ -666,6 +679,7 @@ from graphify.detect import save_manifest
|
||||
# Save manifest for --update
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
|
||||
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding="utf-8-sig").strip()
|
||||
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
|
||||
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
|
||||
# root= relativizes the manifest keys to the scan root (same base as the build),
|
||||
@@ -687,7 +701,7 @@ _corpus = detect.get('all_files') or detect['files']
|
||||
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
|
||||
_pf = Path('graphify-out/.graphify_partial.txt')
|
||||
_partial = {l.strip() for l in _pf.read_text(encoding="utf-8").splitlines() if l.strip()} if _pf.exists() else set()
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
|
||||
# Files dispatched this run (the changed subset) but NOT stamped above still carry
|
||||
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
|
||||
# them instead of reading them as unchanged (#1948).
|
||||
@@ -699,7 +713,7 @@ _cleared = _dispatched - _stamped
|
||||
# files newly excluded since last run are dropped rather than masquerading as
|
||||
# deletions; untouched files' prior rows are still preserved (#1908).
|
||||
_scan = {f for fl in _corpus.values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
|
||||
# Update cumulative cost tracker
|
||||
input_tok = extract.get('input_tokens', 0)
|
||||
@@ -729,7 +743,7 @@ Get-ChildItem graphify-out -Filter '.graphify_chunk_*.json' -File -ErrorAction S
|
||||
Remove-Item -Force -ErrorAction SilentlyContinue graphify-out\.needs_update
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
|
||||
|
||||
Tell the user (omit the obsidian line unless --obsidian was given):
|
||||
```
|
||||
|
||||
+34
-20
@@ -17,6 +17,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
|
||||
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
|
||||
/graphify <path> --update # incremental - re-extract only new/changed files
|
||||
/graphify <path> --force # full rebuild allowing graph shrink (e.g. after deleting files)
|
||||
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
|
||||
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
|
||||
/graphify <path> --cluster-only # rerun clustering on existing graph
|
||||
@@ -46,6 +47,10 @@ Turn any folder of files into a navigable knowledge graph with community detecti
|
||||
|
||||
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
|
||||
|
||||
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
|
||||
|
||||
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
|
||||
|
||||
## What You Must Do When Invoked
|
||||
|
||||
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
|
||||
@@ -56,7 +61,7 @@ If no path was given, use `.` (current directory). Do not ask the user for a pat
|
||||
|
||||
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.
|
||||
|
||||
Follow these steps in order. Do not skip steps.
|
||||
Follow these steps in order unless the fast path above applies.
|
||||
|
||||
### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths)
|
||||
|
||||
@@ -119,7 +124,8 @@ from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
# Write the sidecar from Python, not a shell redirect, so the same block renders
|
||||
# on PowerShell hosts without console-encoding drift (#2528).
|
||||
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
|
||||
@@ -127,7 +133,7 @@ print(f'Detected {result[\"total_files\"]} files')
|
||||
"
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
The block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved, so there is no path to substitute and a scan root containing quotes or shell metacharacters can never be re-interpreted as code (the same reason Step 1 writes it through a quoted heredoc). Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
|
||||
```
|
||||
Corpus: X files · ~Y words
|
||||
@@ -188,6 +194,7 @@ import json
|
||||
|
||||
code_files = []
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
for f in detect.get('files', {}).get('code', []):
|
||||
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
|
||||
|
||||
@@ -195,7 +202,7 @@ if code_files:
|
||||
# root= anchors node ids and source_file on the scan root; cache_root only says
|
||||
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
|
||||
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
|
||||
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
|
||||
result = extract(code_files, cache_root=Path(INPUT_PATH), root=Path(INPUT_PATH))
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
|
||||
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
|
||||
else:
|
||||
@@ -242,7 +249,8 @@ detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encodin
|
||||
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
|
||||
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
|
||||
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root=INPUT_PATH, prompt_file='SPEC_PATH')
|
||||
|
||||
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
|
||||
# run so Part C never merges a stale .graphify_cached.json (#1392).
|
||||
@@ -312,6 +320,7 @@ $(cat graphify-out/.graphify_python) -c "
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
covered = {}
|
||||
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
|
||||
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
|
||||
@@ -322,7 +331,7 @@ partial = []
|
||||
for src, n in sorted(covered.items()):
|
||||
p = Path(src)
|
||||
if not p.is_absolute():
|
||||
p = Path('INPUT_PATH') / src
|
||||
p = Path(INPUT_PATH) / src
|
||||
if not p.is_file():
|
||||
continue
|
||||
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
|
||||
@@ -378,7 +387,8 @@ uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_te
|
||||
# so the next --update re-dispatches it instead of serving a truncated extraction forever
|
||||
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
|
||||
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root=INPUT_PATH, allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
|
||||
note = f' ({len(partial)} left partial for retry)' if partial else ''
|
||||
print(f'Cached {saved} files' + note)
|
||||
"
|
||||
@@ -464,7 +474,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
|
||||
|
||||
### Step 4 - Build graph, cluster, analyze, generate outputs
|
||||
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Substitute it the same way you substitute `INPUT_PATH` — do not leave the literal `IS_DIRECTED` in the code.
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()` and `force=IS_FORCE` to `to_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Replace `IS_FORCE` with `True` if `--force` was given (permits intentional shrink, e.g. after deleting files), otherwise `False`. Substitute both so no literal `IS_DIRECTED` or `IS_FORCE` is left in the code. INPUT_PATH is not substituted — each block reads the scan root from the trusted `graphify-out/.graphify_root` that Step 1 resolved.
|
||||
|
||||
```bash
|
||||
mkdir -p graphify-out
|
||||
@@ -479,10 +489,11 @@ from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= mirrors the --update runbook (#1361): relativize source_file to the same
|
||||
# base so the full build and incremental --update never drift apart on re-extract.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
|
||||
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
|
||||
if G.number_of_nodes() == 0:
|
||||
@@ -502,12 +513,12 @@ questions = suggest_questions(G, communities, labels)
|
||||
# nothing) when the new graph is smaller than the existing graph.json. Only write
|
||||
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
|
||||
# they never describe a graph that graph.json doesn't contain (#1392).
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json')
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json', force=IS_FORCE)
|
||||
if not wrote:
|
||||
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
|
||||
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
|
||||
raise SystemExit(1)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
analysis = {
|
||||
'communities': {str(k): v for k, v in communities.items()},
|
||||
@@ -523,7 +534,7 @@ print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(co
|
||||
|
||||
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
|
||||
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 4.5 - Graph health check (read-only integrity gate)
|
||||
|
||||
@@ -536,7 +547,8 @@ from pathlib import Path
|
||||
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root=INPUT_PATH)
|
||||
print(format_diagnostic_report(summary))
|
||||
flags = [f'{summary[k]} {label}' for k, label in (
|
||||
('dangling_endpoint_edges', 'dangling-endpoint edges'),
|
||||
@@ -549,7 +561,7 @@ print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/
|
||||
"
|
||||
```
|
||||
|
||||
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
Substitute `IS_DIRECTED` as in Step 4 (INPUT_PATH is read from `graphify-out/.graphify_root`). If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
|
||||
### Step 5 - Label communities
|
||||
|
||||
@@ -570,9 +582,10 @@ from pathlib import Path
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
|
||||
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
G = build_from_json(extraction, root=INPUT_PATH, directed=IS_DIRECTED)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
|
||||
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
|
||||
@@ -583,7 +596,7 @@ labels = LABELS_DICT
|
||||
# Regenerate questions with real community labels (labels affect question phrasing)
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, INPUT_PATH, suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
|
||||
# Re-export so graph.json nodes carry the curated community_name (#2490).
|
||||
@@ -598,7 +611,7 @@ print('Report updated with community labels')
|
||||
```
|
||||
|
||||
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
|
||||
Replace INPUT_PATH with the actual path.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root`; there is no path to substitute.
|
||||
|
||||
### Step 6 - Generate Obsidian vault (opt-in) + HTML
|
||||
|
||||
@@ -638,6 +651,7 @@ from graphify.detect import save_manifest
|
||||
# Save manifest for --update
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
|
||||
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
|
||||
# root= relativizes the manifest keys to the scan root (same base as the build),
|
||||
@@ -659,7 +673,7 @@ _corpus = detect.get('all_files') or detect['files']
|
||||
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
|
||||
_pf = Path('graphify-out/.graphify_partial.txt')
|
||||
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
|
||||
_manifest_files = _stamped_manifest_files(_corpus, extract, Path(INPUT_PATH), partial_source_files=_partial)
|
||||
# Files dispatched this run (the changed subset) but NOT stamped above still carry
|
||||
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
|
||||
# them instead of reading them as unchanged (#1948).
|
||||
@@ -671,7 +685,7 @@ _cleared = _dispatched - _stamped
|
||||
# files newly excluded since last run are dropped rather than masquerading as
|
||||
# deletions; untouched files' prior rows are still preserved (#1908).
|
||||
_scan = {f for fl in _corpus.values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
|
||||
# Update cumulative cost tracker
|
||||
input_tok = extract.get('input_tokens', 0)
|
||||
@@ -701,7 +715,7 @@ find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
|
||||
INPUT_PATH is read from `graphify-out/.graphify_root` (the scan root Steps 4-5 used), so the manifest is relativized to the scan root.
|
||||
|
||||
Tell the user (omit the obsidian line unless --obsidian was given):
|
||||
```
|
||||
|
||||
@@ -74,7 +74,7 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
|
||||
the edge AMBIGUOUS rather than picking 0.4 or below.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
|
||||
Node ID format: lowercase, word characters only (`[^\W]` after casefolding — `[a-z0-9_]` for ASCII input, but non-ASCII letters and digits are kept as-is), no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
|
||||
|
||||
Generate the extraction JSON matching this schema exactly:
|
||||
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
|
||||
|
||||
@@ -171,6 +171,8 @@ print(output)
|
||||
|
||||
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
|
||||
|
||||
**Bypass check (hub/bridge questions only, #4426).** If the question is about why a node bridges communities or has unusually many edges (a hub/god node), the neighbour listing above only shows code that already has an edge to it — it cannot show code that does the hub's job without ever calling it. Before finalizing the answer: pick one or two literal, distinctive things the hub does (a hard-coded constant it wraps, a specific string it returns, the exact computation in its body), then grep the corpus for that literal text in files that have **no edge** to the hub node in the subgraph above. Report any hits separately, labeled "Bypasses", distinct from the normal neighbour list — each is a file that reimplements the hub instead of using it. Also check whether the hub's own community label names a different node: a shared utility is often clustered into its heaviest consumer's community, so the label can read as if that consumer were the bridge. If so, say so plainly in the answer rather than letting the label stand unquestioned.
|
||||
|
||||
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -14,7 +14,12 @@ from pathlib import Path
|
||||
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
# Step B3.5 lists the files this run reads only partway, and the manifest write (and Step 9,
|
||||
# if it runs) keeps them unstamped. Only B3.5 rewrites the list, so drop one an earlier run
|
||||
# left: it would keep a file this run serves from the cache unstamped on every run (#4807).
|
||||
Path('graphify-out/.graphify_partial.txt').unlink(missing_ok=True)
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
new_total = result.get('new_total', 0)
|
||||
nf = result.get('new_files', {})
|
||||
print(json.dumps({
|
||||
@@ -103,6 +108,7 @@ from graphify.detect import save_manifest
|
||||
# Load new extraction and incremental state
|
||||
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
deleted = list(incremental.get('deleted_files', []))
|
||||
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
|
||||
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
|
||||
@@ -124,7 +130,7 @@ G = build_merge(
|
||||
[new_extraction],
|
||||
graph_path='graphify-out/graph.json',
|
||||
prune_sources=prune,
|
||||
root='INPUT_PATH',
|
||||
root=INPUT_PATH,
|
||||
directed=IS_DIRECTED,
|
||||
)
|
||||
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
|
||||
@@ -161,7 +167,13 @@ print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])
|
||||
# is lost forever (#2015). Mirrors the library extract path
|
||||
# (cli._stamped_manifest_files + clear_semantic + scan_corpus).
|
||||
from graphify.cli import _stamped_manifest_files
|
||||
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'))
|
||||
# A file a subagent only partly read (Step B3.5 lists it) DID produce output, so the
|
||||
# filter alone would stamp it and the next --update would never re-queue it. Pass the
|
||||
# list as Step 9 does after a full build, so it stays unstamped and is retried (#2225, #4807).
|
||||
# Leave the list on disk: Step 9 reads it too if it runs after the update.
|
||||
_pf = Path('graphify-out/.graphify_partial.txt')
|
||||
_partial = {l.strip() for l in _pf.read_text(encoding='utf-8').splitlines() if l.strip()} if _pf.exists() else set()
|
||||
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path(INPUT_PATH), partial_source_files=_partial)
|
||||
# Changed semantic files dispatched this run but NOT stamped had their chunk fail
|
||||
# or be omitted; clear any stale semantic_hash so they are re-queued (#1948).
|
||||
_sem_types = ('document', 'paper', 'image')
|
||||
@@ -171,7 +183,7 @@ _cleared = _dispatched - _stamped
|
||||
# scan_corpus = the RAW full corpus so in-root files newly excluded since last run
|
||||
# are dropped rather than masquerading as deletions; untouched rows preserved (#1908).
|
||||
_scan = {f for fl in incremental['files'].values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
print('[graphify update] Manifest saved.')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -74,7 +74,7 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
|
||||
the edge AMBIGUOUS rather than picking 0.4 or below.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
|
||||
Node ID format: lowercase, word characters only (`[^\W]` after casefolding — `[a-z0-9_]` for ASCII input, but non-ASCII letters and digits are kept as-is), no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
|
||||
|
||||
Generate the extraction JSON matching this schema exactly:
|
||||
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
|
||||
|
||||
@@ -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.')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -74,7 +74,7 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
|
||||
the edge AMBIGUOUS rather than picking 0.4 or below.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
|
||||
Node ID format: lowercase, word characters only (`[^\W]` after casefolding — `[a-z0-9_]` for ASCII input, but non-ASCII letters and digits are kept as-is), no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
|
||||
|
||||
Generate the extraction JSON matching this schema exactly:
|
||||
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
|
||||
|
||||
@@ -31,3 +31,18 @@ This writes a `## graphify` section to the local `CLAUDE.md` that instructs Clau
|
||||
```bash
|
||||
graphify claude uninstall # remove the section
|
||||
```
|
||||
|
||||
## Source-read freshness
|
||||
|
||||
The source-read guard treats a file newer than `graph.json` as potentially stale,
|
||||
but a checkout can refresh timestamps without changing content. For newer files,
|
||||
the guard checks the exact project-relative path (or an exact legacy absolute
|
||||
path) in the configured output directory's extraction manifest. Every populated
|
||||
AST/semantic hash must match the current content; a matching tier cannot hide a
|
||||
stale tier. Unchanged content retains the normal graph guidance and strict-mode
|
||||
first-read deny.
|
||||
|
||||
Missing, unreadable, malformed or oversized manifests, unknown paths, and absent
|
||||
or invalid hashes retain the conservative stale soft nudge. A `needs_update`
|
||||
marker always softens the guard, even when content matches. Older-mtime files
|
||||
are not hashed; this is a checkout-timestamp check, not a full freshness audit.
|
||||
@@ -171,6 +171,8 @@ print(output)
|
||||
|
||||
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
|
||||
|
||||
**Bypass check (hub/bridge questions only, #4426).** If the question is about why a node bridges communities or has unusually many edges (a hub/god node), the neighbour listing above only shows code that already has an edge to it — it cannot show code that does the hub's job without ever calling it. Before finalizing the answer: pick one or two literal, distinctive things the hub does (a hard-coded constant it wraps, a specific string it returns, the exact computation in its body), then grep the corpus for that literal text in files that have **no edge** to the hub node in the subgraph above. Report any hits separately, labeled "Bypasses", distinct from the normal neighbour list — each is a file that reimplements the hub instead of using it. Also check whether the hub's own community label names a different node: a shared utility is often clustered into its heaviest consumer's community, so the label can read as if that consumer were the bridge. If so, say so plainly in the answer rather than letting the label stand unquestioned.
|
||||
|
||||
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -14,7 +14,12 @@ from pathlib import Path
|
||||
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
# Step B3.5 lists the files this run reads only partway, and the manifest write (and Step 9,
|
||||
# if it runs) keeps them unstamped. Only B3.5 rewrites the list, so drop one an earlier run
|
||||
# left: it would keep a file this run serves from the cache unstamped on every run (#4807).
|
||||
Path('graphify-out/.graphify_partial.txt').unlink(missing_ok=True)
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
new_total = result.get('new_total', 0)
|
||||
nf = result.get('new_files', {})
|
||||
print(json.dumps({
|
||||
@@ -103,6 +108,7 @@ from graphify.detect import save_manifest
|
||||
# Load new extraction and incremental state
|
||||
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
deleted = list(incremental.get('deleted_files', []))
|
||||
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
|
||||
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
|
||||
@@ -124,7 +130,7 @@ G = build_merge(
|
||||
[new_extraction],
|
||||
graph_path='graphify-out/graph.json',
|
||||
prune_sources=prune,
|
||||
root='INPUT_PATH',
|
||||
root=INPUT_PATH,
|
||||
directed=IS_DIRECTED,
|
||||
)
|
||||
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
|
||||
@@ -161,7 +167,13 @@ print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])
|
||||
# is lost forever (#2015). Mirrors the library extract path
|
||||
# (cli._stamped_manifest_files + clear_semantic + scan_corpus).
|
||||
from graphify.cli import _stamped_manifest_files
|
||||
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'))
|
||||
# A file a subagent only partly read (Step B3.5 lists it) DID produce output, so the
|
||||
# filter alone would stamp it and the next --update would never re-queue it. Pass the
|
||||
# list as Step 9 does after a full build, so it stays unstamped and is retried (#2225, #4807).
|
||||
# Leave the list on disk: Step 9 reads it too if it runs after the update.
|
||||
_pf = Path('graphify-out/.graphify_partial.txt')
|
||||
_partial = {l.strip() for l in _pf.read_text(encoding='utf-8').splitlines() if l.strip()} if _pf.exists() else set()
|
||||
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path(INPUT_PATH), partial_source_files=_partial)
|
||||
# Changed semantic files dispatched this run but NOT stamped had their chunk fail
|
||||
# or be omitted; clear any stale semantic_hash so they are re-queued (#1948).
|
||||
_sem_types = ('document', 'paper', 'image')
|
||||
@@ -171,7 +183,7 @@ _cleared = _dispatched - _stamped
|
||||
# scan_corpus = the RAW full corpus so in-root files newly excluded since last run
|
||||
# are dropped rather than masquerading as deletions; untouched rows preserved (#1908).
|
||||
_scan = {f for fl in incremental['files'].values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
print('[graphify update] Manifest saved.')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# graphify reference: extraction subagent prompt (compact)
|
||||
|
||||
Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, and DEEP_MODE).
|
||||
Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).
|
||||
|
||||
```
|
||||
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
|
||||
@@ -30,10 +30,13 @@ Rules:
|
||||
- If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author, contributor onto every node from that file.
|
||||
- confidence_score is REQUIRED on every edge — never omit it, never use 0.5 as a default. EXTRACTED = 1.0 always. INFERRED: pick exactly ONE of 0.95 (direct structural evidence), 0.85 (strong inference), 0.75 (reasonable inference), 0.65 (weak inference), 0.55 (speculative but plausible) — never 0.5; if none fit, mark the edge AMBIGUOUS. AMBIGUOUS = 0.1-0.3.
|
||||
|
||||
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format `{stem}_{entity}` where stem is the full repo-relative path with the extension dropped, every segment joined with `_` (each lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent. `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`. Top-level files use just the filename stem. This must match the AST extractor's ID. Never append chunk or sequence suffixes — IDs must be deterministic from the label alone.
|
||||
Node ID format: lowercase, word characters only (`[^\W]` after casefolding — `[a-z0-9_]` for ASCII input, but non-ASCII letters and digits are kept as-is), no dots or slashes. Format `{stem}_{entity}` where stem is the full repo-relative path with the extension dropped, every segment joined with `_` (each lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent. `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`. Top-level files use just the filename stem. This must match the AST extractor's ID. Never append chunk or sequence suffixes — IDs must be deterministic from the label alone.
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
|
||||
|
||||
source_file RULE: set source_file to the FILE_LIST path for that file VERBATIM (absolute, no shortening to basename, no re-relativizing, no separator change). Keeps full build and --update on one base so build_merge's replace matches instead of duplicating.
|
||||
|
||||
Then write the JSON to disk with the Write tool at this exact absolute path (a relative path resolves against an undefined cwd and the file is silently lost):
|
||||
CHUNK_PATH
|
||||
```
|
||||
@@ -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.')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -30,7 +30,7 @@ Rules:
|
||||
- If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author, contributor onto every node from that file.
|
||||
- confidence_score is REQUIRED on every edge — never omit it, never use 0.5 as a default. EXTRACTED = 1.0 always. INFERRED: pick exactly ONE of 0.95 (direct structural evidence), 0.85 (strong inference), 0.75 (reasonable inference), 0.65 (weak inference), 0.55 (speculative but plausible) — never 0.5; if none fit, mark the edge AMBIGUOUS. AMBIGUOUS = 0.1-0.3.
|
||||
|
||||
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format `{stem}_{entity}` where stem is the full repo-relative path with the extension dropped, every segment joined with `_` (each lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent. `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`. Top-level files use just the filename stem. This must match the AST extractor's ID. Never append chunk or sequence suffixes — IDs must be deterministic from the label alone.
|
||||
Node ID format: lowercase, word characters only (`[^\W]` after casefolding — `[a-z0-9_]` for ASCII input, but non-ASCII letters and digits are kept as-is), no dots or slashes. Format `{stem}_{entity}` where stem is the full repo-relative path with the extension dropped, every segment joined with `_` (each lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent. `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`. Top-level files use just the filename stem. This must match the AST extractor's ID. Never append chunk or sequence suffixes — IDs must be deterministic from the label alone.
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
|
||||
|
||||
@@ -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.')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -74,7 +74,7 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
|
||||
the edge AMBIGUOUS rather than picking 0.4 or below.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
|
||||
Node ID format: lowercase, word characters only (`[^\W]` after casefolding — `[a-z0-9_]` for ASCII input, but non-ASCII letters and digits are kept as-is), no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
|
||||
|
||||
Generate the extraction JSON matching this schema exactly:
|
||||
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
|
||||
|
||||
@@ -31,3 +31,18 @@ This writes a `## graphify` section to the local `CLAUDE.md` that instructs Clau
|
||||
```bash
|
||||
graphify claude uninstall # remove the section
|
||||
```
|
||||
|
||||
## Source-read freshness
|
||||
|
||||
The source-read guard treats a file newer than `graph.json` as potentially stale,
|
||||
but a checkout can refresh timestamps without changing content. For newer files,
|
||||
the guard checks the exact project-relative path (or an exact legacy absolute
|
||||
path) in the configured output directory's extraction manifest. Every populated
|
||||
AST/semantic hash must match the current content; a matching tier cannot hide a
|
||||
stale tier. Unchanged content retains the normal graph guidance and strict-mode
|
||||
first-read deny.
|
||||
|
||||
Missing, unreadable, malformed or oversized manifests, unknown paths, and absent
|
||||
or invalid hashes retain the conservative stale soft nudge. A `needs_update`
|
||||
marker always softens the guard, even when content matches. Older-mtime files
|
||||
are not hashed; this is a checkout-timestamp check, not a full freshness audit.
|
||||
@@ -171,6 +171,8 @@ print(output)
|
||||
|
||||
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
|
||||
|
||||
**Bypass check (hub/bridge questions only, #4426).** If the question is about why a node bridges communities or has unusually many edges (a hub/god node), the neighbour listing above only shows code that already has an edge to it — it cannot show code that does the hub's job without ever calling it. Before finalizing the answer: pick one or two literal, distinctive things the hub does (a hard-coded constant it wraps, a specific string it returns, the exact computation in its body), then grep the corpus for that literal text in files that have **no edge** to the hub node in the subgraph above. Report any hits separately, labeled "Bypasses", distinct from the normal neighbour list — each is a file that reimplements the hub instead of using it. Also check whether the hub's own community label names a different node: a shared utility is often clustered into its heaviest consumer's community, so the label can read as if that consumer were the bridge. If so, say so plainly in the answer rather than letting the label stand unquestioned.
|
||||
|
||||
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -14,7 +14,12 @@ from pathlib import Path
|
||||
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
# Step B3.5 lists the files this run reads only partway, and the manifest write (and Step 9,
|
||||
# if it runs) keeps them unstamped. Only B3.5 rewrites the list, so drop one an earlier run
|
||||
# left: it would keep a file this run serves from the cache unstamped on every run (#4807).
|
||||
Path('graphify-out/.graphify_partial.txt').unlink(missing_ok=True)
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
new_total = result.get('new_total', 0)
|
||||
nf = result.get('new_files', {})
|
||||
print(json.dumps({
|
||||
@@ -103,6 +108,7 @@ from graphify.detect import save_manifest
|
||||
# Load new extraction and incremental state
|
||||
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
deleted = list(incremental.get('deleted_files', []))
|
||||
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
|
||||
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
|
||||
@@ -124,7 +130,7 @@ G = build_merge(
|
||||
[new_extraction],
|
||||
graph_path='graphify-out/graph.json',
|
||||
prune_sources=prune,
|
||||
root='INPUT_PATH',
|
||||
root=INPUT_PATH,
|
||||
directed=IS_DIRECTED,
|
||||
)
|
||||
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
|
||||
@@ -161,7 +167,13 @@ print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])
|
||||
# is lost forever (#2015). Mirrors the library extract path
|
||||
# (cli._stamped_manifest_files + clear_semantic + scan_corpus).
|
||||
from graphify.cli import _stamped_manifest_files
|
||||
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'))
|
||||
# A file a subagent only partly read (Step B3.5 lists it) DID produce output, so the
|
||||
# filter alone would stamp it and the next --update would never re-queue it. Pass the
|
||||
# list as Step 9 does after a full build, so it stays unstamped and is retried (#2225, #4807).
|
||||
# Leave the list on disk: Step 9 reads it too if it runs after the update.
|
||||
_pf = Path('graphify-out/.graphify_partial.txt')
|
||||
_partial = {l.strip() for l in _pf.read_text(encoding='utf-8').splitlines() if l.strip()} if _pf.exists() else set()
|
||||
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path(INPUT_PATH), partial_source_files=_partial)
|
||||
# Changed semantic files dispatched this run but NOT stamped had their chunk fail
|
||||
# or be omitted; clear any stale semantic_hash so they are re-queued (#1948).
|
||||
_sem_types = ('document', 'paper', 'image')
|
||||
@@ -171,7 +183,7 @@ _cleared = _dispatched - _stamped
|
||||
# scan_corpus = the RAW full corpus so in-root files newly excluded since last run
|
||||
# are dropped rather than masquerading as deletions; untouched rows preserved (#1908).
|
||||
_scan = {f for fl in incremental['files'].values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
print('[graphify update] Manifest saved.')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -74,7 +74,7 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
|
||||
the edge AMBIGUOUS rather than picking 0.4 or below.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
|
||||
Node ID format: lowercase, word characters only (`[^\W]` after casefolding — `[a-z0-9_]` for ASCII input, but non-ASCII letters and digits are kept as-is), no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
|
||||
|
||||
Generate the extraction JSON matching this schema exactly:
|
||||
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
|
||||
|
||||
@@ -31,3 +31,18 @@ This writes a `## graphify` section to the local `CLAUDE.md` that instructs Clau
|
||||
```bash
|
||||
graphify claude uninstall # remove the section
|
||||
```
|
||||
|
||||
## Source-read freshness
|
||||
|
||||
The source-read guard treats a file newer than `graph.json` as potentially stale,
|
||||
but a checkout can refresh timestamps without changing content. For newer files,
|
||||
the guard checks the exact project-relative path (or an exact legacy absolute
|
||||
path) in the configured output directory's extraction manifest. Every populated
|
||||
AST/semantic hash must match the current content; a matching tier cannot hide a
|
||||
stale tier. Unchanged content retains the normal graph guidance and strict-mode
|
||||
first-read deny.
|
||||
|
||||
Missing, unreadable, malformed or oversized manifests, unknown paths, and absent
|
||||
or invalid hashes retain the conservative stale soft nudge. A `needs_update`
|
||||
marker always softens the guard, even when content matches. Older-mtime files
|
||||
are not hashed; this is a checkout-timestamp check, not a full freshness audit.
|
||||
@@ -171,6 +171,8 @@ print(output)
|
||||
|
||||
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
|
||||
|
||||
**Bypass check (hub/bridge questions only, #4426).** If the question is about why a node bridges communities or has unusually many edges (a hub/god node), the neighbour listing above only shows code that already has an edge to it — it cannot show code that does the hub's job without ever calling it. Before finalizing the answer: pick one or two literal, distinctive things the hub does (a hard-coded constant it wraps, a specific string it returns, the exact computation in its body), then grep the corpus for that literal text in files that have **no edge** to the hub node in the subgraph above. Report any hits separately, labeled "Bypasses", distinct from the normal neighbour list — each is a file that reimplements the hub instead of using it. Also check whether the hub's own community label names a different node: a shared utility is often clustered into its heaviest consumer's community, so the label can read as if that consumer were the bridge. If so, say so plainly in the answer rather than letting the label stand unquestioned.
|
||||
|
||||
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -14,7 +14,12 @@ from pathlib import Path
|
||||
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
# Step B3.5 lists the files this run reads only partway, and the manifest write (and Step 9,
|
||||
# if it runs) keeps them unstamped. Only B3.5 rewrites the list, so drop one an earlier run
|
||||
# left: it would keep a file this run serves from the cache unstamped on every run (#4807).
|
||||
Path('graphify-out/.graphify_partial.txt').unlink(missing_ok=True)
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
new_total = result.get('new_total', 0)
|
||||
nf = result.get('new_files', {})
|
||||
print(json.dumps({
|
||||
@@ -103,6 +108,7 @@ from graphify.detect import save_manifest
|
||||
# Load new extraction and incremental state
|
||||
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
deleted = list(incremental.get('deleted_files', []))
|
||||
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
|
||||
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
|
||||
@@ -124,7 +130,7 @@ G = build_merge(
|
||||
[new_extraction],
|
||||
graph_path='graphify-out/graph.json',
|
||||
prune_sources=prune,
|
||||
root='INPUT_PATH',
|
||||
root=INPUT_PATH,
|
||||
directed=IS_DIRECTED,
|
||||
)
|
||||
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
|
||||
@@ -161,7 +167,13 @@ print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])
|
||||
# is lost forever (#2015). Mirrors the library extract path
|
||||
# (cli._stamped_manifest_files + clear_semantic + scan_corpus).
|
||||
from graphify.cli import _stamped_manifest_files
|
||||
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'))
|
||||
# A file a subagent only partly read (Step B3.5 lists it) DID produce output, so the
|
||||
# filter alone would stamp it and the next --update would never re-queue it. Pass the
|
||||
# list as Step 9 does after a full build, so it stays unstamped and is retried (#2225, #4807).
|
||||
# Leave the list on disk: Step 9 reads it too if it runs after the update.
|
||||
_pf = Path('graphify-out/.graphify_partial.txt')
|
||||
_partial = {l.strip() for l in _pf.read_text(encoding='utf-8').splitlines() if l.strip()} if _pf.exists() else set()
|
||||
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path(INPUT_PATH), partial_source_files=_partial)
|
||||
# Changed semantic files dispatched this run but NOT stamped had their chunk fail
|
||||
# or be omitted; clear any stale semantic_hash so they are re-queued (#1948).
|
||||
_sem_types = ('document', 'paper', 'image')
|
||||
@@ -171,7 +183,7 @@ _cleared = _dispatched - _stamped
|
||||
# scan_corpus = the RAW full corpus so in-root files newly excluded since last run
|
||||
# are dropped rather than masquerading as deletions; untouched rows preserved (#1908).
|
||||
_scan = {f for fl in incremental['files'].values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
print('[graphify update] Manifest saved.')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -74,7 +74,7 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
|
||||
the edge AMBIGUOUS rather than picking 0.4 or below.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
|
||||
Node ID format: lowercase, word characters only (`[^\W]` after casefolding — `[a-z0-9_]` for ASCII input, but non-ASCII letters and digits are kept as-is), no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
|
||||
|
||||
Generate the extraction JSON matching this schema exactly:
|
||||
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
|
||||
|
||||
@@ -31,3 +31,18 @@ This writes a `## graphify` section to the local `CLAUDE.md` that instructs Clau
|
||||
```bash
|
||||
graphify claude uninstall # remove the section
|
||||
```
|
||||
|
||||
## Source-read freshness
|
||||
|
||||
The source-read guard treats a file newer than `graph.json` as potentially stale,
|
||||
but a checkout can refresh timestamps without changing content. For newer files,
|
||||
the guard checks the exact project-relative path (or an exact legacy absolute
|
||||
path) in the configured output directory's extraction manifest. Every populated
|
||||
AST/semantic hash must match the current content; a matching tier cannot hide a
|
||||
stale tier. Unchanged content retains the normal graph guidance and strict-mode
|
||||
first-read deny.
|
||||
|
||||
Missing, unreadable, malformed or oversized manifests, unknown paths, and absent
|
||||
or invalid hashes retain the conservative stale soft nudge. A `needs_update`
|
||||
marker always softens the guard, even when content matches. Older-mtime files
|
||||
are not hashed; this is a checkout-timestamp check, not a full freshness audit.
|
||||
@@ -171,6 +171,8 @@ print(output)
|
||||
|
||||
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
|
||||
|
||||
**Bypass check (hub/bridge questions only, #4426).** If the question is about why a node bridges communities or has unusually many edges (a hub/god node), the neighbour listing above only shows code that already has an edge to it — it cannot show code that does the hub's job without ever calling it. Before finalizing the answer: pick one or two literal, distinctive things the hub does (a hard-coded constant it wraps, a specific string it returns, the exact computation in its body), then grep the corpus for that literal text in files that have **no edge** to the hub node in the subgraph above. Report any hits separately, labeled "Bypasses", distinct from the normal neighbour list — each is a file that reimplements the hub instead of using it. Also check whether the hub's own community label names a different node: a shared utility is often clustered into its heaviest consumer's community, so the label can read as if that consumer were the bridge. If so, say so plainly in the answer rather than letting the label stand unquestioned.
|
||||
|
||||
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -14,7 +14,12 @@ from pathlib import Path
|
||||
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
# Step B3.5 lists the files this run reads only partway, and the manifest write (and Step 9,
|
||||
# if it runs) keeps them unstamped. Only B3.5 rewrites the list, so drop one an earlier run
|
||||
# left: it would keep a file this run serves from the cache unstamped on every run (#4807).
|
||||
Path('graphify-out/.graphify_partial.txt').unlink(missing_ok=True)
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
new_total = result.get('new_total', 0)
|
||||
nf = result.get('new_files', {})
|
||||
print(json.dumps({
|
||||
@@ -103,6 +108,7 @@ from graphify.detect import save_manifest
|
||||
# Load new extraction and incremental state
|
||||
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
deleted = list(incremental.get('deleted_files', []))
|
||||
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
|
||||
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
|
||||
@@ -124,7 +130,7 @@ G = build_merge(
|
||||
[new_extraction],
|
||||
graph_path='graphify-out/graph.json',
|
||||
prune_sources=prune,
|
||||
root='INPUT_PATH',
|
||||
root=INPUT_PATH,
|
||||
directed=IS_DIRECTED,
|
||||
)
|
||||
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
|
||||
@@ -161,7 +167,13 @@ print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])
|
||||
# is lost forever (#2015). Mirrors the library extract path
|
||||
# (cli._stamped_manifest_files + clear_semantic + scan_corpus).
|
||||
from graphify.cli import _stamped_manifest_files
|
||||
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'))
|
||||
# A file a subagent only partly read (Step B3.5 lists it) DID produce output, so the
|
||||
# filter alone would stamp it and the next --update would never re-queue it. Pass the
|
||||
# list as Step 9 does after a full build, so it stays unstamped and is retried (#2225, #4807).
|
||||
# Leave the list on disk: Step 9 reads it too if it runs after the update.
|
||||
_pf = Path('graphify-out/.graphify_partial.txt')
|
||||
_partial = {l.strip() for l in _pf.read_text(encoding='utf-8').splitlines() if l.strip()} if _pf.exists() else set()
|
||||
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path(INPUT_PATH), partial_source_files=_partial)
|
||||
# Changed semantic files dispatched this run but NOT stamped had their chunk fail
|
||||
# or be omitted; clear any stale semantic_hash so they are re-queued (#1948).
|
||||
_sem_types = ('document', 'paper', 'image')
|
||||
@@ -171,7 +183,7 @@ _cleared = _dispatched - _stamped
|
||||
# scan_corpus = the RAW full corpus so in-root files newly excluded since last run
|
||||
# are dropped rather than masquerading as deletions; untouched rows preserved (#1908).
|
||||
_scan = {f for fl in incremental['files'].values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
print('[graphify update] Manifest saved.')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# graphify reference: extraction subagent prompt (compact)
|
||||
|
||||
Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, and DEEP_MODE).
|
||||
Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).
|
||||
|
||||
```
|
||||
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
|
||||
@@ -30,10 +30,13 @@ Rules:
|
||||
- If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author, contributor onto every node from that file.
|
||||
- confidence_score is REQUIRED on every edge — never omit it, never use 0.5 as a default. EXTRACTED = 1.0 always. INFERRED: pick exactly ONE of 0.95 (direct structural evidence), 0.85 (strong inference), 0.75 (reasonable inference), 0.65 (weak inference), 0.55 (speculative but plausible) — never 0.5; if none fit, mark the edge AMBIGUOUS. AMBIGUOUS = 0.1-0.3.
|
||||
|
||||
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format `{stem}_{entity}` where stem is the full repo-relative path with the extension dropped, every segment joined with `_` (each lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent. `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`. Top-level files use just the filename stem. This must match the AST extractor's ID. Never append chunk or sequence suffixes — IDs must be deterministic from the label alone.
|
||||
Node ID format: lowercase, word characters only (`[^\W]` after casefolding — `[a-z0-9_]` for ASCII input, but non-ASCII letters and digits are kept as-is), no dots or slashes. Format `{stem}_{entity}` where stem is the full repo-relative path with the extension dropped, every segment joined with `_` (each lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent. `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`. Top-level files use just the filename stem. This must match the AST extractor's ID. Never append chunk or sequence suffixes — IDs must be deterministic from the label alone.
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
|
||||
|
||||
source_file RULE: set source_file to the FILE_LIST path for that file VERBATIM (absolute, no shortening to basename, no re-relativizing, no separator change). Keeps full build and --update on one base so build_merge's replace matches instead of duplicating.
|
||||
|
||||
Then write the JSON to disk with the Write tool at this exact absolute path (a relative path resolves against an undefined cwd and the file is silently lost):
|
||||
CHUNK_PATH
|
||||
```
|
||||
@@ -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.')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -74,7 +74,7 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
|
||||
the edge AMBIGUOUS rather than picking 0.4 or below.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
|
||||
Node ID format: lowercase, word characters only (`[^\W]` after casefolding — `[a-z0-9_]` for ASCII input, but non-ASCII letters and digits are kept as-is), no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
|
||||
|
||||
Generate the extraction JSON matching this schema exactly:
|
||||
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
|
||||
|
||||
@@ -31,3 +31,18 @@ This writes a `## graphify` section to the local `CLAUDE.md` that instructs Clau
|
||||
```bash
|
||||
graphify claude uninstall # remove the section
|
||||
```
|
||||
|
||||
## Source-read freshness
|
||||
|
||||
The source-read guard treats a file newer than `graph.json` as potentially stale,
|
||||
but a checkout can refresh timestamps without changing content. For newer files,
|
||||
the guard checks the exact project-relative path (or an exact legacy absolute
|
||||
path) in the configured output directory's extraction manifest. Every populated
|
||||
AST/semantic hash must match the current content; a matching tier cannot hide a
|
||||
stale tier. Unchanged content retains the normal graph guidance and strict-mode
|
||||
first-read deny.
|
||||
|
||||
Missing, unreadable, malformed or oversized manifests, unknown paths, and absent
|
||||
or invalid hashes retain the conservative stale soft nudge. A `needs_update`
|
||||
marker always softens the guard, even when content matches. Older-mtime files
|
||||
are not hashed; this is a checkout-timestamp check, not a full freshness audit.
|
||||
@@ -171,6 +171,8 @@ print(output)
|
||||
|
||||
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
|
||||
|
||||
**Bypass check (hub/bridge questions only, #4426).** If the question is about why a node bridges communities or has unusually many edges (a hub/god node), the neighbour listing above only shows code that already has an edge to it — it cannot show code that does the hub's job without ever calling it. Before finalizing the answer: pick one or two literal, distinctive things the hub does (a hard-coded constant it wraps, a specific string it returns, the exact computation in its body), then grep the corpus for that literal text in files that have **no edge** to the hub node in the subgraph above. Report any hits separately, labeled "Bypasses", distinct from the normal neighbour list — each is a file that reimplements the hub instead of using it. Also check whether the hub's own community label names a different node: a shared utility is often clustered into its heaviest consumer's community, so the label can read as if that consumer were the bridge. If so, say so plainly in the answer rather than letting the label stand unquestioned.
|
||||
|
||||
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -14,7 +14,12 @@ from pathlib import Path
|
||||
|
||||
from graphify.paths import out_path
|
||||
from graphify.watch import _read_build_excludes, _read_build_gitignore
|
||||
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
# Step B3.5 lists the files this run reads only partway, and the manifest write (and Step 9,
|
||||
# if it runs) keeps them unstamped. Only B3.5 rewrites the list, so drop one an earlier run
|
||||
# left: it would keep a file this run serves from the cache unstamped on every run (#4807).
|
||||
Path('graphify-out/.graphify_partial.txt').unlink(missing_ok=True)
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
result = detect_incremental(Path(INPUT_PATH), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
|
||||
new_total = result.get('new_total', 0)
|
||||
nf = result.get('new_files', {})
|
||||
print(json.dumps({
|
||||
@@ -103,6 +108,7 @@ from graphify.detect import save_manifest
|
||||
# Load new extraction and incremental state
|
||||
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
|
||||
INPUT_PATH = Path('graphify-out/.graphify_root').read_text(encoding=\"utf-8-sig\").strip()
|
||||
deleted = list(incremental.get('deleted_files', []))
|
||||
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
|
||||
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
|
||||
@@ -124,7 +130,7 @@ G = build_merge(
|
||||
[new_extraction],
|
||||
graph_path='graphify-out/graph.json',
|
||||
prune_sources=prune,
|
||||
root='INPUT_PATH',
|
||||
root=INPUT_PATH,
|
||||
directed=IS_DIRECTED,
|
||||
)
|
||||
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
|
||||
@@ -161,7 +167,13 @@ print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])
|
||||
# is lost forever (#2015). Mirrors the library extract path
|
||||
# (cli._stamped_manifest_files + clear_semantic + scan_corpus).
|
||||
from graphify.cli import _stamped_manifest_files
|
||||
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'))
|
||||
# A file a subagent only partly read (Step B3.5 lists it) DID produce output, so the
|
||||
# filter alone would stamp it and the next --update would never re-queue it. Pass the
|
||||
# list as Step 9 does after a full build, so it stays unstamped and is retried (#2225, #4807).
|
||||
# Leave the list on disk: Step 9 reads it too if it runs after the update.
|
||||
_pf = Path('graphify-out/.graphify_partial.txt')
|
||||
_partial = {l.strip() for l in _pf.read_text(encoding='utf-8').splitlines() if l.strip()} if _pf.exists() else set()
|
||||
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path(INPUT_PATH), partial_source_files=_partial)
|
||||
# Changed semantic files dispatched this run but NOT stamped had their chunk fail
|
||||
# or be omitted; clear any stale semantic_hash so they are re-queued (#1948).
|
||||
_sem_types = ('document', 'paper', 'image')
|
||||
@@ -171,7 +183,7 @@ _cleared = _dispatched - _stamped
|
||||
# scan_corpus = the RAW full corpus so in-root files newly excluded since last run
|
||||
# are dropped rather than masquerading as deletions; untouched rows preserved (#1908).
|
||||
_scan = {f for fl in incremental['files'].values() for f in fl}
|
||||
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
save_manifest(_manifest_files, root=INPUT_PATH, scan_corpus=_scan, clear_semantic=_cleared or None)
|
||||
print('[graphify update] Manifest saved.')
|
||||
"
|
||||
```
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# graphify reference: extraction subagent prompt (compact)
|
||||
|
||||
Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, and DEEP_MODE).
|
||||
Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).
|
||||
|
||||
```
|
||||
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
|
||||
@@ -30,10 +30,13 @@ Rules:
|
||||
- If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author, contributor onto every node from that file.
|
||||
- confidence_score is REQUIRED on every edge — never omit it, never use 0.5 as a default. EXTRACTED = 1.0 always. INFERRED: pick exactly ONE of 0.95 (direct structural evidence), 0.85 (strong inference), 0.75 (reasonable inference), 0.65 (weak inference), 0.55 (speculative but plausible) — never 0.5; if none fit, mark the edge AMBIGUOUS. AMBIGUOUS = 0.1-0.3.
|
||||
|
||||
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format `{stem}_{entity}` where stem is the full repo-relative path with the extension dropped, every segment joined with `_` (each lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent. `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`. Top-level files use just the filename stem. This must match the AST extractor's ID. Never append chunk or sequence suffixes — IDs must be deterministic from the label alone.
|
||||
Node ID format: lowercase, word characters only (`[^\W]` after casefolding — `[a-z0-9_]` for ASCII input, but non-ASCII letters and digits are kept as-is), no dots or slashes. Format `{stem}_{entity}` where stem is the full repo-relative path with the extension dropped, every segment joined with `_` (each lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent. `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`. Top-level files use just the filename stem. This must match the AST extractor's ID. Never append chunk or sequence suffixes — IDs must be deterministic from the label alone.
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
|
||||
|
||||
source_file RULE: set source_file to the FILE_LIST path for that file VERBATIM (absolute, no shortening to basename, no re-relativizing, no separator change). Keeps full build and --update on one base so build_merge's replace matches instead of duplicating.
|
||||
|
||||
Then write the JSON to disk with the Write tool at this exact absolute path (a relative path resolves against an undefined cwd and the file is silently lost):
|
||||
CHUNK_PATH
|
||||
```
|
||||
Loaded 100 of 348 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user