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 | ||
|
|
26818d0857 | ||
|
|
7e7556f09e | ||
|
|
e71d5ed63e | ||
|
|
d157b98ced | ||
|
|
0fa0db50f0 | ||
|
|
41acf8496d | ||
|
|
a5a533a683 | ||
|
|
f20856a0ab | ||
|
|
bc564dd891 | ||
|
|
d1d6a42e31 | ||
|
|
0406d9bed6 | ||
|
|
0d251fe577 | ||
|
|
e677fb8093 | ||
|
|
fc2c354919 | ||
|
|
d64b0be4c5 | ||
|
|
672469a342 | ||
|
|
a0dbd6f979 | ||
|
|
f475138c33 | ||
|
|
a5e01bd206 | ||
|
|
c797e68f9d | ||
|
|
209768ea73 | ||
|
|
68e63edb1e | ||
|
|
e579278fe3 | ||
|
|
8e9a3d95a9 | ||
|
|
9b35e29ac5 | ||
|
|
3ca53c70ac | ||
|
|
fe55ad7cac | ||
|
|
e56cdb56b0 | ||
|
|
24ff9b2c52 | ||
|
|
0068826adc | ||
|
|
007cbeccd8 | ||
|
|
aa5a00a16b | ||
|
|
dfd29c489d | ||
|
|
2daf6874ae | ||
|
|
3801e527f4 | ||
|
|
d5895eae4b | ||
|
|
3304de1623 | ||
|
|
0a8cd4e1e3 | ||
|
|
e97582681f | ||
|
|
ef51a3837a | ||
|
|
c65d46d507 | ||
|
|
c9c658dd11 | ||
|
|
07e11926b5 | ||
|
|
02e404451f | ||
|
|
572fc7e889 | ||
|
|
754bbb6da5 | ||
|
|
fa76a1d503 | ||
|
|
a47deee3af | ||
|
|
a9a0d01f43 | ||
|
|
9af467494f | ||
|
|
51c991bb03 | ||
|
|
55a2b6ab53 | ||
|
|
4f9e07c889 | ||
|
|
79995641ac | ||
|
|
c4858593c2 | ||
|
|
20dbabb47e | ||
|
|
d8764b4903 | ||
|
|
cc22523c03 | ||
|
|
38046fcfa7 | ||
|
|
a0cea18ddc | ||
|
|
97518adbca | ||
|
|
281f7395f0 | ||
|
|
0d909f18fa | ||
|
|
217f6da2da | ||
|
|
a306df6db7 | ||
|
|
d2cff2c230 | ||
|
|
f1b3d54daa | ||
|
|
95f5c8a76d | ||
|
|
d5808b1bcf | ||
|
|
d94f59c713 | ||
|
|
e7f0405934 | ||
|
|
0116d9261e | ||
|
|
7dea8f19ca | ||
|
|
04f1986cb4 | ||
|
|
9107155253 | ||
|
|
1ccc0c16b9 | ||
|
|
506d6ff5fb | ||
|
|
b69b7510c2 | ||
|
|
dac063456b | ||
|
|
290b7f0b30 | ||
|
|
27bc17b5aa | ||
|
|
830de39f94 | ||
|
|
3e1a423fe1 | ||
|
|
a5ea8bbd6b | ||
|
|
f1a11d33ac | ||
|
|
bd07170790 | ||
|
|
8e62a16ebe | ||
|
|
4f8f990020 | ||
|
|
a84557733b | ||
|
|
51088ed3bf | ||
|
|
58417ee754 | ||
|
|
e3bcbcff35 | ||
|
|
e7ddccb127 | ||
|
|
78de58a557 | ||
|
|
c205f45472 | ||
|
|
209b7e3935 | ||
|
|
383d715c83 | ||
|
|
08725465e0 | ||
|
|
6533f57e85 | ||
|
|
e0fb925378 | ||
|
|
968115c0cc | ||
|
|
360056a98a | ||
|
|
59b01dcd3a | ||
|
|
0ba0ed1dbe | ||
|
|
12f0fd6f15 | ||
|
|
5cd4edcc24 | ||
|
|
5e4efda78d | ||
|
|
336312ca12 | ||
|
|
79fce4dd94 | ||
|
|
7b5036662a | ||
|
|
d5f45ba3cc | ||
|
|
8738b7baf0 | ||
|
|
05782647be | ||
|
|
c2dd119b8e | ||
|
|
6e75b42147 | ||
|
|
91c8954345 | ||
|
|
dfd4ea95ec | ||
|
|
4c7d710f75 | ||
|
|
db8b04a331 | ||
|
|
171617dc1b | ||
|
|
51d248b8bb | ||
|
|
245c952f1a | ||
|
|
34b96bcb31 | ||
|
|
92741d162b | ||
|
|
85567c95af | ||
|
|
aa8ca7370b | ||
|
|
e8b1bb571f | ||
|
|
7174d3b972 | ||
|
|
b111c5cea9 | ||
|
|
2a0cacb60c | ||
|
|
18e52c4bb8 | ||
|
|
e76019466d | ||
|
|
87151e40ac | ||
|
|
14514b37f6 | ||
|
|
3bab26798e | ||
|
|
8cfda7f1ce | ||
|
|
291248ef49 | ||
|
|
44079cbd9b | ||
|
|
73876cbdc7 | ||
|
|
cbcd8dd601 | ||
|
|
97f18cb7b0 | ||
|
|
8a19705383 | ||
|
|
53d3d80346 | ||
|
|
ae2b453b7d | ||
|
|
4f99094579 | ||
|
|
3b213769f0 | ||
|
|
e69cc9d89e | ||
|
|
8a29ab62cb | ||
|
|
fedc4e82ed | ||
|
|
bf48d2b83e | ||
|
|
02f62e769d | ||
|
|
5c3c47ebea | ||
|
|
d709f67941 | ||
|
|
7598c5dcee | ||
|
|
fb90065380 | ||
|
|
7aae85ec6e | ||
|
|
d67b5a0faf | ||
|
|
1834b3e703 | ||
|
|
9c5d56f28f | ||
|
|
e4d8235378 | ||
|
|
6a21696caa | ||
|
|
d4f3cf7f51 | ||
|
|
a8ce86f02e | ||
|
|
ac4b5e33dd | ||
|
|
c588b72d93 | ||
|
|
c3dad319ee | ||
|
|
b8d9f12385 | ||
|
|
8e8a7c3808 | ||
|
|
9ce1404719 | ||
|
|
01715accd5 | ||
|
|
518bd3f066 | ||
|
|
608722208d | ||
|
|
7a0b031088 | ||
|
|
c6d4c25135 | ||
|
|
775ddb9d5a | ||
|
|
3a4beec195 | ||
|
|
6e6d5dbbfd | ||
|
|
a287c0795a | ||
|
|
0620458b04 | ||
|
|
b19eefa8f0 | ||
|
|
de35292406 | ||
|
|
dd45dfc2b0 | ||
|
|
c0ac375b11 | ||
|
|
b9f95739ca | ||
|
|
b324c34f78 | ||
|
|
0aa256f95f | ||
|
|
c7f16f9426 | ||
|
|
0e7cf1ec4b | ||
|
|
ae5493c182 | ||
|
|
85537d9c01 | ||
|
|
74bed49f46 | ||
|
|
cc488b9076 | ||
|
|
2b07311b0d | ||
|
|
822fbb04c2 | ||
|
|
52dea94b01 | ||
|
|
53bfe14613 | ||
|
|
8f6ad0f61e | ||
|
|
724a184bdd | ||
|
|
847a93f3ca |
No files matched your search
@@ -8,7 +8,7 @@ body:
|
||||
[discussions](https://github.com/Graphify-Labs/graphify/discussions)
|
||||
and [issues](https://github.com/Graphify-Labs/graphify/issues) — your
|
||||
question may already be answered. For real-time help, join the
|
||||
[Discord](https://discord.gg/XDnKVpzdXB). If you have found a bug, please
|
||||
[Discord](https://discord.gg/graphify). If you have found a bug, please
|
||||
open an issue instead so it can be tracked.
|
||||
- type: textarea
|
||||
id: question
|
||||
|
||||
@@ -4,7 +4,7 @@ contact_links:
|
||||
url: https://github.com/Graphify-Labs/graphify/security/policy
|
||||
about: Please report vulnerabilities privately using the security policy.
|
||||
- name: Discord community
|
||||
url: https://discord.gg/XDnKVpzdXB
|
||||
url: https://discord.gg/graphify
|
||||
about: Join the Discord to ask questions and discuss ideas in real time.
|
||||
- name: 📖 Documentation
|
||||
url: https://docs.graphify.com
|
||||
|
||||
@@ -33,7 +33,7 @@ jobs:
|
||||
return;
|
||||
}
|
||||
|
||||
const discord = 'https://discord.gg/XDnKVpzdXB';
|
||||
const discord = 'https://discord.gg/graphify';
|
||||
const discussions = 'https://github.com/Graphify-Labs/graphify/discussions';
|
||||
|
||||
const body = isPR
|
||||
|
||||
@@ -40,3 +40,8 @@ paper/
|
||||
|
||||
# macOS Finder metadata
|
||||
.DS_Store
|
||||
|
||||
# MSBuild restore/build output: editors with C# tooling restore the fixture
|
||||
# .csproj files on open
|
||||
tests/fixtures/**/obj/
|
||||
tests/fixtures/**/bin/
|
||||
+126
@@ -33,6 +33,12 @@ Signatures below are the real ones - `tests/test_architecture_doc.py` imports ev
|
||||
| `watch.py` | `watch(watch_path, debounce=3.0)`, `check_update(watch_path)` | directory → rebuild on change; `check_update` reports whether a re-extraction is pending |
|
||||
| `benchmark.py` | `run_benchmark(graph_path)` | graph file → corpus vs subgraph token comparison |
|
||||
|
||||
Detection counts words from text and converted documents. Supported raster images,
|
||||
audio and video stay in the discovered corpus, but their raw bytes are never decoded
|
||||
for word counting; detection also bypasses any older cached counts for them. SVG
|
||||
remains text-readable, and PDF/Office files retain their existing text converters.
|
||||
This avoids reading and splitting entire binary media files just to size the corpus.
|
||||
|
||||
### Calling `extract()` from your own code
|
||||
|
||||
`extract()` takes a **list** of paths, and `root` is keyword-only and optional:
|
||||
@@ -49,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
|
||||
@@ -64,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).
|
||||
@@ -78,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.
|
||||
@@ -86,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:
|
||||
@@ -118,6 +186,25 @@ classes under different parents retain separate definitions, methods, and
|
||||
containment edges; top-level class ids are unchanged. AST cache schema 7 prevents
|
||||
older cached definitions from retaining the collapsed identities.
|
||||
|
||||
Python injected fields retain an unchanged parameter/local's declared class
|
||||
through `self.field = value`. A local assigned a member-call result can use the
|
||||
resolved method's single scalar return-type reference. The link uses the exact
|
||||
producer call's byte span, not a same-line argument or a bare method name.
|
||||
Unknown types, conflicting assignments, shadowed names, container returns, and
|
||||
ambiguous return references emit no inferred call. Resulting call edges remain
|
||||
`INFERRED`. Changed-caller rebuilds carry unchanged methods' return-type references
|
||||
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
|
||||
@@ -126,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.
|
||||
+293
@@ -2,6 +2,299 @@
|
||||
|
||||
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).
|
||||
- Fix: **csharp** a C# method node is labelled with its owning type (`MyClass.Method`) instead of a bare `Method`, so same-named methods across types are distinguishable; node ids and edges are unchanged (display label only) (#4883, #4889, thanks @SyedFahad7).
|
||||
- Feat: **path** `graphify path` and the MCP shortest-path output report the overall path confidence as the weakest hop (lowest confidence tier, then lowest score), with a summary line naming that hop (#4885, #4892, thanks @SyedFahad7).
|
||||
- Fix: **path** an endpoint written `Type.Member` resolves to the member node, not the containing type, so `graphify path "Exporter.Run" "PdfReport.Build"` finds the real call route; exact names and file names still win first, and a `Type.Member` whose member does not exist fails closed (#4884, #4893, thanks @SyedFahad7).
|
||||
- Fix: **extract** file ids and per-declaration ids are kept distinct, so a top-level declaration whose name matches its file (for example `class Js` in `a.js`) is no longer silently dropped on an id collision; cross-file references bind to the declared id (#4854, #4857, thanks @Deepjyoti-Sarmah).
|
||||
- Fix: **dedup** when a cross-file document mention and an AST node collide on a defining id, the AST node keeps the id instead of being dropped, while same-file enrichment, extension twins and single-definer cases are left as-is (#4859, #4872, thanks @TanmayShah29; duplicate approach in #4871 by @ayushcodes10).
|
||||
- Fix: **build** a two-file import cycle (a imports b, b imports a) is reported in the default undirected build, and the stamp is cleared correctly on incremental/watch rebuilds so a dropped import no longer leaves a stale cycle (#4839, #4841, thanks @Mpasha17; duplicate approach in #4852 by @legendteddy).
|
||||
- Fix: **extract** a relative JS/TS import carrying a `?query` or `#fragment` suffix (`./mod.js?v=1`) resolves to the real module instead of a phantom node; Node `#subpath` imports are left untouched (#4860, #4876, thanks @Jitendarmahara; duplicate approach in #4869 by @mirzasnowy).
|
||||
- Fix: **go** a receiver bound with `var x = T{}` or `var x = &T{}` (a composite literal) is typed as `T`, matching the `x := T{}` form, so its member calls resolve (#4843, thanks @ayushcodes10).
|
||||
- Fix: **verilog** a SystemVerilog class constructor (`function new(...)`, which has no return type) gets its own node, `method` edge and parameter-type references (#4848, thanks @ayushcodes10).
|
||||
- Fix: **powershell** `using module`/`using assembly` drops a real file extension (`Helpers.psm1` to `helpers`) but keeps a dotted module name with no extension intact (`Az.Accounts`) (#4847, thanks @ayushcodes10).
|
||||
- Fix: **solidity** a free-function `using {a, b} for T` set emits `uses` edges for each named function, not just the single-library `using Lib for T` form (#4846, thanks @ayushcodes10).
|
||||
- Fix: **commonlisp** a `defclass` whose superclass is defined later in the same file binds to that local node instead of minting a sourceless stub (#4845, thanks @ayushcodes10).
|
||||
- Fix: **pascal** `inherited` and `inline` form component blocks (.lfm/.dfm) are recognised, so a later `object` block keeps its correct parent instead of being re-parented by a corrupted nesting stack (#4844, thanks @ayushcodes10).
|
||||
- Fix: **serve** when two nodes tie in a lookup and differ only by case, the one spelled exactly as queried wins (the others stay reachable one tier down) instead of every spelling being refused as ambiguous (#4870, thanks @nothariharan).
|
||||
- Fix: **export** the Cypher text export keys `MERGE` on the stable node id and sets the label separately, so re-importing after a label change updates the node instead of creating a duplicate (#4878, thanks @oleksii-tumanov).
|
||||
- Fix: **pdf** the converted-text cache is keyed on the resolved source path, so two PDFs with the same relative name in different roots do not poison each other within one process (#4851, thanks @xunguangzlj-cloud).
|
||||
|
||||
## 0.9.97 (2026-10-27)
|
||||
|
||||
- Security: **rationale redaction** credential redaction for rationale labels moves to a single pre-cache choke point (`_redact_rationale_labels` inside `_safe_extract`), so no extractor can skip it, and it now covers more leak shapes: URL userinfo with an empty user or with `/`/`@` in the password, PEM private-key bodies, tokens glued to surrounding text by `_` (for example `ghp_...`), Slack `xoxe-` refresh tokens, short JWTs, and Common Lisp docstrings that previously built labels without redacting. Benign strings (hashes, `sk-` prose, URLs without userinfo) are left alone (#4647, thanks @0xkaushik-ai).
|
||||
- Security: **deps** anyio is floored to `>=4.14.2` in the `mcp` extra, above CVE-2026-63374 (an IDNA 2003 vs 2008 hostname-validation bypass that let a MITM on a non-ASCII domain present a cert for a different ASCII host, CVSS 9.3). anyio is only a transitive dependency and the lockfile already resolves 4.15.1, so this is a floor to stop a future re-resolution from regressing.
|
||||
- Fix: **markdown** ATX headings parse per CommonMark: a trailing run of `#` is not part of the heading text (`## Setup ##` is "Setup"), up to three spaces of indent are allowed (four is an indented code block), and a hash-only line like `## ##` mints no node (#4790, #4791, thanks @jaimemartinez).
|
||||
- Fix: **markdown** fenced code blocks are tracked by CommonMark rules (backtick and tilde fences, info strings, matching close length), so a line that looks like a heading inside a fence no longer leaks as structure, and a heading after a `~~~` block that contains a ` ``` ` line is no longer lost (#4787, #4788, thanks @jaimemartinez).
|
||||
- Fix: **yaml** structural extraction reads the composed node tree, so keys carry their written spelling and their own source line instead of all landing on line 1, and YAML 1.1 bare keys like `on`/`off`/`yes`/`no` are no longer folded to booleans (a workflow `on:` block is extracted, not turned into a `True` node) (#4784, #4785, thanks @jaimemartinez).
|
||||
- Fix: **razor** a component's `@implements` interfaces are extracted as `implements` edges instead of being silently dropped (#4820, thanks @ayushcodes10).
|
||||
- Fix: **terraform** an aliased provider block gets its own alias-qualified node (so two `provider "aws"` blocks no longer collapse into one and lose attributes), and a `provider = aws.west` reference resolves to it instead of dangling; a `local` literally named `provider` is no longer misread (#4819, thanks @ayushcodes10).
|
||||
- Fix: **cobol** paragraphs that follow a nested `END PROGRAM` reattach to the enclosing program instead of sticking to the nested one, via a program stack (#4824, thanks @ayushcodes10).
|
||||
- Fix: **blade** a `wire:click` directive binds the bare method name: dotted modifiers (`wire:click.prevent="submit"`) are matched, call arguments are trimmed from the name (`deleteItem(5)` binds `deleteItem`), and a `$`-prefixed magic action mints no fabricated edge (#4823, thanks @ayushcodes10).
|
||||
- Fix: **pascal** a `record` is recognised as a type with its own methods in the regex fallback (the default path without the optional `pascal` extra), matching the tree-sitter path; `operator` members are extracted too (#4825, thanks @ayushcodes10).
|
||||
- Fix: **vbnet** an `Operator` declaration is extracted as an `operator`-kind member of its class and its body is walked for calls, so a helper call inside an operator no longer vanishes (#4821, thanks @ayushcodes10).
|
||||
- Fix: **fortran** a `call` resolves to the subroutine it actually names instead of a target salted with the calling file's name (which never resolved), using the extractor's own cross-file stub idiom (#4795, thanks @ayushcodes10).
|
||||
- Fix: **cli** `graphify query --help`/`-h` (and now `graphify explain --help`/`-h`) with nothing else prints usage instead of running a literal query for the text "--help"; a longer question that merely contains "--help" as a substring still runs as a query (#4830, thanks @curl-man).
|
||||
- Fix: **js** a nested (inner) function no longer leaks into the file-wide name map, so a call elsewhere in the file binds to the top-level function of that name rather than an inner one it cannot see; recursion, shadowing and sibling scopes resolve correctly (ports the Python scope scheme to JS/TS) (#4767, thanks @smngvlkz).
|
||||
- Fix: **ocaml** every binding in an `and`-chained `module ... and ...` or `class ... and ...` is extracted, not just the first, so later bindings are no longer silently dropped; each carries its own source line (#4822, thanks @ayushcodes10).
|
||||
- Fix: **verilog** a SystemVerilog class `task` method is modeled like a `function` one (its own node, `method` edge and parameter-type references), and a task-local variable no longer leaks as a false field reference on the class (#4774, thanks @ayushcodes10).
|
||||
- Fix: **build** an edge with no `relation` is dropped instead of persisted, on both the build and the raw `--no-cluster` write paths, and alias folding (`relationship` to `relation`) runs before the check (#4810, thanks @legendteddy; reproducer also filed as #4826 by @sunhouy).
|
||||
- Fix: **build** the shrink guard counts a saved document-mention node that folds into its AST file twin on reload as present, not lost, so a cluster-only write is no longer refused when nothing was actually lost (#4778, #4779, thanks @AndresDiagoM).
|
||||
- Fix: **detect** a linked git worktree whose main checkout resolves inside the scan root is pruned, so a sibling worktree no longer gets indexed as a second full copy of the repo (#4683, #4833, thanks @barlowa124; duplicate work in #4685 by @AndresDiagoM).
|
||||
- Fix: **resolution** an inline comment in a pnpm-workspace glob is stripped per YAML rules, and a glob that `Path.glob` rejects (a `**` component or an absolute pattern) is skipped with a warning instead of crashing the whole `extract` run (#4681, #4687, thanks @Deepjyoti-Sarmah).
|
||||
- Fix: **report** a community hub `[[wikilink]]` is slugged through the same `export._obsidian_safe_stem` the export uses, so the link matches the file the export actually writes instead of dangling (#4696, thanks @ayushcodes10).
|
||||
- Fix: **wiki** a community relabelled only by letter case keeps its article instead of having the sweep delete the file the run just wrote; on a case-sensitive filesystem the stale lower-case twin is unlinked rather than renamed over the fresh file (which would silently restore the old body) (#4508, #4798, thanks @dupeisen).
|
||||
- Fix: **query** filler verbs `get`/`gets`/`got`/`getting` are dropped from query terms (like the existing `work`/`works`), so a framework hub labelled "Get" is not pulled in as a BFS seed by an exact-match bonus; node lookups for a literal `Get` still resolve (#4686, thanks @AndresDiagoM).
|
||||
|
||||
## 0.9.96 (2026-10-25)
|
||||
|
||||
- Security: **deps** the Pillow floor is raised to `>=13.0.0` on Python 3.11+ (staying at `>=12.3.0` on 3.10, which Pillow 13 no longer supports) and pypdf to `>=6.19.0`, and the lockfile is refreshed to patched versions of transitive dependencies (pyjwt, cryptography, certifi, urllib3, anyio, fsspec, soupsieve, virtualenv). This clears the bulk of the open Dependabot advisories; the Pillow image-parsing CVEs are only patched upstream for Python 3.11+, so a 3.10 install keeps the newest 3.10-compatible Pillow.
|
||||
- Fix: **llm** a chunk that failed before returning a response no longer has its files reported as model omissions; the warning distinguishes a failed chunk from a genuine omission, and both are still re-dispatched (#3616, #4752, thanks @jaimemartinez; reported by @GREYGROUPJP).
|
||||
- Fix: **watch** a Markdown file that `detect()` classifies as a paper (arXiv markers, an Abstract) is included in the watch quick-scan rebuild instead of contributing zero nodes; a paper that already has a semantic layer is still excluded from the AST quick-scan (#4750, #4751, thanks @jaimemartinez; reported by @yeochul-jeon).
|
||||
- Fix: **prs** every unfinished CheckRun status (`WAITING`, `REQUESTED`, `PENDING`, ...) counts as pending CI, so a PR gated on a deployment-protection job is no longer read as ready (#4730, thanks @rudycelekli).
|
||||
- Fix: **export** an Obsidian note lists every parallel relation between two nodes (for example both `imports` and `calls`) instead of only the first edge (#4731, thanks @rudycelekli).
|
||||
- Fix: **build** a hyperedge whose members are given under the `members`/`node_ids` aliases has its numeric member ids coerced to strings like the canonical `nodes` list, so the hyperedge is no longer dropped (#4732, thanks @rudycelekli).
|
||||
- Fix: **llm** a code node whose confidence is written in a different case (`extracted`/`Extracted`) is still evidence-checked before it folds to the `EXTRACTED` enum, so an un-verified node is not presented as solid (#4733, thanks @rudycelekli).
|
||||
- Fix: **python** a member call binds to the method it actually spells rather than a case/underscore-folded twin (`run()` no longer resolves to `_run()`); a lone folded method still resolves, and a genuine collision fails closed (#4734, thanks @rudycelekli).
|
||||
- Fix: **zig** a call no longer crosses between a method and a same-named free function; a bare call binds the free function and a receiver call binds the method (#4755, thanks @ayushcodes10).
|
||||
- Fix: **dart** an unnamed `extension on T { }` declaration is detected and extracted (the name is optional), so its members attach to the extended type (#4741, thanks @ayushcodes10).
|
||||
- Fix: **llm** the DeepSeek backend sends its output cap as `max_tokens` (which DeepSeek honours) rather than `max_completion_tokens` (which it ignores), so responses are no longer silently uncapped (#4739, #4753, thanks @Ethereal49; reported by @snapp-kenya).
|
||||
- Fix: **extract** XAML codebehind (`*.xaml` to `*.xaml.cs`) resolves deterministically regardless of directory iteration order, so a graph built on a case-sensitive filesystem is stable (#4747, thanks @anishraja04).
|
||||
- Fix: **extract** the AST cache hit rate is reported over the file total, not the uncached set, so a warm run no longer prints a misleading "100% uncached" line (#4740, #4746, thanks @Deepjyoti-Sarmah; reported by @lavaxun).
|
||||
- Fix: **dedup** a node id legitimately shared by two files as a `module`/`namespace` no longer prints a spurious "minted by two different files" warning (#4756, thanks @idachev).
|
||||
- Fix: **python** the member-call resolver binds only Python callers to Python targets, so a same-named class in another language is no longer mis-bound as a call (#4757, thanks @idachev).
|
||||
- Fix: **cli** the PreToolUse hook reminders are worded as facts rather than imperatives, so the agent's tool-result stream no longer reads them as prompt injection and ignores them (#2202, #4764, thanks @smngvlkz).
|
||||
- Fix: **llm** the Ollama context window is sized from an estimate that counts non-Latin characters as whole tokens and from the real system-prompt length, so a non-English or long prompt is no longer silently truncated (#4414, #4761, thanks @smngvlkz).
|
||||
- Fix: **cli** `graphify extract` records each run's token usage to `graphify-out/cost.json` (the same ledger the skill writes), so a standalone extract refresh updates the cost history (#1769, #4765, thanks @smngvlkz).
|
||||
- Fix: **ts** chained TypeScript decorators (`@(Link().toMany())`) are recovered as a decorator reference, and a lossy-parse warning names the real error region (#4711, #4715, thanks @Deepjyoti-Sarmah).
|
||||
- Fix: **js** a `const X = require('pkg')` binding for an external package keeps its node (with the package as source) so `new X()` still resolves, while a require of a corpus-local file still folds to the required module (#4688, #4702, thanks @ayushcodes10).
|
||||
- Fix: **detect** generated MSBuild `obj/` and `bin/` output is pruned only when build evidence is present (restore/runtime markers nearby), so a C# project scanned after a build no longer ingests generated sources while a real `src/bin` stays (#4742, thanks @Great-Peace).
|
||||
- Fix: **watch** each watch rebuild is bounded by `GRAPHIFY_REBUILD_TIMEOUT` (default 600s, `0` disables), with a thread-Timer fallback where `SIGALRM` is unavailable or `watch()` runs off the main thread (a `SIGALRM` arm there raises `ValueError` and would tear the watcher down before the rebuild ran), so a hung rebuild no longer stalls the watcher (#2173, #4724, thanks @danieldutu).
|
||||
- Fix: **robot** each duplicate test-case name gets its own node (salted by line), so two tests with the same name are kept distinct (#4697, thanks @ayushcodes10).
|
||||
- Fix: **vbnet** external namespaces and types emit a sourceless stub carrying an empty `source_file` sentinel like other languages, instead of a node that fails validation (#4725, #4728, thanks @madanlalit; reported by @alopezradicle).
|
||||
- Fix: **rust** a `use` is scoped to the crate it names, so `use serde_json::Value` no longer resolves to a same-named type in another crate; a named `pub use` re-export is followed and a manifest-less binding stays `INFERRED` (#4699, #4712, thanks @Deepjyoti-Sarmah).
|
||||
- Fix: **python** a call through a field injected from a constructor parameter, or through a local typed by a method's return annotation, resolves to the target method (`INFERRED`); it requires a single unambiguous producer and class (#4726, thanks @keny11300).
|
||||
- Fix: **dedup** an LLM-marked cross-document reference stub that collides with its real definition is namespaced instead of silently dropped, so neither node is lost (#4738, #4743, thanks @SinghAman21; reported by @snapp-kenya).
|
||||
- Perf: **update** a `graphify update` with no relevant input change skips the detect/extract/build pipeline and leaves the outputs untouched, keyed on the scan file-set, config, `.graphifyrc`, extractor epoch, and an output-completeness stamp; a scanned file with no manifest row (including one whose extraction previously failed) still forces a full rebuild so a later fix is never skipped (#4740, #4748, thanks @Deepjyoti-Sarmah; reported by @lavaxun).
|
||||
|
||||
## 0.9.95 (2026-10-23)
|
||||
|
||||
Twenty-one community pull requests. A security pass on install: the skill-install writes go through randomly-named temp files instead of predictable ones, so a pre-planted symlink can no longer redirect a write. Extraction: Python, Go, C++ and Rust explicit type aliases (and Rust `union` items) are extracted as type nodes so references resolve instead of minting sourceless stubs, each C# method overload gets its own node bound by argument count, and a package.json dependency's manifest entry links to the node that references it. Plus a one-root-per-repo tree on merged graphs, extended-length cache paths on Windows, and binary media no longer counted as text. The AST cache schema is bumped, so the first build after upgrading re-extracts.
|
||||
|
||||
- Fix: **security** the skill install stages every write (version stamp, `SKILL.md`, references) through a randomly-named `mkstemp`/`mkdtemp` file created with `O_EXCL` and restrictive mode instead of a predictable `*.tmp` name, so a local attacker who pre-creates a symlink at that path can no longer redirect the write to clobber an arbitrary file; the final move stays atomic (#4513, thanks @Mahdifotohi).
|
||||
- Fix: **python** an explicit module-level type alias (`X: TypeAlias = ...`, `type X = ...`, `NewType`) is extracted as a type node, so a field or parameter typed by the alias resolves to it instead of minting a sourceless stub; an implicit assignment, a local alias, or a re-export is left alone (#4578, thanks @madhusudanpatnaik).
|
||||
- Fix: **go** a `type A = B` alias is extracted as a type node (tree-sitter parses it as a `type_alias`, not a `type_spec`), so references resolve to it; a re-export (`type Field = pkg.Field`) mints no node (#4579, thanks @madhusudanpatnaik).
|
||||
- Fix: **cpp** a namespace-scope `using A = B;` or `typedef B A;` alias is extracted as a type node so references resolve; a member alias inside a class and a same-name re-export are excluded (#4580, thanks @madhusudanpatnaik).
|
||||
- Fix: **rust** a `type` alias and a `union` item are extracted as type nodes (a union's fields reference their types like a struct), so references resolve instead of minting stubs; an impl-associated `type` is excluded (#4581, Refs #4285, thanks @madhusudanpatnaik; reported by @jonatasbcardio-boop).
|
||||
- Fix: **csharp** each method overload gets its own node and source location instead of collapsing to one, and a call binds to the overload matching its argument count, across in-file, receiver-typed, bare-name cross-file, partial-class, and interface-dispatch resolution; a non-overloaded method keeps its id (#4584, #4591, thanks @Mpasha17; reported by @TerraVenil).
|
||||
- Fix: **tree** `graphify export tree` on a merged multi-repo graph gives each repo its own root (keyed by the repo tag) instead of conflating same-path files from different repos; untagged nodes are not counted as a repo (#4524, #4525, thanks @AromalBiju1).
|
||||
- Fix: **cache** AST cache entries are read and written through Windows extended-length (`\\?\`) paths, so a deep cache path over the 260-character limit no longer fails extraction with a `FileNotFoundError`; a no-op off Windows (#4542, thanks @omsenjalia).
|
||||
- Fix: **detect** a binary media file (an image or audio/video) is no longer read and counted as text toward the corpus word total; an SVG stays counted as the XML text it is (#4548, thanks @kalkaran).
|
||||
- Fix: **json_config** a `package.json` dependency's manifest entry links (`declares`) to the ref node that importing code resolves to, so the manifest entry and its importers share one node instead of being orphaned; the entry is relabelled `name@range` (#4569, #4572, thanks @Deepjyoti-Sarmah; reported by @BiSide).
|
||||
- Feature: **yaml** `.yaml`/`.yml` files are now extracted structurally (a file node plus `contains` edges to keys) and classified as code rather than documents, so Helm charts, Kubernetes manifests, and CI pipelines contribute nodes to a code-only or `--update` run instead of nothing, matching how `.json` is handled. Multi-document streams (`---` separators) are walked per document; a data array, an OpenAPI/Swagger spec, a JSON-schema-in-YAML, and a flat data bundle are skipped so data-heavy YAML does not mint orphan nodes; parsing uses `safe_load` so a `!!python/...` tag never executes; output is bounded (1 MiB, 500 pairs, depth 6). The AST cache schema is bumped, so the first build after upgrading re-extracts (#2214, #4706, thanks @nothariharan; reported by @dchavezf).
|
||||
- Fix: **extract** a bare call that resolves to a same-named symbol only because the caller imported that symbol's module (`from b import other`, then a call to a `_make_id` defined in both `a.py` and `b.py`) is no longer promoted to `EXTRACTED`; the edge is still emitted for connectivity but stays `INFERRED`, so a symbol that was never imported is not falsely certified. A real symbol import (`from a import _make_id`) still resolves `EXTRACTED` (#2945, #4707, thanks @nothariharan; reported by @TotalUnitManagement).
|
||||
- Fix: **security** the SSRF guard blocks a host that resolves to a multicast address (`224.0.0.0/4`, `ff00::/8`), closing a gap alongside the existing private/reserved/loopback/link-local checks (#4708, thanks @Dextheking1).
|
||||
- Fix: **security** the Obsidian export sanitizes a node's file-type and confidence before emitting them as frontmatter `tags`, so a crafted value cannot break out of the YAML list into a sibling key, matching how community tags are already sanitized (#4709, thanks @Dextheking1).
|
||||
- Fix: **security** the Google Workspace shortcut sidecar escapes a file id or url through full YAML double-quoted-scalar escaping (tab, C0/DEL controls, and the Unicode line breaks U+2028/U+2029/U+0085), so a hostile shortcut file cannot inject frontmatter keys (#4710, thanks @Dextheking1).
|
||||
- Fix: **affected** `graphify affected <path>` resolves a path whose file-node label was disambiguated by the shared-basename suffix pass (for example two `hooks.py` from different directories), reusing the canonical file-label predicate instead of a bare basename match (#4698, #4713, thanks @Deepjyoti-Sarmah; reported by @karsan8119).
|
||||
- Fix: **build** a raw (`--no-cluster`) build resolves an import endpoint through the same old-stem alias index the clustered build uses, and mints an external stub only after resolution, so the raw graph no longer freezes an import onto a stub when the clustered graph resolves it (#4670, #4676, thanks @nothariharan; reported by @xiongjianxu).
|
||||
- Fix: **cross-repo** an Objective-C class declared in one repo's header and implemented in another repo's `.m` binds a member call to the implementation, the cross-repo analog of the same-repo split-dir fix; two same-named classes that both define the selector stay ambiguous (#4690, #4691, thanks @xiongjianxu).
|
||||
- Fix: **hooks** the rebuild hook runs from the checkout's top level (derived from the git common dir, falling back to `--show-toplevel`), so a stray `graphify-out/` in a subdirectory can no longer root the rebuild at the wrong place and walk an enormous tree (#3258, #4689, thanks @jaimemartinez; reported by @dsfaccini).
|
||||
- Fix: **objc** `NS_CLOSED_ENUM` declarations are extracted as enums with their cases, the same as `NS_ENUM`/`NS_OPTIONS`; the AST cache schema is bumped so the first build after upgrading re-extracts (#4705, thanks @Jvxoq).
|
||||
- Fix: **sql** a `CREATE TABLE` whose column default the SQL grammar cannot parse (for example MySQL/MariaDB `DEFAULT current_timestamp()`) is recovered from the ERROR node instead of being dropped, so the table and its foreign-key references still resolve; the AST cache schema is bumped (#4613, #4677, thanks @08raviyadav; reported by @AirRunner).
|
||||
|
||||
## 0.9.94 (2026-10-22)
|
||||
|
||||
Nineteen community pull requests. A security pass on ingestion: a fetched URL with no hostname, with a malformed or zero port, or with embedded `user:pass@` credentials is now rejected before the request leaves, on the first fetch and on every redirect, and a text capture no longer follows a dangling symlink out of the corpus. Extraction and resolution: a Maven POM contributes only its own dependencies, a JS/TS member call on an untyped receiver stops guessing a same-named method in the same file, a CommonJS `require` binding no longer shadows the class the required file exports, and Objective-C category node ids stay repo-relative instead of embedding the absolute checkout path. SQL gets its own pass: T-SQL bracketed names are unbracketed, a `GO` batch separator ends the statement, cross-file table stubs fold onto their real definition, and a procedure emits `reads_from`/`writes_to` edges. Plus a markdown bare method only links when its class is cited, the MCP node lookup refuses a substring near-miss instead of answering with an unrelated node, a cross-repo edge points at the call site, Objective-C calls resolve across a split header/impl, an incremental build stops re-queuing files an extractor declined by design, a quoted Codex hook command for install paths with spaces, an IPv6 bracketed-`Host` serve fix, and a complete, drift-guarded `--platform` list in `--help`. The AST cache schema is bumped, so the first build after upgrading re-extracts.
|
||||
|
||||
- Fix: **security** `validate_url` rejects a fetched URL that has no hostname (`http:///path`), a non-numeric, out-of-range, or zero port, or embedded `user:pass@` credentials, before the request is made and again on every redirect, so a malformed or credential-bearing URL is no longer fetched or persisted into the graph; a normal `@` in a path or query and a valid high port still pass (#4643, #4644, #4645, thanks @cellrishi-code).
|
||||
- Fix: **manifest** a Maven `pom.xml` contributes only its own `<dependencies>` (including those under `<profiles>`), not the version pins under `<dependencyManagement>` or a build plugin's own `<dependencies>`, so a parent or BOM POM no longer emits dependency edges it only manages (#4596, thanks @jayhemnani9910).
|
||||
- Fix: **js** a member call on an untyped receiver (`x.foo()` where `x` has no known type) is deferred to receiver-typed resolution instead of binding to a same-named method elsewhere in the file, so a spurious self-loop or cross-call edge is no longer emitted; `this.foo()`, a typed receiver, and a locally instantiated receiver still resolve (#4598, #4605, thanks @ayushcodes10; reported by @SaschaAndresGrimm).
|
||||
- Fix: **js** 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; a real `const x = factory()` binding still keeps its node (#4621, #4634, thanks @lab1207; reported by @sub4biz).
|
||||
- Fix: **extract** an Objective-C category's class and method node ids stay repo-relative instead of embedding the absolute checkout path, so a category file like `Foo+Cat.h` yields portable ids that match across machines and merge cleanly; two same-named categories in different directories stay distinct (#4666, #4642, thanks @madhusudanpatnaik; reported by @xiongjianxu).
|
||||
- Fix: **codex** the generated Codex PreToolUse hook command quotes the graphify executable path, so an install under a path containing a space no longer builds a broken hook command, matching the existing Claude and Gemini hooks (#4662, thanks @supercell02).
|
||||
- Fix: **serve** an IPv6 HTTP bind accepts its own bracketed `Host` header (`[::1]:port`), so a server bound to an IPv6 loopback no longer refuses every request with a 421 (#4656, thanks @zydo).
|
||||
- Fix: **ingest** a text capture never writes through an existing entry: the free-path search uses `lstat`, so a name that is a dangling symlink is treated as occupied and the capture is diverted instead of following the link and writing outside the corpus (#4657, thanks @zydo).
|
||||
- Fix: **cli** `graphify --help` lists every accepted `--platform` value (it had omitted amp, copilot, kilo, kimi, and antigravity-windows); the list is derived from the same source as the install usage so the two cannot drift, with a guard test (#4655, thanks @zydo).
|
||||
- Fix: **sql** T-SQL bracketed identifiers (`[dbo].[Orders]`) are unbracketed so a name matches across styles, and a stored procedure's body emits `reads_from`/`writes_to` edges for the tables it reads and writes; aliases, variables, temp tables, strings, and comments never become targets (#4635, #4649, thanks @Deepjyoti-Sarmah; reported by @RuVl).
|
||||
- Fix: **sql** a `GO` batch separator (a client command, not a terminator) ends the statement, so a statement after a `GO` with no trailing `;` parses on its own instead of merging into one malformed node; a `GO` inside a string, comment, or column name is left alone (#4651, #4652, thanks @Deepjyoti-Sarmah).
|
||||
- Fix: **sql** a table referenced before its `CREATE TABLE` is seen folds onto the real definition instead of staying a separate stub, and a schema-qualified name binds correctly, while two genuinely different tables in different schemas (`dbo.Orders` vs `sales.Orders`) stay distinct and a SQL stub no longer binds to a same-named class in another language (#4653, #4654, thanks @Deepjyoti-Sarmah).
|
||||
- Fix: **markdown** a bare method name in prose (for example `redis` where only `Cache.redis` exists) only links to the method when the owning class is cited in the same document, so a plain word is no longer turned into a false `references` edge; a qualified `Class.method` or `Class::method` mention still resolves (#4609, #4617, thanks @nothariharan; reported by @saad-siddique).
|
||||
- Fix: **mcp** the `get_node` and `get_neighbors` tools, and the `explain` command, refuse a substring-only near-miss with candidate suggestions instead of returning an unrelated node as the answer; an exact or prefix match still resolves (#3917, #4618, thanks @nothariharan; reported by @Alexandre-Aktisea).
|
||||
- Fix: **cross-repo** a cross-repo call edge points at the real call site rather than the caller's header declaration, so the edge's `source_file` and `source_location` name the line that makes the call (#4668, #4669, thanks @xiongjianxu).
|
||||
- Fix: **extract** an incremental build no longer re-queues, on every run, a code file an extractor declined by design (for example a virtual-workspace manifest); the file is marked `ast_empty` and left alone, while a genuinely failed or transiently empty extraction is still retried (#2543, #4672, thanks @xiongjianxu).
|
||||
- Fix: **objc** a member call resolves when a class is split across a header and an implementation in different directories, binding the selector to its single definition; two unrelated same-named classes that both define the selector stay ambiguous and get no edge (#4673, #4674, thanks @xiongjianxu).
|
||||
|
||||
## 0.9.93 (2026-10-20)
|
||||
|
||||
Twenty-two community pull requests. Extraction: a reference to a Kotlin type alias, C# delegate, Swift macro, Dart typedef, Python module function or Rust sibling-module `use` now resolves to its real declaration instead of minting a sourceless stub; Metal/CUDA GPU qualifiers no longer mint god nodes; `extern "C"` headers route to the C++ extractor; an extensionless script with a versioned-interpreter shebang is classified; and Obsidian vault-relative wikilinks resolve. Plus a credential-redaction pass on rationale labels, a node-confidence fold, a truncated-reply label decode, a `.graphifyrc` BOM fix, a GraphML multigraph export fix, two-repo file disambiguation in explain and path, a PDF-read warning, no skill writes on `--version`/`--help`, two PR-tooling fixes (slashed default branch, legacy CI statuses), and a skill partly-read-file recovery so a long file a subagent only skimmed is retried on the next `--update` instead of silently kept half-read. The AST cache schema is bumped, so the first build after upgrading re-extracts.
|
||||
|
||||
+1
-1
@@ -36,7 +36,7 @@ This Code of Conduct applies within all community spaces, including the GitHub r
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the project maintainers at safi@graphify.com, or by directly messaging a Community Leader on the [Graphify Discord server](https://discord.gg/XDnKVpzdXB).
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the project maintainers at safi@graphify.com, or by directly messaging a Community Leader on the [Graphify Discord server](https://discord.gg/graphify).
|
||||
|
||||
All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident.
|
||||
|
||||
|
||||
+1
-1
@@ -149,7 +149,7 @@ Focus on the problem first, proposed behavior, alternatives, and compatibility c
|
||||
- **What should not be committed**: Local cache (`.graphify_cached.json`), generated node artifacts outside of the expected outputs.
|
||||
|
||||
## Getting Help
|
||||
- **Discord**: Join the [Graphify Discord](https://discord.gg/XDnKVpzdXB) for questions and discussion.
|
||||
- **Discord**: Join the [Graphify Discord](https://discord.gg/graphify) for questions and discussion.
|
||||
- **Issues**: Search [existing issues](https://github.com/Graphify-Labs/graphify/issues) before opening a new one.
|
||||
- **Discussions**: Use GitHub issues for bugs and feature requests, Discord for open-ended questions.
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -104,7 +104,7 @@ Shortest path (3 hops):
|
||||
FastAPI --uses--> DefaultPlaceholder <--references-- get_request_handler() --references--> ModelField
|
||||
```
|
||||
|
||||
Every edge carries a **confidence tag** (`EXTRACTED` = explicit in the source, `INFERRED` = derived by resolution), so you can tell what was read directly from what was inferred. `graphify query "<question>"` returns a scoped subgraph for a plain-language question, and `graphify path A B` traces how any two things connect.
|
||||
Every edge carries a **confidence tag** (`EXTRACTED` = explicit in the source, `INFERRED` = derived by resolution), so you can tell what was read directly from what was inferred. `graphify query "<question>"` returns a scoped subgraph for a plain-language question, and `graphify path A B` traces how any two things connect, ending with the path's overall confidence: that of its weakest hop.
|
||||
|
||||
---
|
||||
|
||||
@@ -247,12 +247,15 @@ for example `graphify claude install --project` or `graphify codex install --pro
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Devin CLI | `graphify devin install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
| Google Antigravity (Windows) | `graphify antigravity install` (auto-detected on Windows) |
|
||||
|
||||
Codex users also need `multi_agent = true` under `[features]` in `~/.codex/config.toml` for parallel extraction. CodeBuddy uses the same Agent tool and PreToolUse hook mechanism as Claude Code. Factory Droid uses the `Task` tool for parallel subagent dispatch. OpenClaw and Aider use sequential extraction (parallel agent support is still early on those platforms). Trae uses the Agent tool for parallel subagent dispatch and does **not** support `PreToolUse` hooks, so AGENTS.md is the always-on mechanism.
|
||||
|
||||
`--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`.
|
||||
|
||||
@@ -268,6 +271,7 @@ Pi has no `PreToolUse` hook, so `graphify pi guard install` registers a native P
|
||||
| `google` | Google Sheets rendering | `uv tool install "graphifyy[google]"` |
|
||||
| `video` | Video/audio transcription (faster-whisper + yt-dlp) | `uv tool install "graphifyy[video]"` |
|
||||
| `mcp` | MCP stdio server | `uv tool install "graphifyy[mcp]"` |
|
||||
| `watch` | Auto-rebuild on file changes (`graphify watch`) | `uv tool install "graphifyy[watch]"` |
|
||||
| `neo4j` | Neo4j push support | `uv tool install "graphifyy[neo4j]"` |
|
||||
| `falkordb` | FalkorDB push support | `uv tool install "graphifyy[falkordb]"` |
|
||||
| `svg` | SVG graph export | `uv tool install "graphifyy[svg]"` |
|
||||
@@ -301,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.
|
||||
@@ -369,10 +373,26 @@ See the [full command reference](#full-command-reference) below.
|
||||
|
||||
---
|
||||
|
||||
## Labeling and rendering limits
|
||||
|
||||
- **`--batch-size`**: 100 communities per labeling call by default, sized for a ~16k-token context (~150 tokens/community). Use `--batch-size 40` for an 8k window. Context overflow is not split-retried; failed batches keep hub-derived names.
|
||||
- **`--missing-only`**: `label --missing-only` keeps existing labels and names only unnamed / `Community N` entries. Use `label` (full relabel) to refresh names after the community set changes.
|
||||
- **`.graphify_labels.json.sig`**: records the community membership signature; labels survive a re-cluster only while it matches.
|
||||
- **`export html`**: 5,000-node default; above it graphify renders an aggregated community view. Use `--node-limit N`. `GRAPHIFY_VIZ_NODE_LIMIT` / `.graphifyrc` `viz_node_limit=N` apply to `cluster-only`, `update`, `watch`, and hooks, not `export html`.
|
||||
- **Leiden fallback**: without the `leiden` extra, clustering silently uses networkx Louvain. Switching later reshuffles every community, so plan a full relabel.
|
||||
|
||||
---
|
||||
|
||||
## Ignoring files
|
||||
|
||||
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
|
||||
|
||||
@@ -392,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
|
||||
@@ -410,6 +444,9 @@ 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.
|
||||
|
||||
---
|
||||
|
||||
## Privacy
|
||||
@@ -464,7 +501,7 @@ Every command and flag, with examples: **[CLI reference](https://docs.graphify.c
|
||||
|
||||
Contributions are welcome. See **[CONTRIBUTING.md](CONTRIBUTING.md)** for the development setup, the test and CI-parity commands, the git workflow, and what makes a strong contribution (worked examples and extraction bug reports are the most useful). Architecture and how to add a language: [ARCHITECTURE.md](ARCHITECTURE.md).
|
||||
|
||||
New here? Say hi on [Discord](https://discord.gg/XDnKVpzdXB) or in [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
New here? Say hi on [Discord](https://discord.gg/graphify) or in [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
|
||||
---
|
||||
|
||||
@@ -494,7 +531,7 @@ Building something in the graphify ecosystem? That is encouraged. If your projec
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
+4
-1
@@ -28,7 +28,7 @@ graphify is a **local development tool**. It runs as a Claude Code skill and opt
|
||||
|
||||
| Vector | Mitigation |
|
||||
|--------|-----------|
|
||||
| SSRF via URL fetch | `security.validate_url()` allows only `http` and `https` schemes, blocks private/loopback/link-local IPs, and blocks cloud metadata endpoints. Redirect targets are re-validated. All fetch paths including tweet oEmbed go through `safe_fetch()`. |
|
||||
| SSRF via URL fetch | `security.validate_url()` allows only `http` and `https` schemes, blocks private/loopback/link-local IPs, and blocks cloud metadata endpoints. It also rejects embedded credentials, port 0, and missing hostnames. Redirect targets are re-validated. All fetch paths including tweet oEmbed go through `safe_fetch()`. |
|
||||
| Oversized downloads | `safe_fetch()` streams responses and aborts at 50 MB. `safe_fetch_text()` aborts at 10 MB. |
|
||||
| Non-2xx HTTP responses | `safe_fetch()` raises `HTTPError` on non-2xx status codes - error pages are not silently treated as content. |
|
||||
| Path traversal in MCP server | `security.validate_graph_path()` resolves paths and requires them to be inside `graphify-out/`. Also requires the `graphify-out/` directory to exist. |
|
||||
@@ -38,6 +38,9 @@ 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` 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. |
|
||||
|
||||
### What graphify does NOT do
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ Thanks for using graphify. Here is where to go, depending on what you need.
|
||||
|
||||
- **Docs:** [docs.graphify.com](https://docs.graphify.com) — guides, command reference, and integrations. Start here.
|
||||
- **GitHub Discussions:** [Discussions](https://github.com/Graphify-Labs/graphify/discussions) for longer-form questions, ideas, and show-and-tell.
|
||||
- **Discord:** [discord.gg/XDnKVpzdXB](https://discord.gg/XDnKVpzdXB) for real-time chat with the community and maintainers.
|
||||
- **Discord:** [discord.gg/graphify](https://discord.gg/graphify) for real-time chat with the community and maintainers.
|
||||
|
||||
Please search the docs and existing discussions/issues before posting — your question may already be answered.
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
---
|
||||
|
||||
@@ -97,5 +97,6 @@ Each edge has:
|
||||
- `confidence` — `EXTRACTED`, `INFERRED`, or `AMBIGUOUS`
|
||||
- `confidence_score` — float (INFERRED only)
|
||||
- `source_file` — where the relationship was found
|
||||
- `also_seen` — optional; when the same relation between the same two nodes was found more than once, the edge keeps the highest-confidence copy and lists each other copy's `confidence`, `confidence_score`, `source_file` and `source_location` here, weakest first. `graphify path` shows their tags next to the edge's own (`[AMBIGUOUS/INFERRED]`)
|
||||
|
||||
Hyperedges (group relationships connecting 3+ nodes) live in `G.graph["hyperedges"]`.
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -464,7 +464,7 @@ viz_node_limit=0
|
||||
|
||||
المساهمات مرحّب بها. راجع **[CONTRIBUTING.md](../../CONTRIBUTING.md)** لإعداد التطوير، وأوامر الاختبار وتكافؤ CI، وسير عمل git، وما يصنع مساهمة قوية (الأمثلة العملية وتقارير أخطاء الاستخراج هي الأكثر فائدة). المعمارية وكيفية إضافة لغة: [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
جديد هنا؟ ألقِ التحية على [Discord](https://discord.gg/XDnKVpzdXB) أو في [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
جديد هنا؟ ألقِ التحية على [Discord](https://discord.gg/graphify) أو في [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
|
||||
---
|
||||
|
||||
@@ -494,7 +494,7 @@ Made with [contrib.rocks](https://contrib.rocks).
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -464,7 +464,7 @@ Každý příkaz a přepínač, s příklady: **[CLI reference](https://docs.gra
|
||||
|
||||
Příspěvky jsou vítány. Viz **[CONTRIBUTING.md](../../CONTRIBUTING.md)** pro vývojové nastavení, příkazy pro testy a paritu s CI, git workflow a to, co dělá silný příspěvek (vypracované příklady a hlášení chyb extrakce jsou nejužitečnější). Architektura a jak přidat jazyk: [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
Jste tu noví? Pozdravte nás na [Discordu](https://discord.gg/XDnKVpzdXB) nebo v [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
Jste tu noví? Pozdravte nás na [Discordu](https://discord.gg/graphify) nebo v [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
|
||||
---
|
||||
|
||||
@@ -494,7 +494,7 @@ Stavíte něco v ekosystému graphify? To je podporováno. Pokud váš projekt p
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -464,7 +464,7 @@ Hver kommando og hvert flag, med eksempler: **[CLI-reference](https://docs.graph
|
||||
|
||||
Bidrag er velkomne. Se **[CONTRIBUTING.md](../../CONTRIBUTING.md)** for udviklingsopsætningen, test- og CI-paritetskommandoerne, git-workflowet og hvad der gør et stærkt bidrag (gennemarbejdede eksempler og fejlrapporter om ekstraktion er de mest nyttige). Arkitektur og hvordan man tilføjer et sprog: [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
Ny her? Sig hej på [Discord](https://discord.gg/XDnKVpzdXB) eller i [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
Ny her? Sig hej på [Discord](https://discord.gg/graphify) eller i [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
|
||||
---
|
||||
|
||||
@@ -494,7 +494,7 @@ Bygger du noget i graphify-økosystemet? Det opmuntres. Hvis dit projekt bruger
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -464,7 +464,7 @@ Jeder Befehl und jedes Flag, mit Beispielen: **[CLI-Referenz](https://docs.graph
|
||||
|
||||
Beiträge sind willkommen. Siehe **[CONTRIBUTING.md](../../CONTRIBUTING.md)** für die Entwicklungseinrichtung, die Test- und CI-Paritätsbefehle, den Git-Workflow und was einen starken Beitrag ausmacht (durchgearbeitete Beispiele und Extraktions-Fehlerberichte sind am nützlichsten). Architektur und wie man eine Sprache hinzufügt: [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
Neu hier? Sagen Sie Hallo auf [Discord](https://discord.gg/XDnKVpzdXB) oder in den [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
Neu hier? Sagen Sie Hallo auf [Discord](https://discord.gg/graphify) oder in den [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
|
||||
---
|
||||
|
||||
@@ -494,7 +494,7 @@ Bauen Sie etwas im graphify-Ökosystem? Das ist erwünscht. Wenn Ihr Projekt "gr
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -456,7 +456,7 @@ viz_node_limit=0
|
||||
|
||||
Οι συνεισφορές είναι ευπρόσδεκτες. Δείτε το **[CONTRIBUTING.md](../../CONTRIBUTING.md)** για τη ρύθμιση ανάπτυξης, τις εντολές test και CI-parity, τη ροή εργασίας git, και τι κάνει μια ισχυρή συνεισφορά (τα δουλεμένα παραδείγματα και οι αναφορές σφαλμάτων εξαγωγής είναι τα πιο χρήσιμα). Αρχιτεκτονική και πώς να προσθέσετε μια γλώσσα: [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
Νέοι εδώ; Πείτε ένα γεια στο [Discord](https://discord.gg/XDnKVpzdXB) ή στα [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
Νέοι εδώ; Πείτε ένα γεια στο [Discord](https://discord.gg/graphify) ή στα [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
|
||||
---
|
||||
|
||||
@@ -486,7 +486,7 @@ viz_node_limit=0
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -464,7 +464,7 @@ Cada comando y flag, con ejemplos: **[Referencia de CLI](https://docs.graphify.c
|
||||
|
||||
Las contribuciones son bienvenidas. Consulta **[CONTRIBUTING.md](../../CONTRIBUTING.md)** para la configuración de desarrollo, los comandos de pruebas y de paridad con CI, el flujo de trabajo de git y qué hace una contribución sólida (los ejemplos trabajados y los informes de errores de extracción son los más útiles). Arquitectura y cómo añadir un lenguaje: [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
¿Nuevo por aquí? Saluda en [Discord](https://discord.gg/XDnKVpzdXB) o en [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
¿Nuevo por aquí? Saluda en [Discord](https://discord.gg/graphify) o en [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
|
||||
---
|
||||
|
||||
@@ -494,7 +494,7 @@ El README está disponible en 32 idiomas. Usa el selector de idioma en la parte
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -464,7 +464,7 @@ viz_node_limit=0
|
||||
|
||||
مشارکتها خوشآمد هستند. برای راهاندازی توسعه، فرمانهای آزمون و برابری با CI، گردشکار git، و اینکه چه چیزی یک مشارکت قوی را میسازد (مثالهای عملی و گزارشهای باگ استخراج مفیدترینها هستند) **[CONTRIBUTING.md](../../CONTRIBUTING.md)** را ببینید. معماری و چگونگی افزودن یک زبان: [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
تازهوارد هستید؟ در [Discord](https://discord.gg/XDnKVpzdXB) یا در [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) سلام کنید.
|
||||
تازهوارد هستید؟ در [Discord](https://discord.gg/graphify) یا در [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) سلام کنید.
|
||||
|
||||
---
|
||||
|
||||
@@ -494,7 +494,7 @@ viz_node_limit=0
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -464,7 +464,7 @@ Jokainen komento ja lippu, esimerkkien kera: **[CLI-viite](https://docs.graphify
|
||||
|
||||
Osallistumiset ovat tervetulleita. Katso **[CONTRIBUTING.md](../../CONTRIBUTING.md)** kehitysympäristön, testi- ja CI-pariteettikomentojen, git-työnkulun ja sen osalta, mikä tekee vahvan osallistumisen (työstetyt esimerkit ja ekstraktiovikailmoitukset ovat hyödyllisimpiä). Arkkitehtuuri ja miten lisätä kieli: [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
Uusi täällä? Sano hei [Discordissa](https://discord.gg/XDnKVpzdXB) tai [GitHub Discussionsissa](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
Uusi täällä? Sano hei [Discordissa](https://discord.gg/graphify) tai [GitHub Discussionsissa](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
|
||||
---
|
||||
|
||||
@@ -494,7 +494,7 @@ Rakennatko jotain graphify-ekosysteemissä? Sitä kannustetaan. Jos projektisi k
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -464,7 +464,7 @@ Ang [**Graphify Cloud**](https://app.graphify.com/login) ay ang laging-nakabukas
|
||||
|
||||
Malugod na tinatanggap ang mga kontribusyon. Tingnan ang **[CONTRIBUTING.md](../../CONTRIBUTING.md)** para sa development setup, ang mga utos para sa test at CI-parity, ang git workflow, at kung ano ang bumubuo ng isang matibay na kontribusyon (ang mga worked example at extraction bug report ang pinaka-kapaki-pakinabang). Arkitektura at kung paano magdagdag ng wika: [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
Bago rito? Kumusta sa [Discord](https://discord.gg/XDnKVpzdXB) o sa [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
Bago rito? Kumusta sa [Discord](https://discord.gg/graphify) o sa [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
|
||||
---
|
||||
|
||||
@@ -494,7 +494,7 @@ May ginagawa ka ba sa ekosistema ng graphify? Iyon ay hinihikayat. Kung ang proy
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -464,7 +464,7 @@ Chaque commande et chaque option, avec des exemples : **[CLI reference](https://
|
||||
|
||||
Les contributions sont les bienvenues. Voir **[CONTRIBUTING.md](../../CONTRIBUTING.md)** pour la configuration de développement, les commandes de test et de parité CI, le workflow git, et ce qui fait une contribution solide (les exemples travaillés et les rapports de bugs d'extraction sont les plus utiles). Architecture et comment ajouter un langage : [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
Nouveau ici ? Dites bonjour sur [Discord](https://discord.gg/XDnKVpzdXB) ou dans les [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
Nouveau ici ? Dites bonjour sur [Discord](https://discord.gg/graphify) ou dans les [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
|
||||
---
|
||||
|
||||
@@ -494,7 +494,7 @@ Vous construisez quelque chose dans l'écosystème graphify ? C'est encouragé.
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -456,7 +456,7 @@ viz_node_limit=0
|
||||
|
||||
תרומות מתקבלות בברכה. ראו **[CONTRIBUTING.md](../../CONTRIBUTING.md)** עבור הגדרת הפיתוח, פקודות הבדיקה ושקילות ה-CI, תהליך העבודה של git, ומה הופך תרומה לחזקה (דוגמאות מעשיות ודיווחי באגים של חילוץ הם השימושיים ביותר). ארכיטקטורה ואיך להוסיף שפה: [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
חדשים כאן? אמרו שלום ב-[Discord](https://discord.gg/XDnKVpzdXB) או ב-[GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
חדשים כאן? אמרו שלום ב-[Discord](https://discord.gg/graphify) או ב-[GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
|
||||
---
|
||||
|
||||
@@ -486,7 +486,7 @@ viz_node_limit=0
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -464,7 +464,7 @@ viz_node_limit=0
|
||||
|
||||
योगदान का स्वागत है। डेवलपमेंट सेटअप, टेस्ट और CI-समतुल्य कमांड, git वर्कफ़्लो, और क्या एक मजबूत योगदान बनाता है (worked examples और एक्सट्रैक्शन बग रिपोर्ट सबसे उपयोगी हैं) के लिए **[CONTRIBUTING.md](../../CONTRIBUTING.md)** देखें। आर्किटेक्चर और कोई भाषा कैसे जोड़ें: [ARCHITECTURE.md](../../ARCHITECTURE.md)।
|
||||
|
||||
यहां नए हैं? [Discord](https://discord.gg/XDnKVpzdXB) पर या [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) में नमस्ते कहें।
|
||||
यहां नए हैं? [Discord](https://discord.gg/graphify) पर या [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) में नमस्ते कहें।
|
||||
|
||||
---
|
||||
|
||||
@@ -494,7 +494,7 @@ graphify पारिस्थितिकी तंत्र में कु
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -464,7 +464,7 @@ A [**Graphify Cloud**](https://app.graphify.com/login) a graphify tetejére ép
|
||||
|
||||
A hozzájárulásokat szívesen fogadjuk. A fejlesztési beállításért, a teszt- és CI-paritási parancsokért, a git-munkafolyamatért és azért, hogy mi tesz egy hozzájárulást erőssé (a kidolgozott példák és a kinyerési hibajelentések a leghasznosabbak), lásd: **[CONTRIBUTING.md](../../CONTRIBUTING.md)**. Architektúra és hogyan adjunk hozzá egy nyelvet: [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
Új itt? Köszönjön be a [Discordon](https://discord.gg/XDnKVpzdXB) vagy a [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) felületen.
|
||||
Új itt? Köszönjön be a [Discordon](https://discord.gg/graphify) vagy a [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) felületen.
|
||||
|
||||
---
|
||||
|
||||
@@ -494,7 +494,7 @@ A README 32 nyelven érhető el. Használja a fájl tetején lévő nyelvváltó
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -464,7 +464,7 @@ Setiap perintah dan flag, dengan contoh: **[CLI reference](https://docs.graphify
|
||||
|
||||
Kontribusi disambut baik. Lihat **[CONTRIBUTING.md](../../CONTRIBUTING.md)** untuk penyiapan pengembangan, perintah test dan CI-parity, alur kerja git, dan apa yang membuat kontribusi kuat (worked examples dan laporan bug ekstraksi adalah yang paling berguna). Arsitektur dan cara menambahkan bahasa: [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
Baru di sini? Sapa di [Discord](https://discord.gg/XDnKVpzdXB) atau di [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
Baru di sini? Sapa di [Discord](https://discord.gg/graphify) atau di [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
|
||||
---
|
||||
|
||||
@@ -494,7 +494,7 @@ Sedang membangun sesuatu di ekosistem graphify? Itu dianjurkan. Jika proyek Anda
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -464,7 +464,7 @@ Ogni comando e flag, con esempi: **[CLI reference](https://docs.graphify.com/ref
|
||||
|
||||
I contributi sono benvenuti. Vedi **[CONTRIBUTING.md](../../CONTRIBUTING.md)** per la configurazione di sviluppo, i comandi di test e di parità con la CI, il flusso di lavoro git e cosa rende un contributo solido (gli esempi elaborati e le segnalazioni di bug di estrazione sono i più utili). Architettura e come aggiungere un linguaggio: [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
Nuovo qui? Saluta su [Discord](https://discord.gg/XDnKVpzdXB) o nelle [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
Nuovo qui? Saluta su [Discord](https://discord.gg/graphify) o nelle [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
|
||||
---
|
||||
|
||||
@@ -494,7 +494,7 @@ Stai costruendo qualcosa nell'ecosistema di graphify? È incoraggiato. Se il tuo
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -456,7 +456,7 @@ AI アシスタントに加えて、`graphify query`、`graphify path`、`graphi
|
||||
|
||||
コントリビューションを歓迎します。開発環境のセットアップ、テストと CI-parity のコマンド、git ワークフロー、そして何が優れたコントリビューションになるか(実例と抽出バグレポートが最も役立ちます)については、**[CONTRIBUTING.md](../../CONTRIBUTING.md)** を参照してください。アーキテクチャと言語の追加方法: [ARCHITECTURE.md](../../ARCHITECTURE.md)。
|
||||
|
||||
初めてですか?[Discord](https://discord.gg/XDnKVpzdXB) または [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) で挨拶してください。
|
||||
初めてですか?[Discord](https://discord.gg/graphify) または [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) で挨拶してください。
|
||||
|
||||
---
|
||||
|
||||
@@ -486,7 +486,7 @@ graphify のエコシステムで何かを作っていますか?それは歓
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -456,7 +456,7 @@ AI 어시스턴트 외에도, `graphify query`, `graphify path`, `graphify expla
|
||||
|
||||
기여를 환영합니다. 개발 환경 설정, 테스트 및 CI-parity 명령, git 워크플로, 그리고 무엇이 강력한 기여가 되는지(실제 예시와 추출 버그 리포트가 가장 유용합니다)는 **[CONTRIBUTING.md](../../CONTRIBUTING.md)** 를 참고하세요. 아키텍처와 언어 추가 방법: [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
처음이신가요? [Discord](https://discord.gg/XDnKVpzdXB) 또는 [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) 에서 인사해 주세요.
|
||||
처음이신가요? [Discord](https://discord.gg/graphify) 또는 [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) 에서 인사해 주세요.
|
||||
|
||||
---
|
||||
|
||||
@@ -486,7 +486,7 @@ graphify 생태계에서 무언가를 만들고 계신가요? 그것은 권장
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -464,7 +464,7 @@ Elk commando en elke flag, met voorbeelden: **[CLI reference](https://docs.graph
|
||||
|
||||
Bijdragen zijn welkom. Zie **[CONTRIBUTING.md](../../CONTRIBUTING.md)** voor de ontwikkelopzet, de test- en CI-pariteitscommando's, de git-workflow en wat een sterke bijdrage maakt (uitgewerkte voorbeelden en extractiebugrapporten zijn het nuttigst). Architectuur en hoe je een taal toevoegt: [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
Nieuw hier? Zeg hallo op [Discord](https://discord.gg/XDnKVpzdXB) of in [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
Nieuw hier? Zeg hallo op [Discord](https://discord.gg/graphify) of in [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
|
||||
---
|
||||
|
||||
@@ -494,7 +494,7 @@ Bouw je iets in het graphify-ecosysteem? Dat wordt aangemoedigd. Als je project
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -464,7 +464,7 @@ Hver kommando og hvert flagg, med eksempler: **[CLI-referanse](https://docs.grap
|
||||
|
||||
Bidrag er velkomne. Se **[CONTRIBUTING.md](../../CONTRIBUTING.md)** for utviklingsoppsettet, test- og CI-paritetskommandoene, git-arbeidsflyten og hva som gjør et sterkt bidrag (gjennomarbeidede eksempler og feilrapporter om ekstraksjon er mest nyttige). Arkitektur og hvordan man legger til et språk: [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
Ny her? Si hei på [Discord](https://discord.gg/XDnKVpzdXB) eller i [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
Ny her? Si hei på [Discord](https://discord.gg/graphify) eller i [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
|
||||
---
|
||||
|
||||
@@ -494,7 +494,7 @@ Bygger du noe i graphify-økosystemet? Det oppmuntres. Hvis prosjektet ditt bruk
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -464,7 +464,7 @@ Każde polecenie i flaga, z przykładami: **[CLI reference](https://docs.graphif
|
||||
|
||||
Wkład jest mile widziany. Zobacz **[CONTRIBUTING.md](../../CONTRIBUTING.md)**, aby poznać konfigurację środowiska deweloperskiego, polecenia testów i zgodności z CI, przepływ pracy w git oraz to, co składa się na mocny wkład (opracowane przykłady i zgłoszenia błędów ekstrakcji są najbardziej przydatne). Architektura i jak dodać język: [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
Jesteś tu nowy? Przywitaj się na [Discordzie](https://discord.gg/XDnKVpzdXB) lub w [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
Jesteś tu nowy? Przywitaj się na [Discordzie](https://discord.gg/graphify) lub w [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
|
||||
---
|
||||
|
||||
@@ -494,7 +494,7 @@ Budujesz coś w ekosystemie graphify? To jest zachęcane. Jeśli Twój projekt u
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -464,7 +464,7 @@ O [**Graphify Cloud**](https://app.graphify.com/login) é a camada sempre ativa
|
||||
|
||||
Contribuições são bem-vindas. Veja **[CONTRIBUTING.md](../../CONTRIBUTING.md)** para a configuração de desenvolvimento, os comandos de teste e de paridade com a CI, o fluxo de trabalho do git, e o que faz uma contribuição forte (exemplos resolvidos e relatórios de bugs de extração são os mais úteis). Arquitetura e como adicionar uma linguagem: [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
Novo por aqui? Diga oi no [Discord](https://discord.gg/XDnKVpzdXB) ou nas [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
Novo por aqui? Diga oi no [Discord](https://discord.gg/graphify) ou nas [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
|
||||
---
|
||||
|
||||
@@ -494,7 +494,7 @@ Está construindo algo no ecossistema do graphify? Isso é incentivado. Se o seu
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -464,7 +464,7 @@ Fiecare comandă și opțiune, cu exemple: **[Referința CLI](https://docs.graph
|
||||
|
||||
Contribuțiile sunt binevenite. Vedeți **[CONTRIBUTING.md](../../CONTRIBUTING.md)** pentru configurarea de dezvoltare, comenzile de test și de paritate cu CI, fluxul de lucru git și ce înseamnă o contribuție puternică (exemplele lucrate și rapoartele de erori de extracție sunt cele mai utile). Arhitectura și cum să adăugați un limbaj: [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
Nou aici? Salutați pe [Discord](https://discord.gg/XDnKVpzdXB) sau în [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
Nou aici? Salutați pe [Discord](https://discord.gg/graphify) sau în [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
|
||||
---
|
||||
|
||||
@@ -494,7 +494,7 @@ Construiți ceva în ecosistemul graphify? Asta este încurajat. Dacă proiectul
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -464,7 +464,7 @@ viz_node_limit=0
|
||||
|
||||
Вклад приветствуется. Смотрите **[CONTRIBUTING.md](../../CONTRIBUTING.md)** для настройки среды разработки, команд тестирования и паритета с CI, рабочего процесса git и того, что делает вклад сильным (проработанные примеры и отчёты об ошибках извлечения наиболее полезны). Архитектура и как добавить язык: [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
Впервые здесь? Поздоровайтесь в [Discord](https://discord.gg/XDnKVpzdXB) или в [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
Впервые здесь? Поздоровайтесь в [Discord](https://discord.gg/graphify) или в [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
|
||||
---
|
||||
|
||||
@@ -494,7 +494,7 @@ README доступен на 32 языках. Используйте перек
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -464,7 +464,7 @@ Alla kommandon och flaggor, med exempel: **[CLI-referens](https://docs.graphify.
|
||||
|
||||
Bidrag är välkomna. Se **[CONTRIBUTING.md](../../CONTRIBUTING.md)** för utvecklingsmiljön, kommandona för test och CI-paritet, git-arbetsflödet och vad som gör ett starkt bidrag (utarbetade exempel och felrapporter om extraktion är mest användbara). Arkitektur och hur man lägger till ett språk: [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
Ny här? Säg hej på [Discord](https://discord.gg/XDnKVpzdXB) eller i [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
Ny här? Säg hej på [Discord](https://discord.gg/graphify) eller i [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
|
||||
---
|
||||
|
||||
@@ -494,7 +494,7 @@ Bygger du något i graphify-ekosystemet? Det uppmuntras. Om ditt projekt använd
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -456,7 +456,7 @@ viz_node_limit=0
|
||||
|
||||
ยินดีรับการมีส่วนร่วม ดู **[CONTRIBUTING.md](../../CONTRIBUTING.md)** สำหรับการตั้งค่าสภาพแวดล้อมการพัฒนา, คำสั่งทดสอบและ CI-parity, เวิร์กโฟลว์ git และอะไรที่ทำให้การมีส่วนร่วมแข็งแกร่ง (ตัวอย่างจริงและรายงานบั๊กการสกัดมีประโยชน์ที่สุด) สถาปัตยกรรมและวิธีเพิ่มภาษา: [ARCHITECTURE.md](../../ARCHITECTURE.md)
|
||||
|
||||
เพิ่งมาที่นี่? ทักทายบน [Discord](https://discord.gg/XDnKVpzdXB) หรือใน [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions)
|
||||
เพิ่งมาที่นี่? ทักทายบน [Discord](https://discord.gg/graphify) หรือใน [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions)
|
||||
|
||||
---
|
||||
|
||||
@@ -486,7 +486,7 @@ README นี้มีให้ใน 32 ภาษา ใช้ตัวสล
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -464,7 +464,7 @@ Yaygın kurulum ve çıkarım sorunları ve bunların çözümleri: **[Sorun gid
|
||||
|
||||
Katkılar memnuniyetle karşılanır. Geliştirme kurulumu, test ve CI eşitlik komutları, git iş akışı ve güçlü bir katkıyı neyin oluşturduğu (işlenmiş örnekler ve çıkarım hata raporları en yararlı olanlardır) için **[CONTRIBUTING.md](../../CONTRIBUTING.md)** dosyasına bakın. Mimari ve bir dilin nasıl ekleneceği: [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
Buraya yeni mi geldiniz? [Discord](https://discord.gg/XDnKVpzdXB) üzerinde veya [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) içinde selam verin.
|
||||
Buraya yeni mi geldiniz? [Discord](https://discord.gg/graphify) üzerinde veya [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) içinde selam verin.
|
||||
|
||||
---
|
||||
|
||||
@@ -494,7 +494,7 @@ graphify ekosisteminde bir şeyler mi inşa ediyorsunuz? Buna teşvik ediliyor.
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -464,7 +464,7 @@ viz_node_limit=0
|
||||
|
||||
Внески вітаються. Дивіться **[CONTRIBUTING.md](../../CONTRIBUTING.md)** для налаштування розробки, команд тестування та відповідності CI, git-процесу та того, що робить внесок сильним (опрацьовані приклади та звіти про баги вилучення найкорисніші). Архітектура та як додати мову: [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
Новачок тут? Привітайтеся в [Discord](https://discord.gg/XDnKVpzdXB) або в [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
Новачок тут? Привітайтеся в [Discord](https://discord.gg/graphify) або в [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
|
||||
---
|
||||
|
||||
@@ -494,7 +494,7 @@ README доступний 32 мовами. Використовуйте пере
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -464,7 +464,7 @@ Har bir buyruq va bayroq, misollar bilan: **[CLI ma'lumotnomasi](https://docs.gr
|
||||
|
||||
Hissalar olqishlanadi. Ishlab chiqish sozlash, test va CI-parity buyruqlari, git ish oqimi va kuchli hissani nima tashkil qilishi (ishlab chiqilgan misollar va ekstraktsiya xato hisobotlari eng foydali) uchun **[CONTRIBUTING.md](../../CONTRIBUTING.md)** ga qarang. Arxitektura va til qanday qo'shiladi: [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
Bu yerda yangimisiz? [Discord](https://discord.gg/XDnKVpzdXB) da yoki [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) da salom ayting.
|
||||
Bu yerda yangimisiz? [Discord](https://discord.gg/graphify) da yoki [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) da salom ayting.
|
||||
|
||||
---
|
||||
|
||||
@@ -494,7 +494,7 @@ graphify ekotizimida biror narsa quryapsizmi? Bu rag'batlantiriladi. Agar loyiha
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -456,7 +456,7 @@ Mọi lệnh và cờ, kèm ví dụ: **[CLI reference](https://docs.graphify.co
|
||||
|
||||
Hoan nghênh đóng góp. Xem **[CONTRIBUTING.md](../../CONTRIBUTING.md)** để biết thiết lập môi trường phát triển, các lệnh kiểm thử và CI-parity, quy trình git, và điều gì làm nên một đóng góp mạnh (các ví dụ thực tế và báo cáo lỗi trích xuất là hữu ích nhất). Kiến trúc và cách thêm một ngôn ngữ: [ARCHITECTURE.md](../../ARCHITECTURE.md).
|
||||
|
||||
Mới đến? Chào một tiếng trên [Discord](https://discord.gg/XDnKVpzdXB) hoặc trong [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
Mới đến? Chào một tiếng trên [Discord](https://discord.gg/graphify) hoặc trong [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
|
||||
|
||||
---
|
||||
|
||||
@@ -486,7 +486,7 @@ README có sẵn trong 32 ngôn ngữ. Dùng trình chuyển ngôn ngữ ở đ
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -456,7 +456,7 @@ viz_node_limit=0
|
||||
|
||||
欢迎贡献。请见 **[CONTRIBUTING.md](../../CONTRIBUTING.md)** 以了解开发环境设置、测试与 CI-parity 命令、git 工作流,以及什么构成一次出色的贡献(可运行的示例与提取错误报告是最有用的)。架构与如何新增一种语言:[ARCHITECTURE.md](../../ARCHITECTURE.md)。
|
||||
|
||||
刚来吗?在 [Discord](https://discord.gg/XDnKVpzdXB) 或 [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) 打声招呼。
|
||||
刚来吗?在 [Discord](https://discord.gg/graphify) 或 [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) 打声招呼。
|
||||
|
||||
---
|
||||
|
||||
@@ -486,7 +486,7 @@ Made with [contrib.rocks](https://contrib.rocks).
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
|
||||
<a href="https://app.graphify.com/login"><img src="https://img.shields.io/badge/Graphify%20Cloud-app.graphify.com-118d4f?style=flat&logoColor=white" alt="Graphify Cloud"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://www.ycombinator.com/companies/graphify-labs"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
@@ -456,7 +456,7 @@ viz_node_limit=0
|
||||
|
||||
歡迎貢獻。見 **[CONTRIBUTING.md](../../CONTRIBUTING.md)** 了解開發環境建置、測試與 CI 對齊的命令、git 工作流程,以及什麼樣的貢獻才算扎實(可執行的範例和提取 bug 報告最有用)。架構和如何新增一門語言:[ARCHITECTURE.md](../../ARCHITECTURE.md)。
|
||||
|
||||
新來的?在 [Discord](https://discord.gg/XDnKVpzdXB) 或 [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) 打個招呼。
|
||||
新來的?在 [Discord](https://discord.gg/graphify) 或 [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions) 打個招呼。
|
||||
|
||||
---
|
||||
|
||||
@@ -486,7 +486,7 @@ Made with [contrib.rocks](https://contrib.rocks).
|
||||
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
|
||||
<a href="https://discord.gg/XDnKVpzdXB"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://discord.gg/graphify"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
|
||||
+30
-9
@@ -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,
|
||||
)
|
||||
|
||||
@@ -861,7 +871,11 @@ def _run_cli() -> None:
|
||||
print("Usage: graphify <command>")
|
||||
print()
|
||||
print("Commands:")
|
||||
print(" install [--platform P] copy skill to platform config dir (claude|windows|codebuddy|codex|opencode|aider|amp|agents|claw|droid|trae|trae-cn|gemini|cursor|antigravity|hermes|kiro|pi|devin)")
|
||||
# Derive the list from the same source as `graphify install` usage
|
||||
# (_print_install_usage) so the two can never drift apart, rather than
|
||||
# hand-maintaining it (amp, copilot, antigravity-windows had been missed, #4655).
|
||||
_platform_values = "|".join([*_PLATFORM_CONFIG, "gemini", "cursor"])
|
||||
print(f" install [--platform P] copy skill to platform config dir ({_platform_values})")
|
||||
print(" uninstall remove graphify from all detected platforms in one shot")
|
||||
print(" --purge also delete graphify-out/ directory")
|
||||
print(" path \"A\" \"B\" shortest path between two nodes in graph.json")
|
||||
@@ -905,13 +919,13 @@ def _run_cli() -> None:
|
||||
print(" --graph <path> path to graph.json (default <path>/graphify-out/graph.json)")
|
||||
print(" --no-label keep 'Community N' placeholders (skip LLM community naming)")
|
||||
print(" --backend=<name> backend to use for community naming (default: auto-detect)")
|
||||
print(" --model=<name> model to use for community naming")
|
||||
print(" --model=<name> model to use for community naming (claude-cli also reads GRAPHIFY_CLAUDE_CLI_MODEL)")
|
||||
print(" --max-concurrency=N parallel community-labeling LLM calls (default 4; forced to 1 for ollama/claude-cli)")
|
||||
print(" --batch-size=N communities per labeling LLM call (default 100)")
|
||||
print(" --batch-size=N communities per labeling LLM call (default 100, sized for ~16k context; use 40 for 8k)")
|
||||
print(" label <path> (re)name communities with the configured LLM backend, regenerate report")
|
||||
print(" --missing-only keep existing labels and only name missing/placeholder communities")
|
||||
print(" --backend=<name> backend to use (default: auto-detect from API keys)")
|
||||
print(" --model=<name> model to use for community naming")
|
||||
print(" --model=<name> model to use for community naming (claude-cli also reads GRAPHIFY_CLAUDE_CLI_MODEL)")
|
||||
print(" --max-concurrency=N parallel labeling LLM calls (default 4; forced to 1 for ollama/claude-cli)")
|
||||
print(" --batch-size=N communities per labeling LLM call (default 100)")
|
||||
print(" query \"<question>\" BFS traversal of graph.json for a question")
|
||||
@@ -919,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")
|
||||
@@ -965,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")
|
||||
@@ -991,7 +1010,7 @@ def _run_cli() -> None:
|
||||
print(" global list list repos in the global graph")
|
||||
print(" global path print path to the global graph file")
|
||||
print(" benchmark [graph.json] measure token reduction vs naive full-corpus approach")
|
||||
print(" export html emit interactive graph.html [--graph PATH] [--labels PATH] [--node-limit N] [--no-viz]")
|
||||
print(" export html emit interactive graph.html [--graph PATH] [--labels PATH] [--node-limit N, default 5000] [--no-viz]")
|
||||
print(" export callflow-html emit Mermaid-based architecture/call-flow HTML")
|
||||
print(" [GRAPH|DIR] [--graph PATH] [--labels PATH] [--report PATH] [--sections PATH] [--output HTML]")
|
||||
print(" [--lang auto|zh-CN|en] [--max-sections N] [--diagram-scale N]")
|
||||
@@ -1032,6 +1051,8 @@ def _run_cli() -> None:
|
||||
)
|
||||
print(" aider install write graphify section to AGENTS.md (Aider)")
|
||||
print(" aider uninstall remove graphify section from AGENTS.md")
|
||||
print(" amp install copy graphify skill + write AGENTS.md section (Amp)")
|
||||
print(" amp uninstall remove graphify skill + AGENTS.md section (Amp)")
|
||||
print(
|
||||
" copilot install copy graphify skill to ~/.copilot/skills (GitHub Copilot CLI)"
|
||||
)
|
||||
|
||||
+103
-19
@@ -129,6 +129,29 @@ def _prefer_file_node(
|
||||
if len(exact_file_nodes) == 1:
|
||||
return exact_file_nodes[0]
|
||||
|
||||
# #2032 relabels colliding basenames to their shortest unique path suffix
|
||||
# ("alpha/hooks.py"), so neither pass above nor the one below matches a file
|
||||
# node whose basename is shared. The label is still a path form of the
|
||||
# node's OWN source_file, which is what _is_file_node_label encodes (the
|
||||
# predicate build/analyze already treat as "this node names its file").
|
||||
# Checked before the L1 fallback because a module docstring (a `rationale`
|
||||
# node located on the docstring's line) or a one-line top-level definition
|
||||
# can also sit on L1, leaving that fallback with more than one candidate
|
||||
# (#4698).
|
||||
from graphify.build import _is_file_node_label
|
||||
|
||||
path_file_nodes = [
|
||||
node_id
|
||||
for node_id in node_ids
|
||||
if str(graph.nodes[node_id].get("source_location", "")) == "L1"
|
||||
and _is_file_node_label(
|
||||
str(graph.nodes[node_id].get("label", "")),
|
||||
str(graph.nodes[node_id].get("source_file", "")),
|
||||
)
|
||||
]
|
||||
if len(path_file_nodes) == 1:
|
||||
return path_file_nodes[0]
|
||||
|
||||
l1_nodes = [
|
||||
node_id
|
||||
for node_id in node_ids
|
||||
@@ -148,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
|
||||
@@ -155,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)
|
||||
@@ -260,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
|
||||
@@ -330,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,
|
||||
@@ -337,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}"
|
||||
|
||||
@@ -372,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}. "
|
||||
@@ -387,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")
|
||||
+40
-19
@@ -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
|
||||
@@ -82,9 +82,13 @@ def _is_file_node(G: nx.Graph, node_id: str) -> bool:
|
||||
from graphify.build import _is_file_node_label
|
||||
if _is_file_node_label(label, source_file):
|
||||
return True
|
||||
# Method stub: AST extractor labels methods as '.method_name()'
|
||||
# Method stub: AST extractor labels methods as '.method_name()'; C# methods
|
||||
# carry their owner for display ('Owner.method_name()', #4883).
|
||||
if label.startswith(".") and label.endswith("()"):
|
||||
return True
|
||||
from graphify.extractors.csharp import bare_csharp_method_label
|
||||
if bare_csharp_method_label(label, source_file) is not None:
|
||||
return True
|
||||
# Module-level function stub: labeled 'function_name()' - only has a contains edge
|
||||
# These are real functions but structurally isolated by definition; not a gap worth flagging
|
||||
if label.endswith("()") and G.degree(node_id) <= 1:
|
||||
@@ -406,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
|
||||
@@ -575,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
|
||||
@@ -757,12 +773,14 @@ def find_import_cycles(
|
||||
|
||||
# Deferred `import(...)` edges are real dependencies but do not form a
|
||||
# hard file-level cycle, so they are excluded from cycle detection (#1241).
|
||||
if data.get("deferred"):
|
||||
continue
|
||||
# Type-only imports/re-exports (`import type` / `export type ... from`)
|
||||
# are erased at compile time - a cycle that closes through one cannot
|
||||
# exist at runtime (#3123). The edge itself stays in the graph.
|
||||
if data.get("type_only"):
|
||||
forward = not data.get("deferred") and not data.get("type_only")
|
||||
# An undirected build keeps one edge per file pair, so the other file's
|
||||
# runtime import back is only a stamp on this edge (#4839).
|
||||
reverse = bool(data.get("reverse_import"))
|
||||
if not forward and not reverse:
|
||||
continue
|
||||
|
||||
src_file_attr = data.get("source_file", "")
|
||||
@@ -787,7 +805,10 @@ def find_import_cycles(
|
||||
if not tgt_file:
|
||||
continue
|
||||
|
||||
file_graph.add_edge(src_file_attr, tgt_file)
|
||||
if forward:
|
||||
file_graph.add_edge(src_file_attr, tgt_file)
|
||||
if reverse:
|
||||
file_graph.add_edge(tgt_file, src_file_attr)
|
||||
|
||||
if not file_graph.edges():
|
||||
return []
|
||||
|
||||
+603
-64
@@ -70,6 +70,8 @@ def _lost_saved_semantic_nodes(
|
||||
saved_nodes: list,
|
||||
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.
|
||||
|
||||
@@ -80,6 +82,15 @@ def _lost_saved_semantic_nodes(
|
||||
An auto-minted import stub (``external`` true, or ``type`` ``external``) is
|
||||
rebuilt from the import edges of this run. Dropping one is not a lost
|
||||
rationale or document node.
|
||||
|
||||
``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
|
||||
@@ -89,8 +100,10 @@ def _lost_saved_semantic_nodes(
|
||||
new_ids = {node.get("id") for node in new_nodes if isinstance(node, dict)}
|
||||
# A semantic ghost deduplicated into its AST twin (#1145) loses its id but
|
||||
# the symbol survives at the same (source_file, label).
|
||||
new_ast_loc_nodes: set[tuple[str, str]] = set()
|
||||
new_ast_loc_nodes: dict[tuple[str, str], str] = {}
|
||||
ast_loc_collisions: set[tuple[str, str]] = set()
|
||||
# AST file nodes, for the label-only fold of build_from_json Pass 2b (#3344).
|
||||
new_ast_file_nodes: list[tuple[str, str]] = []
|
||||
for node in new_nodes:
|
||||
# Match build_from_json's strict canonical-AST check (#2334).
|
||||
if not isinstance(node, dict) or node.get("_origin") != "ast":
|
||||
@@ -101,13 +114,15 @@ def _lost_saved_semantic_nodes(
|
||||
lbl = str(node.get("label", "")).strip()
|
||||
if not lbl:
|
||||
continue
|
||||
if _is_file_node_label(lbl, sf):
|
||||
new_ast_file_nodes.append((str(node.get("id")), sf))
|
||||
norm_sf = _norm_source_file(sf)
|
||||
if not norm_sf:
|
||||
continue
|
||||
key = (norm_sf, lbl)
|
||||
if key in new_ast_loc_nodes:
|
||||
ast_loc_collisions.add(key)
|
||||
new_ast_loc_nodes.add(key)
|
||||
new_ast_loc_nodes[key] = str(node.get("id"))
|
||||
# cluster-only and build_from_json rewrite a legacy semantic id to its
|
||||
# canonical stem, then fold a bare doc id into its `_doc` twin. That id
|
||||
# is the same node. A missing rationale id has no such successor.
|
||||
@@ -136,19 +151,84 @@ 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
|
||||
# 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]
|
||||
continue
|
||||
if source and source in deleted:
|
||||
continue
|
||||
lost.append(node)
|
||||
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
|
||||
@@ -170,6 +250,66 @@ _GENERIC_RELATIONS: frozenset[str] = frozenset({"references", "uses", "mentions"
|
||||
# `calls` is not ranked here.
|
||||
_STRUCTURAL_MEMBER_RELATIONS: frozenset[str] = frozenset({"method", "contains"})
|
||||
_CONFIDENCE_RANK: dict[str, int] = {"EXTRACTED": 3, "INFERRED": 2, "AMBIGUOUS": 1}
|
||||
# The fields that say how sure the graph is of an edge and where that came from.
|
||||
# A same-relation collision keeps one edge; the loser's copy of these fields is
|
||||
# folded into the winner's `also_seen` list instead of being discarded (#4881).
|
||||
_EVIDENCE_KEYS: tuple[str, ...] = ("confidence", "confidence_score", "source_file", "source_location")
|
||||
|
||||
|
||||
def _evidence(attrs: dict) -> dict:
|
||||
"""The provenance fields of one edge (or ``also_seen`` entry), scalars only."""
|
||||
out: dict = {}
|
||||
for key in _EVIDENCE_KEYS:
|
||||
val = attrs.get(key)
|
||||
if isinstance(val, bool) or val is None or val == "":
|
||||
continue
|
||||
if key == "confidence_score":
|
||||
try:
|
||||
val = float(val)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if not math.isfinite(val):
|
||||
continue
|
||||
elif not isinstance(val, (str, int, float)):
|
||||
continue
|
||||
out[key] = val
|
||||
return out
|
||||
|
||||
|
||||
def _evidence_sort_key(ev: dict) -> tuple:
|
||||
# Weakest first: lowest confidence tier, then lowest score.
|
||||
score = ev.get("confidence_score")
|
||||
return (
|
||||
_CONFIDENCE_RANK.get(str(ev.get("confidence", "")), 0),
|
||||
score is None,
|
||||
score if score is not None else 0.0,
|
||||
str(ev.get("source_file", "")),
|
||||
str(ev.get("source_location", "")),
|
||||
)
|
||||
|
||||
|
||||
def edge_evidence(d: dict) -> list[dict]:
|
||||
"""Every provenance record an edge carries: its own, then each ``also_seen``."""
|
||||
also = d.get("also_seen")
|
||||
return [d, *(a for a in also if isinstance(a, dict))] if isinstance(also, list) else [d]
|
||||
|
||||
|
||||
def _fold_also_seen(winner: dict, loser: dict) -> None:
|
||||
"""Record ``loser``'s provenance on ``winner`` when the two collapse (#4881).
|
||||
|
||||
Entries that repeat the winner's own provenance, or each other, are dropped,
|
||||
so re-feeding a written graph.json through the build is idempotent.
|
||||
"""
|
||||
own = _evidence(winner)
|
||||
kept: list[dict] = []
|
||||
for raw in (*edge_evidence(winner)[1:], loser, *edge_evidence(loser)[1:]):
|
||||
ev = _evidence(raw)
|
||||
if ev and not ev.items() <= own.items() and ev not in kept:
|
||||
kept.append(ev)
|
||||
if kept:
|
||||
winner["also_seen"] = sorted(kept, key=_evidence_sort_key)
|
||||
else:
|
||||
winner.pop("also_seen", None)
|
||||
|
||||
# Import-family relations whose target may legitimately be a module OUTSIDE the
|
||||
# graph (stdlib, a third-party dependency, another repo). Historically the edge
|
||||
@@ -278,21 +418,90 @@ def finalize_raw_graph_endpoints(data: dict) -> None:
|
||||
A stub is derived from the import edges that point at it, so a stub carried
|
||||
over from an earlier graph that no edge references any more is dropped too;
|
||||
a fresh build of the same tree would not have it.
|
||||
|
||||
Re-pointing an endpoint also needs the alias index, not just
|
||||
normalization: a framework-style ``#import <Kit/ToolEvent.h>`` resolves to
|
||||
a real header whose file node is ``kit_event_toolevent``, but the edge the
|
||||
extractor emitted names the header by its bare basename (``toolevent``).
|
||||
Normalization alone cannot bridge those two ids, so the raw path used to
|
||||
mint an external stub for the import and leave the edge on it while the
|
||||
clustered path re-pointed it at the real file (#4670). Resolving against the
|
||||
shared alias index makes both write paths agree, and only a genuinely
|
||||
external import (e.g. ``<Foundation/Foundation.h>``) is left to mint a stub.
|
||||
"""
|
||||
mint_external_stubs_in_data(data)
|
||||
nodes = data.get("nodes")
|
||||
key = "links" if isinstance(data.get("links"), list) else "edges"
|
||||
links = data.get(key)
|
||||
if not isinstance(nodes, list) or not isinstance(links, list):
|
||||
return
|
||||
# Match build_from_json's pre-validation alias folding before applying the
|
||||
# raw-path persistence rules. An edge that still has no relation afterwards
|
||||
# has no trustworthy semantic default and must not reach graph.json (#4809).
|
||||
for edge in links:
|
||||
if isinstance(edge, dict):
|
||||
_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.
|
||||
#
|
||||
# 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)
|
||||
)
|
||||
|
||||
# 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
|
||||
# unresolved spelling. build_from_json resolves first and mints only for
|
||||
# what is still missing; minting first is what left the raw path's import
|
||||
# edges on a stub for a file that was in the corpus all along (#4670).
|
||||
for e in links:
|
||||
if not isinstance(e, dict):
|
||||
continue
|
||||
for primary, alias in (("source", "from"), ("target", "to")):
|
||||
field = primary if primary in e else alias
|
||||
endpoint = e.get(field)
|
||||
if isinstance(endpoint, str) and endpoint in declared:
|
||||
continue
|
||||
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
|
||||
|
||||
# Whatever still names an undeclared node is genuinely external: mint the
|
||||
# typed stub for it so the on-disk graph.json has no undeclared endpoint
|
||||
# (#2873), then drop the edges that still cannot attach to two declared
|
||||
# nodes.
|
||||
mint_external_stubs_in_data(data)
|
||||
declared = {n.get("id") for n in nodes if isinstance(n, dict)}
|
||||
kept: list = []
|
||||
referenced: set = set()
|
||||
dropped_schema_edges = 0
|
||||
for e in links:
|
||||
if not isinstance(e, dict):
|
||||
kept.append(e)
|
||||
continue
|
||||
if "relation" not in e:
|
||||
dropped_schema_edges += 1
|
||||
continue
|
||||
attached = True
|
||||
for primary, alias in (("source", "from"), ("target", "to")):
|
||||
field = primary if primary in e else alias
|
||||
@@ -309,6 +518,12 @@ def finalize_raw_graph_endpoints(data: dict) -> None:
|
||||
referenced.add(e.get("source", e.get("from")))
|
||||
referenced.add(e.get("target", e.get("to")))
|
||||
links[:] = kept
|
||||
if dropped_schema_edges:
|
||||
print(
|
||||
f"[graphify] WARNING: dropped {dropped_schema_edges} schema-invalid edge(s) "
|
||||
"missing required field 'relation'.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
for hyperedge in data.get("hyperedges", []) or []:
|
||||
if isinstance(hyperedge, dict):
|
||||
members = hyperedge.get("nodes", hyperedge.get("members", hyperedge.get("node_ids", [])))
|
||||
@@ -468,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)
|
||||
@@ -508,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.
|
||||
@@ -528,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"
|
||||
|
||||
@@ -607,9 +828,13 @@ def _coerce_non_string_ids(extraction: dict) -> None:
|
||||
for he in extraction.get("hyperedges") or ():
|
||||
if not isinstance(he, dict):
|
||||
continue
|
||||
members = he.get("nodes")
|
||||
if isinstance(members, list):
|
||||
he["nodes"] = [_coerce_id(ref) for ref in members]
|
||||
# The `members`/`node_ids` aliases (#1561) are coerced too, for the
|
||||
# same reason as `from`/`to` above: they are folded onto `nodes` only
|
||||
# later, by which time the node ids they name have already become str.
|
||||
for key in ("nodes", *_HE_MEMBER_ALIASES):
|
||||
members = he.get(key)
|
||||
if isinstance(members, list):
|
||||
he[key] = [_coerce_id(ref) for ref in members]
|
||||
|
||||
|
||||
def _norm_source_file(p: str | None, root: str | None = None) -> str | None:
|
||||
@@ -676,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`;
|
||||
@@ -735,6 +979,39 @@ def disambiguate_file_labels_in_nodes(nodes: "list") -> None:
|
||||
nodes[i]["label"] = new_label
|
||||
|
||||
|
||||
def _qualify_csharp_method_labels(G: "nx.Graph") -> None:
|
||||
"""Give C# method nodes an ``Owner.Name()`` display label (#4883). Ids and
|
||||
edges are never changed, and an undirected graph's owner side is read from
|
||||
the edge's recorded ``_src``/``_tgt``. Idempotent."""
|
||||
from graphify.extractors.csharp import csharp_method_label_reassignments
|
||||
method_edges = [
|
||||
(data.get("_src", u), data.get("_tgt", v))
|
||||
for u, v, data in G.edges(data=True)
|
||||
if data.get("relation") == "method"
|
||||
]
|
||||
for nid, new_label in csharp_method_label_reassignments(
|
||||
G.nodes(data=True), method_edges
|
||||
).items():
|
||||
G.nodes[nid]["label"] = new_label
|
||||
|
||||
|
||||
def qualify_csharp_method_labels_in_nodes(nodes: "list", edges: "list") -> None:
|
||||
"""Raw node/edge-list form of :func:`_qualify_csharp_method_labels`, in
|
||||
place, for the --no-cluster writers that bypass build_from_json (#4883)."""
|
||||
from graphify.extractors.csharp import csharp_method_label_reassignments
|
||||
method_edges = [
|
||||
(e.get("source"), e.get("target"))
|
||||
for e in edges
|
||||
if isinstance(e, dict) and e.get("relation") == "method"
|
||||
]
|
||||
reassigned = csharp_method_label_reassignments(
|
||||
((n.get("id"), n) for n in nodes if isinstance(n, dict)), method_edges
|
||||
)
|
||||
for n in nodes:
|
||||
if isinstance(n, dict) and n.get("id") in reassigned:
|
||||
n["label"] = reassigned[n["id"]]
|
||||
|
||||
|
||||
def _infer_merge_root(graph_path: Path) -> str | None:
|
||||
"""Best-effort scan root for relativizing paths in build_merge when the caller
|
||||
passes no ``root`` (#1571).
|
||||
@@ -966,6 +1243,106 @@ def _old_file_stems(rel: Path) -> list[str]:
|
||||
return [f for f in forms if f and not (f in seen or seen.add(f))]
|
||||
|
||||
|
||||
def _alias_index(nodes: "Iterable[tuple[str, dict]]") -> dict[str, str]:
|
||||
"""Map every OLD-stem spelling of a node to that node's canonical id.
|
||||
|
||||
The pre-migration id recipe keyed a file's node on its stem, so a file at
|
||||
``Kit/Event/ToolEvent.h`` used to be ``toolevent`` and is now
|
||||
``kit_event_toolevent`` (#1504/#1509). An edge endpoint still written in the
|
||||
old spelling must resolve to the migrated node instead of dangling, so each
|
||||
node registers its old-stem forms as aliases.
|
||||
|
||||
An alias is committed only when EXACTLY ONE node claims it. The old-stem
|
||||
form drops the extension and every directory but the immediate parent, so
|
||||
"ping.h" and "ping.php" in different directories both alias to bare "ping";
|
||||
committing an ambiguous alias would bind an edge to whichever same-stem file
|
||||
happened to be seen first, merging unrelated files.
|
||||
|
||||
A Python module whose bare stem is a stdlib name (e.g. ``scripts/logging.py``)
|
||||
must not claim the collapsed bare-stem alias ("logging"): that alias would
|
||||
capture a genuine external ``import logging`` edge and bind it to this
|
||||
same-named local file (#4261). The directory-scoped alias form
|
||||
("scripts_logging") is still registered, so a real stale-id reference to this
|
||||
file keeps healing.
|
||||
|
||||
Both the normalized and the raw spelling of every alias are registered, so
|
||||
a caller can look an endpoint up with or without normalization.
|
||||
|
||||
Shared by :func:`build_from_json` and :func:`finalize_raw_graph_endpoints`
|
||||
so the clustered and the raw (``--no-cluster``) write paths resolve an
|
||||
endpoint the same way (#4670).
|
||||
"""
|
||||
from graphify.extractors.base import _file_stem as _fs
|
||||
from graphify.extractors.csharp import bare_csharp_method_label
|
||||
from graphify.extractors.resolution import _PYTHON_STDLIB_MODULE_NAMES
|
||||
|
||||
alias_candidates: dict[str, set[str]] = {}
|
||||
for nid, attrs in nodes:
|
||||
if not isinstance(nid, str) or not isinstance(attrs, dict):
|
||||
continue
|
||||
sf = attrs.get("source_file")
|
||||
if not sf:
|
||||
continue
|
||||
rel = Path(str(sf))
|
||||
if _is_abs(str(sf)):
|
||||
continue
|
||||
new_stem = make_id(_fs(rel))
|
||||
if not new_stem:
|
||||
continue
|
||||
is_py_stdlib_stem = (
|
||||
rel.suffix.lower() in (".py", ".pyi")
|
||||
and make_id(rel.stem) in _PYTHON_STDLIB_MODULE_NAMES
|
||||
)
|
||||
if str(attrs.get("label", "")) == rel.name:
|
||||
suffix = "" # this node IS the file, whatever its (possibly salted) id
|
||||
else:
|
||||
suffix = ""
|
||||
if _normalize_id(nid).startswith(new_stem):
|
||||
suffix = _normalize_id(nid)[len(new_stem):] # leading "_entity" or ""
|
||||
for old_stem in _old_file_stems(rel):
|
||||
if old_stem == new_stem:
|
||||
continue
|
||||
if is_py_stdlib_stem and old_stem in _PYTHON_STDLIB_MODULE_NAMES:
|
||||
continue
|
||||
alias = old_stem + suffix
|
||||
alias_candidates.setdefault(_normalize_id(alias), set()).add(nid)
|
||||
alias_candidates.setdefault(alias, set()).add(nid)
|
||||
m_label = str(attrs.get("label", ""))
|
||||
m_label = bare_csharp_method_label(m_label.strip(), sf) or m_label
|
||||
if attrs.get("_origin") == "ast" and m_label.startswith("."):
|
||||
m_name = make_id(m_label.strip().removeprefix(".").removesuffix("()"))
|
||||
m_alias = f"{new_stem}_{m_name}"
|
||||
if _normalize_id(nid) != _normalize_id(m_alias):
|
||||
alias_candidates.setdefault(_normalize_id(m_alias), set()).add(nid)
|
||||
alias_candidates.setdefault(m_alias, set()).add(nid)
|
||||
return {
|
||||
alias_key: next(iter(candidates))
|
||||
for alias_key, candidates in alias_candidates.items()
|
||||
if len(candidates) == 1
|
||||
}
|
||||
|
||||
|
||||
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
|
||||
@@ -1063,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.
|
||||
@@ -1075,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):
|
||||
@@ -1097,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))
|
||||
@@ -1212,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
|
||||
@@ -1359,6 +1777,7 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
|
||||
_noloc_nodes: dict[tuple[str, str], str] = {} # (source_file, label) -> ghost node id
|
||||
_ast_file_nodes: list[tuple[str, str]] = [] # (node_id, source_file) for AST file-self nodes (#3344)
|
||||
_ast_method_nodes: dict[tuple[str, str], list[str]] = {} # (source_file, norm_method) -> [ast_nid, ...]
|
||||
from graphify.extractors.csharp import bare_csharp_method_label
|
||||
|
||||
# Pass 1: collect canonical nodes — AST-origin nodes take precedence over LLM nodes.
|
||||
# When 2+ AST nodes share a key (same-named symbols in same-named files across
|
||||
@@ -1420,8 +1839,9 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
|
||||
# a dotfile label like `.env` is never mistaken for a method
|
||||
# (#3705 follow-up). Key on the normalized name for parity with
|
||||
# the alias index below and the rest of the dedup passes.
|
||||
if label.startswith(".") and label.endswith("()"):
|
||||
m_name = make_id(label.removeprefix(".").removesuffix("()"))
|
||||
m_label = bare_csharp_method_label(label, sf) or label
|
||||
if m_label.startswith(".") and m_label.endswith("()"):
|
||||
m_name = make_id(m_label.removeprefix(".").removesuffix("()"))
|
||||
_ast_method_nodes.setdefault((sf, m_name), []).append(nid)
|
||||
else:
|
||||
# First non-AST node for this (file, label) wins as canonical; a
|
||||
@@ -1445,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
|
||||
@@ -1488,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.
|
||||
@@ -1533,55 +1967,35 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
|
||||
# unrelated same-named PHP script) is still caught as ambiguous instead of
|
||||
# the header silently dropping out of the race and leaving the PHP file as
|
||||
# the lone (wrong) "unambiguous" winner.
|
||||
from graphify.extractors.base import _file_stem as _fs
|
||||
from graphify.extractors.resolution import _PYTHON_STDLIB_MODULE_NAMES
|
||||
_alias_candidates: dict[str, set[str]] = {}
|
||||
for nid in node_set:
|
||||
attrs = G.nodes[nid]
|
||||
sf = attrs.get("source_file")
|
||||
if not sf:
|
||||
continue
|
||||
rel = Path(str(sf))
|
||||
if _is_abs(str(sf)):
|
||||
continue
|
||||
new_stem = make_id(_fs(rel))
|
||||
# A Python module whose bare stem is a stdlib name (e.g. `scripts/logging.py`)
|
||||
# must not claim the collapsed bare-stem alias ("logging"): that alias would
|
||||
# capture a genuine external `import logging` / `logging.getLogger()` edge
|
||||
# and bind it to this same-named local file (#4261). The directory-scoped
|
||||
# alias form ("scripts_logging") is still registered, so a real stale-id
|
||||
# reference to this file keeps healing.
|
||||
is_py_stdlib_stem = (
|
||||
rel.suffix.lower() in (".py", ".pyi")
|
||||
and make_id(rel.stem) in _PYTHON_STDLIB_MODULE_NAMES
|
||||
)
|
||||
if str(attrs.get("label", "")) == rel.name:
|
||||
suffix = "" # this node IS the file, whatever its (possibly salted) id
|
||||
else:
|
||||
suffix = ""
|
||||
if _normalize_id(nid).startswith(new_stem):
|
||||
suffix = _normalize_id(nid)[len(new_stem):] # leading "_entity" or ""
|
||||
for old_stem in _old_file_stems(rel):
|
||||
if old_stem == new_stem:
|
||||
continue
|
||||
if is_py_stdlib_stem and old_stem in _PYTHON_STDLIB_MODULE_NAMES:
|
||||
continue
|
||||
alias = old_stem + suffix
|
||||
_alias_candidates.setdefault(_normalize_id(alias), set()).add(nid)
|
||||
_alias_candidates.setdefault(alias, set()).add(nid)
|
||||
if attrs.get("_origin") == "ast" and str(attrs.get("label", "")).startswith("."):
|
||||
m_name = make_id(str(attrs.get("label", "")).strip().removeprefix(".").removesuffix("()"))
|
||||
m_alias = f"{new_stem}_{m_name}"
|
||||
if _normalize_id(nid) != _normalize_id(m_alias):
|
||||
_alias_candidates.setdefault(_normalize_id(m_alias), set()).add(nid)
|
||||
_alias_candidates.setdefault(m_alias, set()).add(nid)
|
||||
for alias_key, candidates in _alias_candidates.items():
|
||||
if len(candidates) == 1:
|
||||
norm_to_id.setdefault(alias_key, next(iter(candidates)))
|
||||
#
|
||||
# The index itself lives in _alias_index so the raw (--no-cluster) write
|
||||
# path resolves endpoints identically (#4670).
|
||||
#
|
||||
# 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
|
||||
# and makes the serialized graph churn. Sorting fixes the last-write outcome.
|
||||
dropped_schema_edges = 0
|
||||
for edge in sorted(
|
||||
extraction.get("edges", []),
|
||||
key=lambda e: (
|
||||
@@ -1612,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
|
||||
@@ -1663,6 +2077,8 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
|
||||
if not math.isfinite(_num_val) or _num_val < 0:
|
||||
_num_val = 1.0
|
||||
attrs[_num_key] = _num_val
|
||||
if "also_seen" in attrs:
|
||||
_fold_also_seen(attrs, {})
|
||||
# Backfill source_file from the endpoint nodes (every node carries one).
|
||||
# Semantic/LLM edges occasionally omit it, which downstream validation
|
||||
# flags and leaves query results with no file reference (#1279).
|
||||
@@ -1674,6 +2090,13 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
|
||||
)
|
||||
if "source_file" in attrs:
|
||||
attrs["source_file"] = _norm_source_file(attrs["source_file"], _root)
|
||||
# Relation aliases are folded before validation, but a still-missing
|
||||
# relation has no trustworthy default. Other historically tolerated edge
|
||||
# gaps have repair/default paths elsewhere in this builder; relation does
|
||||
# not. Fail closed rather than persist an uninterpretable edge (#4809).
|
||||
if "relation" not in attrs:
|
||||
dropped_schema_edges += 1
|
||||
continue
|
||||
if attrs.get("definition_file"):
|
||||
# Same portability rule as source_file (#3223); heals a graph
|
||||
# written before the fix on its next rebuild.
|
||||
@@ -1744,6 +2167,15 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
|
||||
incoming_rel = attrs.get("relation")
|
||||
reverse = existing.get("_src") == tgt and existing.get("_tgt") == src
|
||||
if reverse and existing_rel == incoming_rel:
|
||||
# For an import the dropped leg is the other half of a two-file
|
||||
# cycle. Stamp the kept edge so find_import_cycles still sees it
|
||||
# (#4839); a type-only or deferred import closes no cycle.
|
||||
if (
|
||||
incoming_rel in ("imports_from", "re_exports")
|
||||
and not attrs.get("type_only")
|
||||
and not attrs.get("deferred")
|
||||
):
|
||||
existing["reverse_import"] = True
|
||||
continue
|
||||
# Different relations in opposite directions are two facts that only
|
||||
# share a pair because the graph is undirected. A type's
|
||||
@@ -1784,9 +2216,11 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
|
||||
existing_rank = _CONFIDENCE_RANK.get(existing_conf, 0)
|
||||
incoming_rank = _CONFIDENCE_RANK.get(incoming_conf, 0)
|
||||
if existing_rank > incoming_rank:
|
||||
_fold_also_seen(existing_attrs, attrs)
|
||||
continue
|
||||
if existing_rank == incoming_rank:
|
||||
if existing_attrs.get("source_location") and not attrs.get("source_location"):
|
||||
_fold_also_seen(existing_attrs, attrs)
|
||||
continue
|
||||
existing_score = existing_attrs.get("confidence_score")
|
||||
incoming_score = attrs.get("confidence_score")
|
||||
@@ -1795,8 +2229,21 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
|
||||
and incoming_score is not None
|
||||
and existing_score > incoming_score
|
||||
):
|
||||
_fold_also_seen(existing_attrs, attrs)
|
||||
continue
|
||||
_fold_also_seen(attrs, existing_attrs)
|
||||
# add_edge merges into the stored dict: a field only the loser
|
||||
# carried (its score, its line) would otherwise stay on the winner.
|
||||
for _key in (*_EVIDENCE_KEYS, "also_seen"):
|
||||
if _key not in attrs:
|
||||
existing_attrs.pop(_key, None)
|
||||
G.add_edge(src, tgt, **attrs)
|
||||
if dropped_schema_edges:
|
||||
print(
|
||||
f"[graphify] WARNING: dropped {dropped_schema_edges} schema-invalid edge(s) "
|
||||
"missing required field 'relation'.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
hyperedges = extraction.get("hyperedges", [])
|
||||
if hyperedges:
|
||||
# Relativize hyperedge source_file the same way nodes and edges are
|
||||
@@ -1857,6 +2304,9 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
|
||||
# directory-qualified display label so lookup/discovery can disambiguate
|
||||
# them (#2032). Labels only — ids and edges are untouched.
|
||||
_disambiguate_file_node_labels(G)
|
||||
# Also last, after the method-ghost passes above: C# methods display with
|
||||
# their owning type (#4883).
|
||||
_qualify_csharp_method_labels(G)
|
||||
return G
|
||||
|
||||
|
||||
@@ -1896,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
|
||||
@@ -1925,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)
|
||||
@@ -1932,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
|
||||
|
||||
|
||||
@@ -1950,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):
|
||||
@@ -2014,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
|
||||
@@ -2042,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
|
||||
@@ -2054,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)),
|
||||
)
|
||||
|
||||
@@ -2635,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
|
||||
@@ -2728,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.
|
||||
@@ -2772,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
|
||||
|
||||
|
||||
|
||||
+149
-30
@@ -17,6 +17,7 @@ from pathlib import Path
|
||||
# absolute path ("/shared/graphify-out"). Single source of truth in graphify.paths
|
||||
# (#1423); re-exported here as _GRAPHIFY_OUT for the existing call sites.
|
||||
from graphify.paths import GRAPHIFY_OUT as _GRAPHIFY_OUT
|
||||
from graphify.paths import os_long_path as _os_long_path
|
||||
from graphify.paths import os_replace_with_fallback as _os_replace_with_fallback
|
||||
|
||||
# AST cache entries are the output of graphify's own extractor code, so they
|
||||
@@ -37,7 +38,7 @@ except Exception:
|
||||
_EXTRACTOR_VERSION = "unknown"
|
||||
|
||||
# Bump when AST cache-key semantics change independently of the package version.
|
||||
_AST_CACHE_SCHEMA = 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 (`_rust_use_name`, #4439); (15): Go generic receiver types normalized (`Box[T]` -> `Box`) so methods attach to the type node; prior (14): C# receiver resolution for nameless/`new X()`/`foreach` receivers (defer + receiver-chain markers) and `_`/case-distinct node ids (underscore-salted); prior (13): Kotlin/Scala/C++/Swift generic & template type params no longer mint sourceless stubs; Objective-C NS_ENUM/NS_OPTIONS extraction and `_callable`/`_callable_class` markers; Go and PHP receiver-typed member calls park cross-repo (`go_type_table`/`php_type_table`, receiver fields); prior (12): Java inherited-supertype (`receiver_unbound`) and chained/new/cast receiver typing (`java_receiver_chain`, `_java_ret`); C/C++ quoted cross-directory include provenance (`include_kind`); JS external imports anchored to the package, not the path leaf; prior (11): Python property-accessor decorators / `Self`, Swift `Self`, Go generic type params, Python forward type-hint file node, PowerShell dot-source, C# verbatim-interpolated string recovery; (10): C# partial types carry `type_path`; (9): Python property-read raw calls and `_py_property` nodes; (8): Rust `use`-group per-binding edges; (7): Python opaque-base/super(args) markers + nested-class enclosing ids.
|
||||
_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
|
||||
@@ -410,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 = {}
|
||||
@@ -498,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:
|
||||
@@ -524,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:
|
||||
@@ -545,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:
|
||||
@@ -566,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):
|
||||
@@ -592,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")
|
||||
@@ -627,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"]
|
||||
@@ -643,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
|
||||
@@ -1099,10 +1123,11 @@ def load_cached(path: Path, root: Path = Path("."), kind: str = "ast",
|
||||
return None
|
||||
h = _salted_key(h, salt)
|
||||
prompt_fp = _resolve_prompt_fp(prompt, prompt_file)
|
||||
entry = cache_dir(location, kind, prompt_fp) / f"{h}.json"
|
||||
# Extended-length form so a deep root does not push the entry past MAX_PATH.
|
||||
entry = Path(_os_long_path(cache_dir(location, kind, prompt_fp) / f"{h}.json"))
|
||||
legacy_hit = False
|
||||
if prompt_fp and not entry.exists() and allow_legacy:
|
||||
legacy = cache_dir(location, kind) / f"{h}.json"
|
||||
legacy = Path(_os_long_path(cache_dir(location, kind) / f"{h}.json"))
|
||||
if legacy.exists():
|
||||
entry, legacy_hit = legacy, True
|
||||
if entry.exists():
|
||||
@@ -1263,8 +1288,10 @@ def save_cached(path: Path, result: dict, root: Path = Path("."), kind: str = "a
|
||||
_relativize_ids_in(on_disk, p, root)
|
||||
h = _salted_key(file_hash(p, root, cache_root=cache_root), salt)
|
||||
location = cache_root if cache_root is not None else root
|
||||
target_dir = cache_dir(location, kind, _resolve_prompt_fp(prompt, prompt_file))
|
||||
entry = target_dir / f"{h}.json"
|
||||
# Extended-length form: under a deep root the entry, and its longer temp
|
||||
# name, overrun Windows MAX_PATH and the write fails the whole extraction.
|
||||
target_dir = _os_long_path(cache_dir(location, kind, _resolve_prompt_fp(prompt, prompt_file)))
|
||||
entry = os.path.join(target_dir, f"{h}.json")
|
||||
fd, tmp_path = tempfile.mkstemp(dir=target_dir, prefix=f"{h}.", suffix=".tmp")
|
||||
try:
|
||||
os.write(fd, json.dumps(on_disk).encode())
|
||||
@@ -1822,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("."),
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -26,6 +27,29 @@ def _load_toml(path: Path) -> dict[str, Any]:
|
||||
return tomllib.load(manifest)
|
||||
|
||||
|
||||
def package_name(manifest: Path) -> str | None:
|
||||
"""A Cargo.toml's `[package] name` as Rust spells it in a path (`-` -> `_`).
|
||||
|
||||
Returns None when the manifest has no package name, cannot be read, or
|
||||
cannot be parsed. Callers that scope a Rust import to a crate treat "no
|
||||
name" as "no crate", never as an error, so this stays silent.
|
||||
"""
|
||||
try:
|
||||
package = _load_toml(manifest).get("package")
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
except ImportError: # Python 3.10 without tomli: recover the one key we need
|
||||
try:
|
||||
text = manifest.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
return None
|
||||
match = re.search(r'^\[package\][^\[]*?^name\s*=\s*"([^"]+)"', text, re.M | re.S)
|
||||
name = match.group(1) if match else None
|
||||
else:
|
||||
name = package.get("name") if isinstance(package, dict) else None
|
||||
return name.replace("-", "_") if isinstance(name, str) and name else None
|
||||
|
||||
|
||||
def _discover_root_manifest(root: Path) -> Path | None:
|
||||
"""Find a Cargo.toml under *root* when none sits directly at the root.
|
||||
|
||||
|
||||
+847
-135
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:
|
||||
|
||||
@@ -14,7 +14,10 @@ The resolvers now park those calls on the caller node as
|
||||
``_park_unresolved_member_call``). This pass reads them back after the graphs are
|
||||
composed and emits the ``calls`` edge when the receiver's type resolves to
|
||||
exactly one declaration in another repo, keeping the single-definition guard the
|
||||
single-repo resolvers use: an ambiguous name still fabricates nothing.
|
||||
single-repo resolvers use: an ambiguous name still fabricates nothing. An ObjC
|
||||
class split ``@interface``(.h)/``@implementation``(.m) across repos is the one
|
||||
exception — several same-named candidates bind to the sole one that DEFINES the
|
||||
selector (#1556), two definitions still being an ambiguity.
|
||||
|
||||
Edges only, no node merging or renaming, so the pass composes with the prefixing
|
||||
and pruning already in place. Every edge it adds is tagged, and it clears its own
|
||||
@@ -59,6 +62,11 @@ _LANG_SUFFIXES: dict[str, frozenset[str]] = {
|
||||
# carries `defines` instead. `method` wins when both name the same member.
|
||||
_MEMBER_RELATIONS = ("defines", "method")
|
||||
|
||||
# An ObjC @implementation lives in a `.m`/`.mm`; a `.h` carries only the @interface
|
||||
# declaration. This is what tells the one DEFINITION apart from the declarations when
|
||||
# a class is split across repositories.
|
||||
_OBJC_IMPL_SUFFIXES = frozenset({".m", ".mm"})
|
||||
|
||||
|
||||
def _key(label: object) -> str:
|
||||
"""Normalize a node label or a parked name to its bare identifier.
|
||||
@@ -172,6 +180,34 @@ def _member_keys(lang: str, callee: str) -> tuple[str, ...]:
|
||||
return (callee,)
|
||||
|
||||
|
||||
def _objc_union_definition(
|
||||
merged: "nx.Graph",
|
||||
members: dict[tuple[str, str], list[str]],
|
||||
candidates: list[str],
|
||||
callee: str,
|
||||
) -> str | None:
|
||||
"""The sole DEFINITION of an ObjC selector across same-named candidates.
|
||||
|
||||
An ObjC class whose `@interface` (`.h`) and `@implementation` (`.m`) live in
|
||||
different repositories surfaces as several same-named candidates that
|
||||
``_merge_decl_def_classes`` folds within a repo but cannot across the boundary
|
||||
(its id embeds the directory, #1556). The candidate that DEFINES the selector —
|
||||
an impl in `.m`/`.mm`, or a folded node naming its impl in ``definition_file`` —
|
||||
is the target; a bare header declaration is not. Two candidates that both define
|
||||
it are two unrelated classes and stay ambiguous, so the single-definition guard
|
||||
still holds for the collision it was meant to catch.
|
||||
"""
|
||||
defs: list[str] = []
|
||||
for cand in candidates:
|
||||
for member_key in _member_keys("objc", callee):
|
||||
for member in members.get((cand, member_key), []):
|
||||
data = merged.nodes[member]
|
||||
if data.get("definition_file") or _suffix(data.get("source_file")) in _OBJC_IMPL_SUFFIXES:
|
||||
defs.append(member)
|
||||
defs = list(dict.fromkeys(defs))
|
||||
return defs[0] if len(defs) == 1 else None
|
||||
|
||||
|
||||
def link_cross_repo_member_calls(merged: "nx.Graph") -> int:
|
||||
"""Emit `calls` edges for parked member calls another repo answers.
|
||||
|
||||
@@ -228,31 +264,42 @@ def link_cross_repo_member_calls(merged: "nx.Graph") -> int:
|
||||
if merged.nodes[node].get("repo") != caller_repo
|
||||
and _suffix(merged.nodes[node].get("source_file")) in suffixes
|
||||
]
|
||||
if len(candidates) != 1:
|
||||
# The same guard the single-repo resolvers apply: two repos
|
||||
# declaring the same name is an ambiguity, not a hit.
|
||||
if not candidates:
|
||||
continue
|
||||
if lang == "csharp":
|
||||
# Reuse the extractor's authoritative C# visibility rules. A
|
||||
# candidate is valid only when the caller's namespace, using,
|
||||
# or alias resolves this exact receiver name to that node.
|
||||
resolved, _decisive = csharp_resolver.resolve_type_name(
|
||||
receiver_type,
|
||||
dict(caller_data, id=caller),
|
||||
str(caller_data.get("source_file") or ""),
|
||||
)
|
||||
if resolved != candidates[0]:
|
||||
if lang == "objc" and len(candidates) > 1:
|
||||
# A class split @interface(.h)/@implementation(.m) across repos
|
||||
# leaves several same-named candidates; bind the selector to its
|
||||
# sole definition rather than bailing on the collision guard.
|
||||
target = _objc_union_definition(
|
||||
merged, members_by_relation["method"], candidates, callee)
|
||||
if target is None:
|
||||
continue
|
||||
targets: list[str] = []
|
||||
for relation in _member_relations(lang):
|
||||
members = members_by_relation[relation]
|
||||
for member_key in _member_keys(lang, callee):
|
||||
targets.extend(members.get((candidates[0], member_key), []))
|
||||
if targets:
|
||||
break
|
||||
if len(targets) != 1:
|
||||
continue
|
||||
target = targets[0]
|
||||
else:
|
||||
if len(candidates) != 1:
|
||||
# The same guard the single-repo resolvers apply: two repos
|
||||
# declaring the same name is an ambiguity, not a hit.
|
||||
continue
|
||||
if lang == "csharp":
|
||||
# Reuse the extractor's authoritative C# visibility rules. A
|
||||
# candidate is valid only when the caller's namespace, using,
|
||||
# or alias resolves this exact receiver name to that node.
|
||||
resolved, _decisive = csharp_resolver.resolve_type_name(
|
||||
receiver_type,
|
||||
dict(caller_data, id=caller),
|
||||
str(caller_data.get("source_file") or ""),
|
||||
)
|
||||
if resolved != candidates[0]:
|
||||
continue
|
||||
targets: list[str] = []
|
||||
for relation in _member_relations(lang):
|
||||
members = members_by_relation[relation]
|
||||
for member_key in _member_keys(lang, callee):
|
||||
targets.extend(members.get((candidates[0], member_key), []))
|
||||
if targets:
|
||||
break
|
||||
if len(targets) != 1:
|
||||
continue
|
||||
target = targets[0]
|
||||
if target == caller or merged.has_edge(caller, target):
|
||||
continue
|
||||
merged.add_edge(
|
||||
@@ -262,7 +309,12 @@ def link_cross_repo_member_calls(merged: "nx.Graph") -> int:
|
||||
context="cross_repo",
|
||||
confidence="INFERRED",
|
||||
confidence_score=0.85,
|
||||
source_file=str(caller_data.get("source_file") or ""),
|
||||
# The parked call-site file (the .m), not the caller node's own
|
||||
# source_file (often the .h where the method is declared): the
|
||||
# location below is the call-site line, so pairing it with the
|
||||
# .h would point past the end of an unrelated file. Pre-#3152
|
||||
# graphs have no `file`, so fall back to the caller's file.
|
||||
source_file=str(entry.get("file") or caller_data.get("source_file") or ""),
|
||||
source_location=entry.get("line"),
|
||||
weight=1.0,
|
||||
_src=caller,
|
||||
|
||||
+191
-7
@@ -446,12 +446,14 @@ def _rank_path(source_file: str, root: Path | None) -> str:
|
||||
|
||||
|
||||
def _collision_rank(node: dict, root: Path | None = None,
|
||||
mentions: "frozenset | set" = frozenset()) -> tuple:
|
||||
mentions: "frozenset | set" = frozenset(),
|
||||
outranked: "frozenset | set" = frozenset()) -> tuple:
|
||||
"""A total order for choosing the survivor of an ID collision, independent of
|
||||
the order the colliding nodes arrive in.
|
||||
|
||||
The winner is the node with the SMALLEST rank. A node whose ``source_file``
|
||||
defines the ID always outranks a mere reference; among equally-(non-)defining
|
||||
defines the ID always outranks a mere reference, and a definer listed in
|
||||
``outranked`` ranks behind the other definers (#4859); among equally-(non-)defining
|
||||
nodes an active/in-progress path outranks an archived/done one (#2532); then
|
||||
it prefers the shorter, more canonical label over a longer qualified variant,
|
||||
then breaks any remaining tie lexically on label and finally on the REVERSED
|
||||
@@ -470,6 +472,14 @@ def _collision_rank(node: dict, root: Path | None = None,
|
||||
level up (#3775/#3786). It changes no collision between two sourced
|
||||
nodes, since both sides of that key agree there.
|
||||
|
||||
``outranked`` (see ``_outranked_by_ast``) holds the ``(id, file)`` of non-AST
|
||||
definers that another file's AST node also defines. A doc whose own path
|
||||
prefixes a code entity's id (``pkg.md`` beside ``pkg/test_x.py``) defines it
|
||||
too, and used to take it on a shorter label, so its next re-extract deleted the
|
||||
code node (#4859). Such a definer now ranks right behind the other definers;
|
||||
same-file pairs (#2091), same-stem twins, and collisions with one definer
|
||||
rank as before.
|
||||
|
||||
``mentions`` (see ``_mentions``) holds the ``(id, file)`` of nodes read as a
|
||||
mention of a document rather than the document itself. Such a node ranks as a
|
||||
reference even though its id is a path slice, so a real document outranks it
|
||||
@@ -481,9 +491,10 @@ def _collision_rank(node: dict, root: Path | None = None,
|
||||
"""
|
||||
label = node.get("label") or ""
|
||||
rank_path = _rank_path(node.get("source_file") or "", root)
|
||||
key = (node.get("id"), rank_path)
|
||||
return (
|
||||
# definers (False) sort before references (True)
|
||||
not _defines_id(node) or (node.get("id"), rank_path) in mentions,
|
||||
not _defines_id(node) or key in mentions,
|
||||
key in outranked and node.get("_origin") != "ast", # (#4859)
|
||||
not node.get("source_file"), # a located node beats a source-less one (#4492)
|
||||
_lifecycle_penalty(rank_path), # active paths beat archived ones (#2532)
|
||||
len(label), # shorter, more canonical label first
|
||||
@@ -492,6 +503,40 @@ def _collision_rank(node: dict, root: Path | None = None,
|
||||
)
|
||||
|
||||
|
||||
def _outranked_by_ast(nodes: list[dict], root: Path | None,
|
||||
mentions: "frozenset | set") -> set[tuple[str, str]]:
|
||||
"""``(id, root-relative file)`` of non-AST definers that an AST node from
|
||||
another file also defines, while their own file has no AST definer (#4859).
|
||||
|
||||
The AST node is extracted fact and the other is an inference about it, so the
|
||||
AST node keeps the id. The check is strict on ``_origin == "ast"``, as in the
|
||||
build ghost pass: fresh semantic chunks arrive unstamped. A file that has its
|
||||
own AST definer (#2091 enrichment) is never listed, and an AST node with the
|
||||
same full stem (an ``x.py``/``x.html`` twin, or a slug twin such as
|
||||
``pkg/service.py`` and ``pkg_service.py``) never counts against it.
|
||||
"""
|
||||
ast_defs: dict[str, list[tuple[str, str]]] = defaultdict(list)
|
||||
others: list[tuple[str, str, str]] = []
|
||||
for node in nodes:
|
||||
nid = node.get("id") or ""
|
||||
source_file = node.get("source_file") or ""
|
||||
rank_path = _rank_path(source_file, root)
|
||||
if not nid or not _defines_id(node) or (nid, rank_path) in mentions:
|
||||
continue
|
||||
entry = (rank_path, _full_stem(source_file))
|
||||
if node.get("_origin") == "ast":
|
||||
ast_defs[nid].append(entry)
|
||||
else:
|
||||
others.append((nid, *entry))
|
||||
outranked = set()
|
||||
for nid, rank_path, stem in others:
|
||||
defs = ast_defs.get(nid, [])
|
||||
if (defs and rank_path not in {rp for rp, _ in defs}
|
||||
and any(ast_stem != stem for _, ast_stem in defs)):
|
||||
outranked.add((nid, rank_path))
|
||||
return outranked
|
||||
|
||||
|
||||
def _mentions(nodes: list[dict], edges: list[dict],
|
||||
root: Path | None) -> set[tuple[str, str]]:
|
||||
"""``(id, root-relative file)`` of nodes read as a MENTION of a document (#4281).
|
||||
@@ -609,6 +654,9 @@ def _merge_missing_attributes(survivor: dict, duplicate: dict) -> dict:
|
||||
return merged
|
||||
|
||||
|
||||
_SHARED_ID_TYPES = ("module", "namespace")
|
||||
|
||||
|
||||
def _report_id_collision(nid: str, survivor: dict, losers: list[dict]) -> None:
|
||||
"""Report an ID collision in proportion to what dropping the loser actually costs.
|
||||
|
||||
@@ -619,6 +667,18 @@ def _report_id_collision(nid: str, survivor: dict, losers: list[dict]) -> None:
|
||||
and one is genuinely lost — warn, and point at the extraction split that keeps them
|
||||
apart (#1504).
|
||||
"""
|
||||
# A module/namespace node (`import Foundation`) is one shared entity that every
|
||||
# importing file legitimately mints — the same rule the extractors apply when
|
||||
# they exempt these types from collision disambiguation. Only a group of one
|
||||
# such type under one label is that shared entity; a module colliding with a
|
||||
# namespace, or two differently named modules, is still a real collision.
|
||||
group = (survivor, *losers)
|
||||
if (
|
||||
survivor.get("type") in _SHARED_ID_TYPES
|
||||
and all(n.get("type") == survivor.get("type") for n in group)
|
||||
and all(n.get("label") == survivor.get("label") for n in group)
|
||||
):
|
||||
return
|
||||
keep_file = survivor.get("source_file") or ""
|
||||
keep_label = survivor.get("label") or ""
|
||||
for loser in losers:
|
||||
@@ -905,6 +965,120 @@ def _path_qualify_dropped_collisions(
|
||||
return out_nodes, edges
|
||||
|
||||
|
||||
def _is_reference_stub(node: dict) -> bool:
|
||||
"""Whether semantic extraction marked a node as a cross-document stub."""
|
||||
metadata = node.get("metadata")
|
||||
return isinstance(metadata, dict) and metadata.get("graphify_reference_stub") is True
|
||||
|
||||
|
||||
def _namespace_reference_stub_collisions(
|
||||
nodes: list[dict], edges: list[dict], hyperedges: list[dict] | None,
|
||||
root: Path | None, *, preserve_saved_semantics: bool = False,
|
||||
) -> tuple[list[dict], list[dict]]:
|
||||
"""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
|
||||
``<citing-file>__ref__<original-id>`` instead of silently dropping it when
|
||||
its target ID collides with another file's node. Edges from the citing file
|
||||
follow its namespaced endpoint.
|
||||
|
||||
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 ""
|
||||
|
||||
by_id: dict[str, list[dict]] = defaultdict(list)
|
||||
for node in nodes:
|
||||
nid = node.get("id")
|
||||
if isinstance(nid, str) and nid:
|
||||
by_id[nid].append(node)
|
||||
|
||||
taken = {node.get("id") for node in nodes if node.get("id")}
|
||||
renames: dict[tuple[str, str], str] = {}
|
||||
for nid, members in by_id.items():
|
||||
if len({key(node.get("source_file")) for node in members}) < 2:
|
||||
continue
|
||||
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}
|
||||
if "" in source_keys:
|
||||
continue
|
||||
candidates = {
|
||||
source_key: f"{_full_stem(source_key)}__ref__{nid}"
|
||||
for source_key in source_keys
|
||||
if _full_stem(source_key)
|
||||
}
|
||||
if len(candidates) != len(source_keys):
|
||||
continue
|
||||
if len(set(candidates.values())) != len(candidates):
|
||||
continue
|
||||
if any(candidate in taken for candidate in candidates.values()):
|
||||
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())
|
||||
|
||||
if not renames:
|
||||
return nodes, edges
|
||||
|
||||
out_nodes = [
|
||||
dict(node, id=renames[(node["id"], key(node.get("source_file")))])
|
||||
if (node.get("id"), key(node.get("source_file"))) in renames else node
|
||||
for node in nodes
|
||||
]
|
||||
for collection in (edges, hyperedges or []):
|
||||
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)
|
||||
replacement = renames.get((value, source_key))
|
||||
if replacement:
|
||||
item[endpoint] = replacement
|
||||
members = item.get("nodes")
|
||||
if isinstance(members, list):
|
||||
item["nodes"] = [renames.get((member, source_key), member)
|
||||
if isinstance(member, str) else member
|
||||
for member in members]
|
||||
return out_nodes, edges
|
||||
|
||||
|
||||
# ── main entry point ──────────────────────────────────────────────────────────
|
||||
|
||||
def _remap_hyperedge_members(hyperedges: list[dict], remap: dict[str, str]) -> None:
|
||||
@@ -956,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.
|
||||
|
||||
@@ -963,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)
|
||||
@@ -1003,7 +1181,11 @@ def deduplicate_entities(
|
||||
# Genuine cross-file ID collisions stay isolated and are reported below (#1504).
|
||||
nodes, edges = _disambiguate_defining_collisions(nodes, edges, hyperedges, root_resolved)
|
||||
nodes, edges = _path_qualify_dropped_collisions(nodes, edges, hyperedges, root_resolved)
|
||||
nodes, edges = _namespace_reference_stub_collisions(
|
||||
nodes, edges, hyperedges, root_resolved,
|
||||
)
|
||||
mentions = _mentions(nodes, edges, root_resolved) | _slice_references(nodes, root_resolved)
|
||||
outranked = _outranked_by_ast(nodes, root_resolved, mentions)
|
||||
seen_ids: dict[str, dict] = {}
|
||||
dropped: dict[str, list[dict]] = defaultdict(list)
|
||||
for node in nodes:
|
||||
@@ -1013,8 +1195,8 @@ def deduplicate_entities(
|
||||
incumbent = seen_ids.get(nid)
|
||||
if incumbent is None:
|
||||
seen_ids[nid] = node
|
||||
elif (_collision_rank(node, root_resolved, mentions)
|
||||
< _collision_rank(incumbent, root_resolved, mentions)):
|
||||
elif (_collision_rank(node, root_resolved, mentions, outranked)
|
||||
< _collision_rank(incumbent, root_resolved, mentions, outranked)):
|
||||
# Smallest-ranked node wins; the min over a total order is independent
|
||||
# of the order nodes arrive in, so the survivor no longer depends on
|
||||
# chunk ordering (#1851).
|
||||
@@ -1032,7 +1214,7 @@ def deduplicate_entities(
|
||||
survivor = seen_ids[nid]
|
||||
same_source = sorted(
|
||||
(l for l in losers if _same_source_entity(survivor, l)),
|
||||
key=lambda l: _collision_rank(l, root_resolved, mentions),
|
||||
key=lambda l: _collision_rank(l, root_resolved, mentions, outranked),
|
||||
)
|
||||
for loser in same_source:
|
||||
survivor = _merge_missing_attributes(survivor, loser)
|
||||
@@ -1391,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
|
||||
|
||||
+399
-131
@@ -22,7 +22,7 @@ from graphify.google_workspace import (
|
||||
convert_google_workspace_file,
|
||||
google_workspace_enabled,
|
||||
)
|
||||
from graphify.paths import GRAPHIFY_OUT, GRAPHIFY_OUT_NAME, out_path
|
||||
from graphify.paths import GRAPHIFY_OUT, GRAPHIFY_OUT_NAME, os_long_path, out_path
|
||||
from graphify.rcfile import activate_language_overrides, cache_salt, effective_suffix
|
||||
|
||||
|
||||
@@ -45,16 +45,24 @@ _MANIFEST_PATH = str(out_path("manifest.json"))
|
||||
_MTIME_COARSE_S = 2.0
|
||||
_MTIME_SUBSECOND_S = 0.05
|
||||
|
||||
CODE_EXTENSIONS = {'.py', '.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs', '.ejs', '.ets', '.go', '.rs', '.vb', '.cbl', '.cob', '.cobol', '.cpy', '.java', '.groovy', '.gradle', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.cu', '.cuh', '.metal', '.rb', '.rake', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.luau', '.toc', '.zig', '.ps1', '.psm1', '.psd1', '.ex', '.exs', '.m', '.mm', '.ml', '.mli', '.jl', '.vue', '.svelte', '.astro', '.dart', '.v', '.sv', '.svh', '.vh', '.sql', '.r', '.f', '.F', '.f90', '.F90', '.f95', '.F95', '.f03', '.F03', '.f08', '.F08', '.pas', '.pp', '.dpr', '.dpk', '.lpr', '.inc', '.dfm', '.lfm', '.lpk', '.sh', '.bash', '.json', '.tf', '.tfvars', '.hcl', '.dm', '.dme', '.dmi', '.dmm', '.dmf', '.sln', '.slnx', '.csproj', '.fsproj', '.vbproj', '.xaml', '.razor', '.cshtml', '.cls', '.trigger', '.lisp', '.cl', '.lsp', '.asd', '.robot', '.resource', '.sol', '.erl', '.hrl', '.escript'}
|
||||
DOC_EXTENSIONS = {'.md', '.mdx', '.qmd', '.skill', '.txt', '.rst', '.html', '.yaml', '.yml', '.j2', '.jinja', '.jinja2'}
|
||||
CODE_EXTENSIONS = {'.py', '.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs', '.ejs', '.ets', '.go', '.rs', '.vb', '.cbl', '.cob', '.cobol', '.cpy', '.java', '.groovy', '.gradle', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.cu', '.cuh', '.metal', '.rb', '.rake', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.luau', '.toc', '.zig', '.ps1', '.psm1', '.psd1', '.ex', '.exs', '.m', '.mm', '.ml', '.mli', '.jl', '.vue', '.svelte', '.astro', '.dart', '.v', '.sv', '.svh', '.vh', '.sql', '.r', '.f', '.F', '.f90', '.F90', '.f95', '.F95', '.f03', '.F03', '.f08', '.F08', '.pas', '.pp', '.dpr', '.dpk', '.lpr', '.inc', '.dfm', '.lfm', '.lpk', '.sh', '.bash', '.json', '.yaml', '.yml', '.tf', '.tfvars', '.hcl', '.dm', '.dme', '.dmi', '.dmm', '.dmf', '.sln', '.slnx', '.csproj', '.fsproj', '.vbproj', '.xaml', '.razor', '.cshtml', '.cls', '.trigger', '.lisp', '.cl', '.lsp', '.asd', '.robot', '.resource', '.sol', '.erl', '.hrl', '.escript'}
|
||||
DOC_EXTENSIONS = {'.md', '.mdx', '.qmd', '.skill', '.txt', '.rst', '.html', '.j2', '.jinja', '.jinja2'}
|
||||
PAPER_EXTENSIONS = {'.pdf'}
|
||||
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
|
||||
OFFICE_EXTENSIONS = {'.docx', '.xlsx'}
|
||||
VIDEO_EXTENSIONS = {'.mp4', '.mov', '.webm', '.mkv', '.avi', '.m4v', '.mp3', '.wav', '.m4a', '.ogg'}
|
||||
_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
|
||||
@@ -931,6 +939,8 @@ def convert_office_file(path: Path, out_dir: Path, root: "Path | None" = None) -
|
||||
def count_words(path: Path) -> int:
|
||||
try:
|
||||
ext = path.suffix.lower()
|
||||
if ext in _BINARY_MEDIA_EXTENSIONS:
|
||||
return 0
|
||||
if ext == ".pdf":
|
||||
return len(extract_pdf_text(path).split())
|
||||
if ext == ".docx":
|
||||
@@ -1003,6 +1013,30 @@ _SKIP_FILES = {
|
||||
".graphifyinclude",
|
||||
}
|
||||
|
||||
# Files a JS/TS toolchain reads to resolve modules: workspace package roots,
|
||||
# tsconfig `paths`/`baseUrl`, and the installed dependency tree. Changing one of
|
||||
# these can change a .ts/.tsx/.js result without touching a single source file, so
|
||||
# the no-change gate in watch._rebuild_code() has to see them (#4740).
|
||||
# tsconfig*.json / jsconfig.json / package.json are ordinary scan input (they land
|
||||
# in the "code" bucket and are stamped in the manifest like any other file). The
|
||||
# lock files are in _SKIP_FILES, so detect() records them separately instead.
|
||||
_RESOLUTION_INPUT_NAMES = frozenset({
|
||||
"package.json", "package-lock.json", "pnpm-lock.yaml", "yarn.lock",
|
||||
"jsconfig.json",
|
||||
})
|
||||
_TS_CONFIG_NAME_RE = re.compile(r"^tsconfig(\.[^/\\]+)?\.json$")
|
||||
|
||||
|
||||
def is_resolution_input(path: "Path | str") -> bool:
|
||||
"""True when ``path`` steers JS/TS module resolution (#4740).
|
||||
|
||||
Deliberately over-approximate: a false positive only costs a slower run, a
|
||||
false negative ships a stale graph.
|
||||
"""
|
||||
name = Path(path).name.lower()
|
||||
return name in _RESOLUTION_INPUT_NAMES or bool(_TS_CONFIG_NAME_RE.match(name))
|
||||
|
||||
|
||||
# A bare "snapshots" dir is a Jest/Vitest artifact only when it actually holds
|
||||
# snapshot files or lives directly under a JS test root. Elsewhere it is often a
|
||||
# real code namespace (e.g. Rails app/services/snapshots/), so pruning it by name
|
||||
@@ -1011,7 +1045,8 @@ _SKIP_FILES = {
|
||||
_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
|
||||
@@ -1146,6 +1181,53 @@ def _has_venv_markers(d: "Path") -> bool:
|
||||
return False
|
||||
|
||||
|
||||
# Files only MSBuild/NuGet write. ``obj/`` gets the restore outputs (every
|
||||
# SDK-style restore writes project.assets.json) and, for legacy non-SDK
|
||||
# projects, the per-configuration FileListAbsolute.txt. ``bin/`` gets the
|
||||
# runtime manifests the SDK emits next to every executable, plus the PDBs.
|
||||
# .dll/.exe are deliberately absent: a checked-in tools/bin/ of vendored
|
||||
# binaries next to its wrapper scripts is source, not output.
|
||||
_MSBUILD_OBJ_MARKERS = (
|
||||
"project.assets.json", ".nuget.dgspec.json", ".nuget.g.props",
|
||||
".filelistabsolute.txt",
|
||||
)
|
||||
_MSBUILD_BIN_MARKERS = (".deps.json", ".runtimeconfig.json", ".pdb")
|
||||
|
||||
|
||||
def _has_msbuild_markers(d: "Path", markers: tuple, max_depth: int) -> bool:
|
||||
"""True when a file ending in one of *markers* sits within *max_depth*
|
||||
directory levels below *d*.
|
||||
|
||||
``bin`` and ``obj`` are MSBuild's output and intermediate dirs, and an
|
||||
unignored C# project carries both after its first build: the generated
|
||||
GlobalUsings/AssemblyInfo sources land in the graph as file nodes with
|
||||
import edges to every implicit namespace, and the build-copied
|
||||
appsettings*.json are scanned twice. ``dotnet new`` writes no .gitignore,
|
||||
so nothing else stops them. Neither name is safe to prune alone — ``bin``
|
||||
is source in Rust's src/bin/, Ruby binstubs and script dirs — so prune
|
||||
only on MSBuild's own artifacts, the same keep-on-doubt gating ``out``
|
||||
gets (#3347). The walk is bounded by entries scanned, not just depth.
|
||||
"""
|
||||
budget = 4000
|
||||
pending = [(str(d), 0)]
|
||||
while pending:
|
||||
current, depth = pending.pop()
|
||||
try:
|
||||
with os.scandir(current) as it:
|
||||
for entry in it:
|
||||
budget -= 1
|
||||
if budget <= 0:
|
||||
return False
|
||||
if entry.is_file():
|
||||
if entry.name.lower().endswith(markers):
|
||||
return True
|
||||
elif depth < max_depth and entry.is_dir(follow_symlinks=False):
|
||||
pending.append((entry.path, depth + 1))
|
||||
except OSError:
|
||||
continue
|
||||
return False
|
||||
|
||||
|
||||
def _is_noise_dir(part: str, parent: "Path | None" = None) -> bool:
|
||||
"""Return True if this directory name looks like a venv, cache, or dep dir."""
|
||||
if part in _SKIP_DIRS:
|
||||
@@ -1170,6 +1252,15 @@ def _is_noise_dir(part: str, parent: "Path | None" = None) -> bool:
|
||||
if parent is None:
|
||||
return False # cannot verify; keep a possibly-real code dir
|
||||
return _has_build_output_markers(parent / part)
|
||||
if part in ("obj", "bin"):
|
||||
# Ambiguous: MSBuild intermediate/output dirs OR real source (Rust's
|
||||
# src/bin/, script dirs). Depths reach a legacy obj/<config>/ and a
|
||||
# RID-specific bin/<config>/<tfm>/<rid>/.
|
||||
if parent is None:
|
||||
return False # cannot verify; keep a possibly-real code dir
|
||||
if part == "obj":
|
||||
return _has_msbuild_markers(parent / part, _MSBUILD_OBJ_MARKERS, 1)
|
||||
return _has_msbuild_markers(parent / part, _MSBUILD_BIN_MARKERS, 3)
|
||||
if part == "snapshots":
|
||||
# Prune only when it looks like an actual JS/Vitest snapshot dir.
|
||||
if parent is None:
|
||||
@@ -1402,6 +1493,51 @@ def _git_info_exclude(vcs_root: Path) -> Path | None:
|
||||
return exclude if exclude.is_file() else None
|
||||
|
||||
|
||||
def _linked_worktree_main_root(directory: Path) -> Path | None:
|
||||
"""Return the main worktree's root for a linked-worktree dir, else None.
|
||||
|
||||
``git worktree add`` gives the linked checkout a ``.git`` FILE reading
|
||||
``gitdir: <main>/.git/worktrees/<name>``, and writes a ``commondir`` file
|
||||
inside that gitdir pointing back at the shared git dir ``<main>/.git`` —
|
||||
so the main checkout's root is the common dir's parent. A submodule's
|
||||
``.git`` file points at ``<super>/.git/modules/<name>``, which carries no
|
||||
``commondir``; a bare repo's shared git dir is not named ``.git`` (it has
|
||||
no main working tree); and a moved/deleted main checkout leaves ``cd``
|
||||
dangling — all three fall through to None and stay scannable (#4683).
|
||||
No git subprocess is used.
|
||||
"""
|
||||
dot_git = directory / ".git"
|
||||
try:
|
||||
if not dot_git.is_file():
|
||||
return None
|
||||
content = dot_git.read_text(encoding="utf-8", errors="ignore").strip()
|
||||
except OSError:
|
||||
return None
|
||||
if not content.startswith("gitdir:"):
|
||||
return None
|
||||
gd = Path(content[len("gitdir:"):].strip())
|
||||
if not gd.is_absolute():
|
||||
try:
|
||||
gd = (directory / gd).resolve()
|
||||
except (OSError, RuntimeError):
|
||||
return None
|
||||
try:
|
||||
cd_raw = (gd / "commondir").read_text(encoding="utf-8", errors="ignore").strip()
|
||||
except OSError:
|
||||
return None
|
||||
if not cd_raw:
|
||||
return None
|
||||
cd = Path(cd_raw)
|
||||
if not cd.is_absolute():
|
||||
try:
|
||||
cd = (gd / cd).resolve()
|
||||
except (OSError, RuntimeError):
|
||||
return None
|
||||
if cd.name != ".git" or not cd.is_dir():
|
||||
return None
|
||||
return cd.parent
|
||||
|
||||
|
||||
def _git_global_excludes(vcs_root: Path) -> Path | None:
|
||||
"""Resolve git's user-wide excludes file (``core.excludesFile``).
|
||||
|
||||
@@ -1884,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.
|
||||
@@ -1904,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
|
||||
@@ -2007,6 +2151,10 @@ def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace:
|
||||
# this bounded — a pruned `data/` is one entry, not one per contained file.
|
||||
ignored: list[str] = []
|
||||
pruned_noise: list[str] = []
|
||||
# JS/TS resolution inputs that _SKIP_FILES keeps out of the corpus. They are
|
||||
# not scan input, but they do steer resolution, so they are reported
|
||||
# separately for the no-change gate to compare (#4740).
|
||||
resolution_inputs: list[str] = []
|
||||
ignore_patterns = _load_graphifyignore(root, gitignore=gitignore)
|
||||
explicit_ignore_patterns = _load_graphifyignore(root, gitignore=False)
|
||||
# See ignored_predicate: skip the `git ls-files` subprocess when .gitignore
|
||||
@@ -2120,6 +2268,16 @@ def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace:
|
||||
# than vanishing silently (#2058).
|
||||
pruned_noise.append(str(child) + os.sep)
|
||||
continue
|
||||
# A linked worktree whose main checkout is also inside the
|
||||
# scan root is a second copy of the same repo — every file
|
||||
# counted twice (#4683). Neither the name-based rules (the
|
||||
# worktree's name is arbitrary) nor info/exclude (the scan
|
||||
# root need not be a repo) reach this sibling layout, but
|
||||
# its .git file + commondir back-pointer identify it.
|
||||
_wt_main = _linked_worktree_main_root(child)
|
||||
if _wt_main is not None and _resolves_under_root(_wt_main, root):
|
||||
pruned_noise.append(str(child) + os.sep)
|
||||
continue
|
||||
# Directory-level pruning: ONE ignore evaluation excludes the
|
||||
# whole subtree — os.walk never descends, so a 29k-file
|
||||
# ignored dir costs one check, not one per contained file.
|
||||
@@ -2139,6 +2297,11 @@ def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace:
|
||||
dirnames[:] = safe_dirs
|
||||
for fname in filenames:
|
||||
if fname in _SKIP_FILES:
|
||||
if is_resolution_input(fname):
|
||||
# Not corpus input, but a JS/TS resolution input: record
|
||||
# it so the no-change gate can compare its content
|
||||
# (#4740). It stays out of the scan exactly as before.
|
||||
resolution_inputs.append(str(dp / fname))
|
||||
continue
|
||||
p = dp / fname
|
||||
if _is_installed_graphify_file(p):
|
||||
@@ -2234,7 +2397,8 @@ def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace:
|
||||
skipped_sensitive.append(str(p) + " [office conversion failed - pip install graphifyy[office]]")
|
||||
continue
|
||||
files[ftype].append(str(p))
|
||||
if ftype != FileType.VIDEO:
|
||||
# Bypass legacy cached counts derived from binary media bytes.
|
||||
if p.suffix.lower() not in _BINARY_MEDIA_EXTENSIONS:
|
||||
total_words += _wc(p)
|
||||
|
||||
for ftype in files:
|
||||
@@ -2257,48 +2421,46 @@ 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,
|
||||
"ignored": sorted(ignored),
|
||||
"pruned_noise_dirs": sorted(pruned_noise),
|
||||
"resolution_inputs": sorted(set(resolution_inputs)),
|
||||
"graphifyignore_patterns": len(ignore_patterns),
|
||||
"scan_root": str(root.resolve()),
|
||||
}
|
||||
|
||||
|
||||
def _os_path(path: Path) -> str:
|
||||
r"""Return an OS path string safe for open()/stat() on Windows long paths.
|
||||
|
||||
On win32, paths longer than the legacy MAX_PATH (260 chars) are rejected by
|
||||
the plain file APIs unless prefixed with the extended-length marker ``\\?\``
|
||||
(which also requires a fully-qualified path). Without it, _md5_file /
|
||||
save_manifest / count_words silently fail to hash deeply-nested files, so
|
||||
their manifest entry never stabilizes and detect_incremental re-flags them
|
||||
as changed on every run (#1655). cache._normalize_path strips this prefix
|
||||
for stable KEYS; this adds it for I/O. Non-win32 and already-prefixed paths
|
||||
pass through unchanged.
|
||||
"""
|
||||
import sys
|
||||
if sys.platform != "win32":
|
||||
return str(path)
|
||||
s = str(path)
|
||||
if s.startswith("\\\\?\\"):
|
||||
return s
|
||||
try:
|
||||
s = os.path.abspath(s) # \\?\ requires a fully-qualified path
|
||||
except Exception:
|
||||
return str(path)
|
||||
if s.startswith("\\\\"):
|
||||
# UNC share \\server\share -> \\?\UNC\server\share
|
||||
return "\\\\?\\UNC\\" + s[2:]
|
||||
return "\\\\?\\" + s
|
||||
# Shared with cache.py (paths.os_long_path); the name stays for detect's callers.
|
||||
_os_path = os_long_path
|
||||
|
||||
|
||||
def _md5_file(path: Path) -> str:
|
||||
@@ -2601,6 +2763,7 @@ def save_manifest(
|
||||
scan_corpus: set[str] | list[str] | None = None,
|
||||
clear_semantic: set[str] | list[str] | None = None,
|
||||
clear_ast: set[str] | list[str] | None = None,
|
||||
ast_empty: set[str] | list[str] | None = None,
|
||||
) -> None:
|
||||
"""Save current file mtimes + content hashes for change detection.
|
||||
|
||||
@@ -2644,6 +2807,12 @@ def save_manifest(
|
||||
``semantic_hash`` on the seeded row so either detect_incremental kind
|
||||
re-queues the file after the failure is fixed, without deleting
|
||||
graphify-out/.
|
||||
|
||||
``ast_empty`` (#2879): code files the AST extractor declined by design this
|
||||
run (data JSON, etc.) — stamped as up-to-date yet contributing zero nodes.
|
||||
Marks their row ``ast_empty: true`` so the #2543 heal can tell an intentional
|
||||
empty from a poisoned stamp and stop re-queuing them. Preserved across
|
||||
incrementals for unchanged rows; dropped once a file starts producing nodes.
|
||||
"""
|
||||
# Another root may have activated different overrides in this thread.
|
||||
if root is not None:
|
||||
@@ -2664,6 +2833,7 @@ def save_manifest(
|
||||
scan_set = _path_index(scan_corpus)
|
||||
clear_set = _path_index(clear_semantic)
|
||||
clear_ast_set = _path_index(clear_ast)
|
||||
ast_empty_set = _path_index(ast_empty)
|
||||
try:
|
||||
root_res: Path | None = Path(root).resolve() if root is not None else None
|
||||
except (OSError, RuntimeError):
|
||||
@@ -2700,6 +2870,17 @@ def save_manifest(
|
||||
except (OSError, RuntimeError):
|
||||
return False
|
||||
|
||||
def _in_ast_empty(path_str: str) -> bool:
|
||||
if ast_empty_set is None:
|
||||
return False
|
||||
if path_str in ast_empty_set or _nfc(path_str) in ast_empty_set:
|
||||
return True
|
||||
try:
|
||||
resolved = str(Path(path_str).resolve())
|
||||
return resolved in ast_empty_set or _nfc(resolved) in ast_empty_set
|
||||
except (OSError, RuntimeError):
|
||||
return False
|
||||
|
||||
def _in_root(path_str: str) -> bool:
|
||||
# Without a root we cannot tell in-root from out-of-root; fail open
|
||||
# (keep the row) so out-of-root corpora are never pruned by accident.
|
||||
@@ -2764,7 +2945,9 @@ def save_manifest(
|
||||
continue # excluded-but-alive: drop the stale row (#1908)
|
||||
if clear_ast_set is not None and _in_clear_ast(f):
|
||||
# AST failure this run (missing extra / zero nodes, #2543): blank
|
||||
# both hashes so either detect_incremental kind re-queues.
|
||||
# both hashes so either detect_incremental kind re-queues. A genuine
|
||||
# failure is not an intentional empty, so drop any stale marker too.
|
||||
normalised = {k: v for k, v in normalised.items() if k != "ast_empty"}
|
||||
normalised = {**normalised, "ast_hash": "", "semantic_hash": ""}
|
||||
elif clear_set is not None and _in_clear(f):
|
||||
# Dispatched-but-omitted this run: don't inherit the stale
|
||||
@@ -2822,6 +3005,13 @@ def save_manifest(
|
||||
if current_lang is not None:
|
||||
# No override keeps legacy rows unchanged.
|
||||
entry["language"] = current_lang
|
||||
# Intentional-empty marker (#2879): set when the extractor declined the
|
||||
# file this run; otherwise inherited across an unchanged incremental the
|
||||
# same way ast_hash is, and dropped once the file produces nodes.
|
||||
if _in_ast_empty(f):
|
||||
entry["ast_empty"] = True
|
||||
elif not lang_changed and prev.get("ast_empty") and ast_h == prev.get("ast_hash", ""):
|
||||
entry["ast_empty"] = True
|
||||
manifest[key] = entry
|
||||
if storage_root is not None:
|
||||
manifest = _collapse_manifest_duplicates(
|
||||
@@ -2867,14 +3057,173 @@ 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(
|
||||
file_buckets: dict[str, list[str]],
|
||||
manifest: dict,
|
||||
*,
|
||||
kind: str = "ast",
|
||||
unstamped_is_changed: bool = True,
|
||||
) -> tuple[dict[str, list[str]], dict[str, list[str]]]:
|
||||
"""Split ``file_buckets`` into (changed, unchanged) against ``manifest``.
|
||||
|
||||
This is the comparison ``detect_incremental`` has always used: mtime first
|
||||
(free, no disk IO beyond stat), content hash only when mtime moved or when
|
||||
the racily-clean window needs it. A missing row, a row with no usable hash,
|
||||
a language change, or an unknown row format all count as changed, so a caller
|
||||
can only ever over-report change.
|
||||
|
||||
Factored out so the ``graphify update`` no-change gate in
|
||||
:func:`graphify.watch._rebuild_code` reaches the same verdict from an
|
||||
already-computed ``detect()`` result instead of paying for a second scan
|
||||
(#4740). ``file_buckets`` is not required to come from ``detect()["files"]``:
|
||||
the gate passes a synthetic bucket holding the JS/TS resolution inputs that
|
||||
the manifest stamps but the scan skips.
|
||||
|
||||
``unstamped_is_changed=False`` is for that gate. A file with no row (or a row
|
||||
whose hash was blanked after a failed extraction, #2543) is then treated as
|
||||
unchanged: it contributed no nodes, so re-extraction cannot change the graph,
|
||||
and only the gate's own file-set digest can tell "same file, still failing"
|
||||
from "new file". The incremental path keeps the default, where such a file is
|
||||
re-queued until it extracts.
|
||||
"""
|
||||
new_files: dict[str, list[str]] = {k: [] for k in file_buckets}
|
||||
unchanged_files: dict[str, list[str]] = {k: [] for k in file_buckets}
|
||||
|
||||
for ftype, file_list in file_buckets.items():
|
||||
for f in file_list:
|
||||
# Manifest keys are NFC; scan paths may arrive NFD (#2221).
|
||||
stored = manifest.get(_nfc(f))
|
||||
try:
|
||||
current_mtime = os.stat(_os_path(Path(f))).st_mtime
|
||||
except Exception:
|
||||
current_mtime = 0
|
||||
|
||||
# Legacy manifest: plain float value stores only mtime.
|
||||
# Compare with `!=` so backwards mtime motion (git checkout of an
|
||||
# older commit, tarball restore, rsync --times) still triggers a
|
||||
# re-extract; the previous `>` silently kept the stale cache and
|
||||
# the graph drifted from disk (#1859). No stored hash means we
|
||||
# cannot verify content — any mtime delta forces a re-extract,
|
||||
# and the next save promotes the entry into the dict schema.
|
||||
# A language change invalidates even identical bytes and legacy rows.
|
||||
stored_lang = stored.get("language") if isinstance(stored, dict) else None
|
||||
if stored is None:
|
||||
changed = unstamped_is_changed
|
||||
elif cache_salt(f) != stored_lang:
|
||||
changed = True
|
||||
elif isinstance(stored, (int, float)):
|
||||
changed = current_mtime != stored
|
||||
elif isinstance(stored, dict):
|
||||
# Normalise legacy {mtime, hash} to new schema
|
||||
if "hash" in stored and "ast_hash" not in stored:
|
||||
stored = {"mtime": stored.get("mtime", 0), "ast_hash": stored["hash"], "semantic_hash": ""}
|
||||
hash_key = "semantic_hash" if kind == "semantic" else "ast_hash"
|
||||
stored_hash = stored.get(hash_key, "")
|
||||
# Missing semantic_hash means update ran but extract hasn't — always re-extract
|
||||
if not stored_hash:
|
||||
changed = unstamped_is_changed
|
||||
else:
|
||||
stored_mtime = stored.get("mtime")
|
||||
# Schema-drift guard (#1163): tolerate a nested {mtime: ...}
|
||||
# dict or any non-numeric value without crashing.
|
||||
if isinstance(stored_mtime, dict):
|
||||
stored_mtime = stored_mtime.get("mtime")
|
||||
if not isinstance(stored_mtime, (int, float)):
|
||||
stored_mtime = None
|
||||
if stored_mtime is None or current_mtime != stored_mtime:
|
||||
# mtime bumped — verify with content hash before re-extracting
|
||||
changed = _md5_file(Path(f)) != stored_hash
|
||||
elif _mtime_may_hide_a_rewrite(current_mtime, stored):
|
||||
# mtime is unchanged, but it was recorded in the same
|
||||
# filesystem tick the file was written in — a later
|
||||
# same-length edit lands in that tick without moving
|
||||
# mtime, and the file silently skips re-extraction
|
||||
# while the graph keeps serving the old content.
|
||||
# Only this narrow window pays for a content hash.
|
||||
changed = _md5_file(Path(f)) != stored_hash
|
||||
else:
|
||||
changed = False
|
||||
else:
|
||||
changed = True # unknown format, re-extract to be safe
|
||||
|
||||
if changed:
|
||||
new_files[ftype].append(f)
|
||||
else:
|
||||
unchanged_files[ftype].append(f)
|
||||
|
||||
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,
|
||||
@@ -2938,108 +3287,27 @@ def detect_incremental(
|
||||
full["excluded_files"] = []
|
||||
return full
|
||||
|
||||
new_files: dict[str, list[str]] = {k: [] for k in full["files"]}
|
||||
unchanged_files: dict[str, list[str]] = {k: [] for k in full["files"]}
|
||||
|
||||
for ftype, file_list in full["files"].items():
|
||||
for f in file_list:
|
||||
# Manifest keys are NFC; scan paths may arrive NFD (#2221).
|
||||
stored = manifest.get(_nfc(f))
|
||||
try:
|
||||
current_mtime = os.stat(_os_path(Path(f))).st_mtime
|
||||
except Exception:
|
||||
current_mtime = 0
|
||||
|
||||
# Legacy manifest: plain float value stores only mtime.
|
||||
# Compare with `!=` so backwards mtime motion (git checkout of an
|
||||
# older commit, tarball restore, rsync --times) still triggers a
|
||||
# re-extract; the previous `>` silently kept the stale cache and
|
||||
# the graph drifted from disk (#1859). No stored hash means we
|
||||
# cannot verify content — any mtime delta forces a re-extract,
|
||||
# and the next save promotes the entry into the dict schema.
|
||||
# A language change invalidates even identical bytes and legacy rows.
|
||||
stored_lang = stored.get("language") if isinstance(stored, dict) else None
|
||||
if stored is not None and cache_salt(f) != stored_lang:
|
||||
changed = True
|
||||
elif isinstance(stored, (int, float)):
|
||||
changed = current_mtime != stored
|
||||
elif isinstance(stored, dict):
|
||||
# Normalise legacy {mtime, hash} to new schema
|
||||
if "hash" in stored and "ast_hash" not in stored:
|
||||
stored = {"mtime": stored.get("mtime", 0), "ast_hash": stored["hash"], "semantic_hash": ""}
|
||||
hash_key = "semantic_hash" if kind == "semantic" else "ast_hash"
|
||||
stored_hash = stored.get(hash_key, "")
|
||||
# Missing semantic_hash means update ran but extract hasn't — always re-extract
|
||||
if not stored_hash:
|
||||
changed = True
|
||||
else:
|
||||
stored_mtime = stored.get("mtime")
|
||||
# Schema-drift guard (#1163): tolerate a nested {mtime: ...}
|
||||
# dict or any non-numeric value without crashing.
|
||||
if isinstance(stored_mtime, dict):
|
||||
stored_mtime = stored_mtime.get("mtime")
|
||||
if not isinstance(stored_mtime, (int, float)):
|
||||
stored_mtime = None
|
||||
if stored_mtime is None or current_mtime != stored_mtime:
|
||||
# mtime bumped — verify with content hash before re-extracting
|
||||
changed = _md5_file(Path(f)) != stored_hash
|
||||
elif _mtime_may_hide_a_rewrite(current_mtime, stored):
|
||||
# mtime is unchanged, but it was recorded in the same
|
||||
# filesystem tick the file was written in — a later
|
||||
# same-length edit lands in that tick without moving
|
||||
# mtime, and the file silently skips re-extraction
|
||||
# while the graph keeps serving the old content.
|
||||
# Only this narrow window pays for a content hash.
|
||||
changed = _md5_file(Path(f)) != stored_hash
|
||||
else:
|
||||
changed = False
|
||||
else:
|
||||
changed = True # unknown format, re-extract to be safe
|
||||
|
||||
if changed:
|
||||
new_files[ftype].append(f)
|
||||
else:
|
||||
unchanged_files[ftype].append(f)
|
||||
new_files, unchanged_files = classify_manifest_files(full["files"], manifest, kind=kind)
|
||||
|
||||
# Manifest rows that left the corpus, split by disk existence (#1908):
|
||||
# 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 (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}
|
||||
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
|
||||
|
||||
+82
-25
@@ -15,7 +15,7 @@ import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
from graphify.security import sanitize_label
|
||||
from graphify.analyze import _node_community_map
|
||||
from graphify.build import edge_data, has_parallel_links
|
||||
from graphify.build import edge_datas, has_parallel_links
|
||||
from graphify.paths import (
|
||||
os_replace_with_fallback,
|
||||
stem_filename_budget,
|
||||
@@ -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,12 +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)
|
||||
]
|
||||
missing = _lost_saved_semantic_nodes(existing_nodes, new_node_list, set())
|
||||
folded: dict[str, str] = {}
|
||||
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)
|
||||
@@ -350,7 +378,17 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
|
||||
file=_sys.stderr,
|
||||
)
|
||||
return False
|
||||
if new_n < existing_n:
|
||||
# A saved semantic node merged into an AST twin that was already
|
||||
# saved is one node, not two; a reload-and-recluster folds it (#4389).
|
||||
# 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(
|
||||
f"[graphify] WARNING: new graph has {new_n} nodes but existing "
|
||||
@@ -363,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()}
|
||||
@@ -436,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", {}):
|
||||
@@ -458,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:
|
||||
@@ -558,7 +606,7 @@ def to_cypher(G: nx.Graph, output_path: str) -> None:
|
||||
(data.get("file_type", "unknown") or "unknown").capitalize(),
|
||||
"Entity",
|
||||
)
|
||||
lines.append(f"MERGE (n:{ftype} {{id: '{node_id_esc}', label: '{label}'}});")
|
||||
lines.append(f"MERGE (n:{ftype} {{id: '{node_id_esc}'}}) SET n.label = '{label}';")
|
||||
lines.append("")
|
||||
for u, v, data in G.edges(data=True):
|
||||
u, v = data.get("_src", u), data.get("_tgt", v)
|
||||
@@ -859,9 +907,9 @@ def to_obsidian(
|
||||
|
||||
# Build tags for this node
|
||||
ftype = data.get("file_type", "")
|
||||
ftype_tag = _FTYPE_TAG.get(ftype, f"graphify/{ftype}" if ftype else "graphify/document")
|
||||
ftype_tag = _FTYPE_TAG.get(ftype, f"graphify/{_obsidian_tag(ftype)}" if ftype else "graphify/document")
|
||||
dom_conf = _dominant_confidence(node_id)
|
||||
conf_tag = f"graphify/{dom_conf}"
|
||||
conf_tag = f"graphify/{_obsidian_tag(dom_conf)}"
|
||||
comm_tag = f"community/{_obsidian_tag(community_name)}"
|
||||
node_tags = [ftype_tag, conf_tag, comm_tag]
|
||||
|
||||
@@ -889,11 +937,20 @@ def to_obsidian(
|
||||
if neighbors:
|
||||
lines.append("## Connections")
|
||||
for neighbor in sorted(neighbors, key=lambda n: G.nodes[n].get("label", n)):
|
||||
edata = edge_data(G, node_id, neighbor)
|
||||
neighbor_label = node_filename[neighbor]
|
||||
relation = edata.get("relation", "")
|
||||
confidence = edata.get("confidence", "EXTRACTED")
|
||||
lines.append(f"- [[{neighbor_label}]] - `{relation}` [{confidence}]")
|
||||
# One bullet per parallel edge, not per neighbour: graph.json is
|
||||
# reloaded as a MultiGraph when it carries parallel edges
|
||||
# (#4500), and `edge_data()` returns only the FIRST of them — so
|
||||
# a pair joined by both `imports` and `calls` lost one relation
|
||||
# from the note. Sorted so the note is byte-stable regardless of
|
||||
# the order the parallel edges were inserted in.
|
||||
for edata in sorted(
|
||||
edge_datas(G, node_id, neighbor),
|
||||
key=lambda d: (str(d.get("relation", "")), str(d.get("confidence", "EXTRACTED"))),
|
||||
):
|
||||
relation = edata.get("relation", "")
|
||||
confidence = edata.get("confidence", "EXTRACTED")
|
||||
lines.append(f"- [[{neighbor_label}]] - `{relation}` [{confidence}]")
|
||||
lines.append("")
|
||||
|
||||
# Inline tags at bottom of note body (for Obsidian tag panel)
|
||||
|
||||
+2110
-117
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)
|
||||
|
||||
@@ -54,11 +54,24 @@ def extract_blade(path: Path) -> dict:
|
||||
"confidence": "EXTRACTED", "confidence_score": 1.0,
|
||||
"source_file": str(path), "source_location": None, "weight": 1.0})
|
||||
|
||||
# wire:click="methodName"
|
||||
for m in re.finditer(r'wire:click=["\']([^"\']+)["\']', src):
|
||||
tgt_nid = _make_id(m.group(1))
|
||||
# wire:click="methodName" or wire:click="methodName(arg)", with an optional
|
||||
# Livewire event modifier (wire:click.prevent=, wire:click.stop=) the bare
|
||||
# `wire:click=` pattern never matched at all. A call's own arguments are not
|
||||
# part of the method's name and must not end up in the bound id; a magic
|
||||
# action ($set, $emit, $toggle, $refresh, ...) is Livewire's own runtime
|
||||
# behavior, not a method the component defines, so it is left unbound rather
|
||||
# than fabricating an edge to something that does not exist.
|
||||
for m in re.finditer(r'wire:click(?:\.\w+)*=["\']([^"\']+)["\']', src):
|
||||
raw = m.group(1).strip()
|
||||
if raw.startswith("$"):
|
||||
continue
|
||||
name_match = re.match(r"[A-Za-z_]\w*", raw)
|
||||
if not name_match:
|
||||
continue
|
||||
method_name = name_match.group(0)
|
||||
tgt_nid = _make_id(method_name)
|
||||
if tgt_nid not in {n["id"] for n in nodes}:
|
||||
nodes.append({"id": tgt_nid, "label": m.group(1), "file_type": "code",
|
||||
nodes.append({"id": tgt_nid, "label": method_name, "file_type": "code",
|
||||
"source_file": str(path), "source_location": None})
|
||||
edges.append({"source": file_nid, "target": tgt_nid, "relation": "binds_method",
|
||||
"confidence": "EXTRACTED", "confidence_score": 1.0,
|
||||
|
||||
@@ -22,6 +22,7 @@ _COPY = re.compile(
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_CALL = re.compile(r"\bCALL\s+(['\"])([A-Z0-9-]+)\1", re.IGNORECASE)
|
||||
_END_PROGRAM = re.compile(r"\bEND\s+PROGRAM\b", re.IGNORECASE)
|
||||
_DATA_ITEM = re.compile(
|
||||
rf"^\s*(?:0[1-9]|[1-4][0-9]|66|77|88)\s+({_NAME})\b", re.IGNORECASE
|
||||
)
|
||||
@@ -169,6 +170,14 @@ def extract_cobol(path: Path) -> dict:
|
||||
in_exec = False
|
||||
paragraphs: dict[tuple[str, str], str] = {}
|
||||
pending_performs: list[tuple[str, str, str, int]] = []
|
||||
# A nested (contained) program's PROGRAM-ID switches current_program with
|
||||
# no record of what it switched FROM; everything after its own END
|
||||
# PROGRAM, including code physically back in the enclosing program, kept
|
||||
# attributing to the nested one forever. Each PROGRAM-ID pushes the
|
||||
# program it is nested under (possibly file_id, for a top-level one), and
|
||||
# END PROGRAM pops back to it, so sibling and nested programs alike
|
||||
# restore the right scope once their own body ends.
|
||||
program_stack: list[str] = []
|
||||
|
||||
for line, code in code_lines:
|
||||
upper = code.upper().strip()
|
||||
@@ -182,9 +191,17 @@ def extract_cobol(path: Path) -> dict:
|
||||
in_exec = True
|
||||
continue
|
||||
|
||||
if _END_PROGRAM.search(upper):
|
||||
if program_stack:
|
||||
current_program = program_stack.pop()
|
||||
current_scope = current_program
|
||||
in_procedure = True
|
||||
continue
|
||||
|
||||
program_match = _PROGRAM.search(upper)
|
||||
if program_match:
|
||||
name = program_match.group(1).upper()
|
||||
program_stack.append(current_program)
|
||||
current_program = add_node(
|
||||
_make_id(file_id, "program", name.casefold()),
|
||||
name,
|
||||
|
||||
@@ -5,6 +5,7 @@ import warnings
|
||||
from pathlib import Path
|
||||
|
||||
from graphify.extractors.base import _file_stem, _make_id, _read_source_bytes
|
||||
from graphify.security import redact_secrets
|
||||
|
||||
|
||||
# Standard CL definer forms that introduce data/type/variable bindings
|
||||
@@ -166,9 +167,16 @@ def extract_commonlisp(path: Path) -> dict:
|
||||
rewire can collapse it onto the real `defclass` in another file. Without
|
||||
this, a cross-file superclass had no matching node and its `inherits`
|
||||
edge was pruned by the dangling-edge filter — silently erasing every
|
||||
inheritance edge whose parent lives in a different file."""
|
||||
inheritance edge whose parent lives in a different file.
|
||||
|
||||
`local` is checked against `local_class_names` (every class this file
|
||||
defines, gathered up front), not just `seen_ids`: forms are walked in
|
||||
file order, so a class referenced before its own `defclass` form is
|
||||
processed — e.g. a subclass listed above its parent — would otherwise
|
||||
still be in `seen_ids` as absent, and this would wrongly mint an
|
||||
external stub for a class that is right here in the same file."""
|
||||
local = _cl_id(stem, name)
|
||||
if local in seen_ids:
|
||||
if local in seen_ids or name in local_class_names:
|
||||
return local
|
||||
stub = _cl_id(name)
|
||||
if stub not in seen_ids:
|
||||
@@ -330,7 +338,7 @@ def extract_commonlisp(path: Path) -> dict:
|
||||
doc_text = _text(child).strip('"')
|
||||
if doc_text:
|
||||
doc_nid = _cl_id(func_nid, "rationale")
|
||||
add_node(doc_nid, doc_text[:120], child.start_point[0] + 1, file_type="rationale")
|
||||
add_node(doc_nid, redact_secrets(doc_text)[:120], child.start_point[0] + 1, file_type="rationale")
|
||||
add_edge(doc_nid, func_nid, "rationale_for",
|
||||
child.start_point[0] + 1)
|
||||
break
|
||||
@@ -420,7 +428,7 @@ def extract_commonlisp(path: Path) -> dict:
|
||||
doc_text = _text(child).strip('"')
|
||||
if doc_text:
|
||||
doc_nid = _cl_id(nid, "rationale")
|
||||
add_node(doc_nid, doc_text[:120], child.start_point[0] + 1, file_type="rationale")
|
||||
add_node(doc_nid, redact_secrets(doc_text)[:120], child.start_point[0] + 1, file_type="rationale")
|
||||
add_edge(doc_nid, nid, "rationale_for",
|
||||
child.start_point[0] + 1)
|
||||
break
|
||||
@@ -504,6 +512,40 @@ def extract_commonlisp(path: Path) -> dict:
|
||||
elif top.type == "include_reader_macro":
|
||||
_walk_forms(top)
|
||||
|
||||
def _prescan_class_names(parent) -> set[str]:
|
||||
"""Collect every name this file defines via `defclass`, regardless of
|
||||
where in the file the definition sits, so `ensure_class_ref` can tell
|
||||
a forward-referenced same-file class apart from a genuinely external
|
||||
one before `_walk_forms` reaches the defining form. Mirrors
|
||||
`_walk_forms`'s own recursion rule (stop at a recognized top-level
|
||||
form, descend into anything else) so it finds a `defclass` nested in
|
||||
a wrapper macro the same way the real walk later will."""
|
||||
names: set[str] = set()
|
||||
for top in parent.children:
|
||||
if top.type == "list_lit":
|
||||
first = _first_sym(top)
|
||||
first_lower = (first or "").lower()
|
||||
if first_lower == "defclass":
|
||||
# Mirror _handle_defclass's own name extraction exactly
|
||||
# (direct-child sym_lits, second one is the name) so a
|
||||
# form _handle_defclass would itself skip — e.g. a
|
||||
# list-style name — isn't prescanned as a local class.
|
||||
sym_lits = [c for c in top.children if c.type == "sym_lit"]
|
||||
if len(sym_lits) >= 2:
|
||||
names.add(_text(sym_lits[1]))
|
||||
elif not first or (
|
||||
first_lower not in ("defpackage", "in-package", "require", "ql:quickload")
|
||||
and first_lower not in _CL_DATA_DEFINERS
|
||||
and first_lower not in _CL_MACRO_DEFINERS
|
||||
and not _is_def_prefixed(first_lower)
|
||||
):
|
||||
names |= _prescan_class_names(top)
|
||||
elif top.type == "include_reader_macro":
|
||||
names |= _prescan_class_names(top)
|
||||
return names
|
||||
|
||||
local_class_names = _prescan_class_names(root)
|
||||
|
||||
_walk_forms(root)
|
||||
|
||||
# Call extraction pass
|
||||
|
||||
@@ -11,12 +11,28 @@ the core migration happens.
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
from collections.abc import Iterable
|
||||
from pathlib import Path
|
||||
|
||||
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,
|
||||
@@ -187,6 +203,92 @@ def _metadata(value: object) -> dict:
|
||||
return value if isinstance(value, dict) else {}
|
||||
|
||||
|
||||
def _is_plain_csharp_name(text: str) -> bool:
|
||||
return bool(text) and not any(ch in text for ch in ".()") and not any(
|
||||
ch.isspace() for ch in text
|
||||
)
|
||||
|
||||
|
||||
def bare_csharp_method_label(label: object, source_file: object) -> str | None:
|
||||
"""Return the ``.Name()`` resolver form of a C# method label, else ``None``.
|
||||
|
||||
Accepts both the extractor's bare ``.Name()`` and the owner-qualified
|
||||
``Owner.Name()`` display form the graph build assigns (#4883). Extraction
|
||||
emits, and call resolution, interface dispatch, and the method-ghost index
|
||||
match on, the bare form, so anything reading labels back from a persisted
|
||||
graph normalizes through here. C# method and type names never contain a
|
||||
dot (an explicit interface implementation is still labeled ``.Build()``),
|
||||
so the split is unambiguous.
|
||||
"""
|
||||
if not _is_cs_file(source_file) or not isinstance(label, str):
|
||||
return None
|
||||
if not label.endswith("()"):
|
||||
return None
|
||||
owner, dot, name = label[:-2].rpartition(".")
|
||||
if not dot or not _is_plain_csharp_name(name):
|
||||
return None
|
||||
if owner and not _is_plain_csharp_name(owner):
|
||||
return None
|
||||
return f".{name}()"
|
||||
|
||||
|
||||
def bare_csharp_method_labels_in_nodes(nodes: list[dict]) -> list[dict]:
|
||||
"""Copy of *nodes* with owner-qualified C# method labels reverted to ``.Name()``.
|
||||
|
||||
Nodes that need no change are returned as-is; changed nodes are shallow
|
||||
copies, so the caller's list and dicts are never mutated.
|
||||
"""
|
||||
out: list[dict] = []
|
||||
for node in nodes:
|
||||
label = node.get("label")
|
||||
bare = bare_csharp_method_label(label, node.get("source_file"))
|
||||
out.append(node if bare is None or bare == label else {**node, "label": bare})
|
||||
return out
|
||||
|
||||
|
||||
def csharp_method_label_reassignments(
|
||||
nodes: Iterable[tuple[object, dict]],
|
||||
method_edges: Iterable[tuple[object, object]],
|
||||
) -> dict[str, str]:
|
||||
"""Return ``{method_id: "Owner.Name()"}`` display labels for C# methods (#4883).
|
||||
|
||||
*nodes* are ``(id, attrs)`` pairs and *method_edges* are ``(owner_id,
|
||||
method_id)`` pairs from ``method`` edges. A method with zero or several
|
||||
distinct owner labels, or an owner whose label is not a plain type name,
|
||||
is omitted and keeps its bare ``.Name()`` label. Derived from the bare form,
|
||||
so applying it to already-qualified labels is a no-op.
|
||||
"""
|
||||
owner_label_by_id: dict[str, str] = {}
|
||||
bare_by_id: dict[str, str] = {}
|
||||
for nid, attrs in nodes:
|
||||
if not isinstance(nid, str) or not isinstance(attrs, dict):
|
||||
continue
|
||||
label = attrs.get("label")
|
||||
source_file = attrs.get("source_file")
|
||||
if not isinstance(label, str) or not _is_cs_file(source_file):
|
||||
continue
|
||||
if _is_plain_csharp_name(label):
|
||||
owner_label_by_id[nid] = label
|
||||
continue
|
||||
bare = bare_csharp_method_label(label, source_file)
|
||||
if bare is not None:
|
||||
bare_by_id[nid] = bare
|
||||
|
||||
owner_labels_by_method: dict[str, set[str | None]] = {}
|
||||
for owner, method in method_edges:
|
||||
if isinstance(owner, str) and isinstance(method, str) and method in bare_by_id:
|
||||
owner_labels_by_method.setdefault(method, set()).add(owner_label_by_id.get(owner))
|
||||
|
||||
out: dict[str, str] = {}
|
||||
for method, owner_labels in owner_labels_by_method.items():
|
||||
if len(owner_labels) != 1:
|
||||
continue
|
||||
owner_label = next(iter(owner_labels))
|
||||
if owner_label is not None:
|
||||
out[method] = f"{owner_label}{bare_by_id[method]}"
|
||||
return out
|
||||
|
||||
|
||||
class CsharpNameResolver:
|
||||
"""Namespace/using/alias-aware C# simple-name resolution.
|
||||
|
||||
@@ -320,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, []):
|
||||
|
||||
+45
-29
@@ -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)
|
||||
@@ -428,8 +438,14 @@ def extract_dart(path: Path) -> dict:
|
||||
add_node(target_nid, target_type, source_file=None)
|
||||
add_edge(typedef_nid, target_nid, "references", context="typedef", line=typedef_line)
|
||||
|
||||
# 3. Extensions (extension MyExt on MyClass)
|
||||
ext_pattern = r"^\s{0,4}extension\s+(\w+)?(?:<[^>]+>)?\s+on\s+(\w+)"
|
||||
# 3. Extensions (extension MyExt on MyClass, or the anonymous `extension on
|
||||
# MyClass` form). The name and its generics sit in one optional group,
|
||||
# together with the whitespace that follows them: splitting that
|
||||
# whitespace into two separate `\s+` runs (one before the name, one
|
||||
# before `on`) makes both demand at least one space of their own, which
|
||||
# a single space between `extension` and `on` can never satisfy when the
|
||||
# name is absent, so the anonymous form never matched at all.
|
||||
ext_pattern = r"^\s{0,4}extension\s+(?:(\w+)\s*(?:<[^>]+>)?\s+)?on\s+(\w+)"
|
||||
for m in re.finditer(ext_pattern, src_clean, re.MULTILINE):
|
||||
ext_name = m.group(1) or f"{stem}_anonymous_extension"
|
||||
target_class = m.group(2)
|
||||
|
||||
@@ -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:
|
||||
|
||||
+1437
-94
File diff suppressed because it is too large.
Load diff
@@ -237,14 +237,23 @@ def extract_fortran(path: Path) -> dict:
|
||||
t = node.type
|
||||
if t in ("subroutine", "function", "module", "program", "internal_procedures"):
|
||||
return
|
||||
# call FOO(args) — tree-sitter-fortran uses subroutine_call
|
||||
# call FOO(args) — tree-sitter-fortran uses subroutine_call. Unlike
|
||||
# call_expression below, `call` is unambiguous: there is no array-index
|
||||
# reading, so a callee defined in another file (reached through its own
|
||||
# `use` statement) is resolved the same way a cross-file parameter/return
|
||||
# type already is, through a sourceless stub the corpus rewire can
|
||||
# collapse onto the real definition. Computing the target id directly
|
||||
# (the previous behaviour) always salted it with THIS file's own stem,
|
||||
# so a cross-file call target never matched the callee's real node and
|
||||
# dangled permanently.
|
||||
if t == "subroutine_call":
|
||||
name_node = next((c for c in node.children if c.type == "identifier"), None)
|
||||
if name_node:
|
||||
callee = _read_text(name_node, source).lower()
|
||||
target_nid = _make_id(stem, callee)
|
||||
add_edge(scope_nid, target_nid, "calls", node.start_point[0] + 1,
|
||||
confidence="EXTRACTED", context="call")
|
||||
target_nid = ensure_named_node(callee, node.start_point[0] + 1)
|
||||
if target_nid != scope_nid:
|
||||
add_edge(scope_nid, target_nid, "calls", node.start_point[0] + 1,
|
||||
confidence="EXTRACTED", context="call")
|
||||
# x = compute(args) — function invocations are `call_expression`, which
|
||||
# shares Fortran's `name(...)` syntax with array indexing. Only emit a
|
||||
# call edge when the callee resolves to a procedure defined in this file
|
||||
@@ -305,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
|
||||
|
||||
+321
-58
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
from graphify.ids import DeclIdRegistry
|
||||
from graphify.extractors.base import (
|
||||
_LANGUAGE_BUILTIN_GLOBALS,
|
||||
_file_stem,
|
||||
@@ -11,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({
|
||||
@@ -48,6 +50,28 @@ _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
|
||||
name, so it gets no node: references to `A` keep resolving to the original
|
||||
instead of tying between the two. Any other alias introduces a name."""
|
||||
target = alias_node.child_by_field_name("type")
|
||||
if target is not None and target.type == "generic_type":
|
||||
target = target.child_by_field_name("type")
|
||||
if target is None or target.type != "qualified_type":
|
||||
return False
|
||||
name, target_name = alias_node.child_by_field_name("name"), target.child_by_field_name("name")
|
||||
return (name is not None and target_name is not None
|
||||
and _read_text(name, source) == _read_text(target_name, source))
|
||||
|
||||
|
||||
def _go_type_param_names(decl_node, source: bytes) -> frozenset[str]:
|
||||
"""Names bound by a declaration's generic type parameters.
|
||||
|
||||
@@ -152,55 +176,135 @@ 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)
|
||||
return name if name and name not in _GO_PREDECLARED_TYPES else None
|
||||
|
||||
|
||||
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_inferred_composite_bindings(names, values, source: bytes):
|
||||
"""Pair same-position declared names with composite-literal values.
|
||||
|
||||
Four sources: a struct field, a parameter (which covers the method receiver
|
||||
`func (s *Server)`), `var x T`, and `x := T{}` / `x := &T{}`. 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.
|
||||
Shared by `x := T{}` (`short_var_declaration`) and `var x = T{}` (a
|
||||
type-less `var_spec`): both bind a name to the type of a same-position
|
||||
`T{}` / `&T{}` value. Yields (name text, inferred type) for each pair
|
||||
that is in fact a composite literal.
|
||||
"""
|
||||
table: dict[str, str] = {}
|
||||
for name_node, value in zip(names, values):
|
||||
if value.type == "unary_expression":
|
||||
value = value.child_by_field_name("operand") or value
|
||||
if value.type != "composite_literal":
|
||||
continue
|
||||
type_name = _go_single_type_name(value.child_by_field_name("type"), source)
|
||||
if type_name:
|
||||
yield _read_text(name_node, source), type_name
|
||||
|
||||
|
||||
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.
|
||||
|
||||
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 | 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)
|
||||
for c in n.children if type_name else ():
|
||||
if c.type in ("field_identifier", "identifier"):
|
||||
table.setdefault(_read_text(c, source), type_name)
|
||||
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:
|
||||
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_node, value in zip(names, values):
|
||||
if value.type == "unary_expression":
|
||||
value = value.child_by_field_name("operand") or value
|
||||
if value.type != "composite_literal":
|
||||
continue
|
||||
type_name = _go_single_type_name(
|
||||
value.child_by_field_name("type"), source)
|
||||
if type_name:
|
||||
table.setdefault(_read_text(name_node, source), type_name)
|
||||
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:
|
||||
@@ -226,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] = {}
|
||||
|
||||
@@ -267,6 +373,7 @@ def extract_go(path: Path) -> dict:
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
add_node(file_nid, path.name, 1)
|
||||
decl_registry = DeclIdRegistry(reserved_ids=(file_nid,))
|
||||
|
||||
def ensure_named_node(name: str, line: int) -> str:
|
||||
nid = type_symbol_nid(name)
|
||||
@@ -340,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
|
||||
@@ -393,8 +527,11 @@ def extract_go(path: Path) -> dict:
|
||||
|
||||
def _scan_type_names(node) -> None:
|
||||
# Types first: a method is keyed under its owner's final id, which is
|
||||
# salted when the owner's own name collides.
|
||||
if node.type == "type_spec":
|
||||
# salted when the owner's own name collides. An alias (`type A = B`) is a
|
||||
# `type_alias`, not a `type_spec`, and declares a type name all the same.
|
||||
if node.type == "type_spec" or (
|
||||
node.type == "type_alias" and not _go_alias_re_exports(node, source)
|
||||
):
|
||||
name_node = node.child_by_field_name("name")
|
||||
if name_node is not None:
|
||||
name = _read_text(name_node, source)
|
||||
@@ -428,21 +565,20 @@ def extract_go(path: Path) -> dict:
|
||||
for child in node.children:
|
||||
_scan_declarations(child)
|
||||
|
||||
def symbol_nid(plain_nid: str, name: str) -> str:
|
||||
def symbol_nid(plain_nid: str, name: str, kind: str = "fn") -> str:
|
||||
nid = plain_nid
|
||||
names = case_groups.get(plain_nid) or set()
|
||||
if len(names) < 2:
|
||||
return plain_nid
|
||||
exported = [n for n in names if n[:1].isupper()]
|
||||
if len(exported) == 1 and name == exported[0]:
|
||||
return plain_nid
|
||||
salt = hashlib.sha1(name.encode("utf-8"), usedforsecurity=False).hexdigest()[:6]
|
||||
return _make_id(plain_nid, salt)
|
||||
if len(names) >= 2 and not (len([n for n in names if n[:1].isupper()]) == 1
|
||||
and name == [n for n in names if n[:1].isupper()][0]):
|
||||
salt = hashlib.sha1(name.encode("utf-8"), usedforsecurity=False).hexdigest()[:6]
|
||||
nid = _make_id(plain_nid, salt)
|
||||
return decl_registry.resolve(nid, name, kind, seen_ids)
|
||||
|
||||
def type_symbol_nid(name: str) -> str:
|
||||
plain_nid = _make_id(pkg_scope, name)
|
||||
if name not in case_groups.get(plain_nid, ()):
|
||||
return plain_nid
|
||||
return symbol_nid(plain_nid, name)
|
||||
return decl_registry.resolve(plain_nid, name, "type", seen_ids)
|
||||
return symbol_nid(plain_nid, name, "type")
|
||||
|
||||
def walk(node) -> None:
|
||||
t = node.type
|
||||
@@ -509,7 +645,9 @@ def extract_go(path: Path) -> dict:
|
||||
|
||||
if t == "type_declaration":
|
||||
for child in node.children:
|
||||
if child.type != "type_spec":
|
||||
if child.type not in ("type_spec", "type_alias"):
|
||||
continue
|
||||
if child.type == "type_alias" and _go_alias_re_exports(child, source):
|
||||
continue
|
||||
name_node = child.child_by_field_name("name")
|
||||
if not name_node:
|
||||
@@ -520,6 +658,11 @@ def extract_go(path: Path) -> dict:
|
||||
add_node(type_nid, type_name, line)
|
||||
callable_class_nids.add(type_nid)
|
||||
add_edge(file_nid, type_nid, "contains", line)
|
||||
if child.type == "type_alias":
|
||||
# `type A = B` is a declaration like `type A B`: references to
|
||||
# it land here instead of minting a sourceless stub. Its
|
||||
# right-hand side is not walked.
|
||||
continue
|
||||
# A generic type's own parameters (`type Box[T any]`) are local
|
||||
# bindings; a field or method using `T` must not mint a stub.
|
||||
type_params = _go_type_param_names(child, source)
|
||||
@@ -561,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
|
||||
@@ -615,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":
|
||||
@@ -652,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"]
|
||||
@@ -671,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
|
||||
@@ -682,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":
|
||||
@@ -699,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:
|
||||
@@ -721,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:
|
||||
@@ -750,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)
|
||||
@@ -776,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},
|
||||
}
|
||||
@@ -234,7 +234,7 @@ def extract_json(path: Path) -> dict:
|
||||
if ref_nid:
|
||||
add_edge(parent_nid, ref_nid, "references", line)
|
||||
|
||||
elif parent_key in _DEP_KEYS and val_text:
|
||||
elif parent_key in _DEP_KEYS and val_text.strip():
|
||||
# Two defects fixed here, both from the #1764 shape:
|
||||
#
|
||||
# 1. The edge ran `key_nid -> dep_nid`, and both nodes carry
|
||||
@@ -253,10 +253,34 @@ def extract_json(path: Path) -> dict:
|
||||
# `types` could then be collapsed onto a same-named local
|
||||
# module by build.py's alias index -- the #1638 failure
|
||||
# mode reached through a different door.
|
||||
#
|
||||
# 3. Moving that edge to the manifest also cut the only link between the
|
||||
# dependency's key node (its manifest entry, reached through
|
||||
# `dependencies --contains-->`) and its ref node, so the entry and
|
||||
# the code that imports the package landed in different communities
|
||||
# (#4569). `key_nid --declares--> dep_nid` reconnects them, and the
|
||||
# entry is relabelled `name@range` so the two nodes no longer share a
|
||||
# label: a same-label edge is the `react -> react` view #1764
|
||||
# removed, and two `react` nodes made `explain`/`affected`
|
||||
# ambiguous. The ref node keeps the bare name, which is what
|
||||
# `import "react"` resolves to. The range is one line, capped at 40
|
||||
# characters; a blank one links nothing (like an empty one) and the
|
||||
# entry keeps its bare name.
|
||||
dep_nid = _make_id("ref", key)
|
||||
if dep_nid:
|
||||
add_node(dep_nid, key, line, file_type="concept")
|
||||
add_edge(file_nid, dep_nid, "imports", line, context="import")
|
||||
add_edge(key_nid, dep_nid, "declares", line)
|
||||
version = " ".join(val_text.split())
|
||||
if len(version) > 40:
|
||||
version = version[:37] + "..."
|
||||
# `add_node` kept the first node under this id (the same key under
|
||||
# two sibling blocks shares it), so relabel only the pair that
|
||||
# node's line belongs to: label and line then name one entry.
|
||||
for node in nodes:
|
||||
if node["id"] == key_nid and node["source_location"] == f"L{line}":
|
||||
node["label"] = f"{key}@{version}"
|
||||
break
|
||||
|
||||
# Entry: find root document → object
|
||||
doc = root
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""julia — moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
from graphify.ids import DeclIdRegistry
|
||||
from graphify.extractors.base import _file_stem, _make_id, _read_source_bytes, _read_text
|
||||
from graphify.extractors.engine import _semantic_reference_edge
|
||||
from pathlib import Path
|
||||
@@ -59,6 +60,10 @@ def extract_julia(path: Path) -> dict:
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
add_node(file_nid, path.name, 1)
|
||||
decl_registry = DeclIdRegistry(reserved_ids=(file_nid,))
|
||||
|
||||
def decl_id(nid: str, name: str, kind: str) -> str:
|
||||
return decl_registry.resolve(nid, name, kind, seen_ids)
|
||||
|
||||
def ensure_named_node(name: str, line: int) -> str:
|
||||
nid = _make_id(stem, name)
|
||||
@@ -274,7 +279,7 @@ def extract_julia(path: Path) -> dict:
|
||||
name_node = next((c for c in node.children if c.type == "identifier"), None)
|
||||
if name_node:
|
||||
mod_name = _read_text(name_node, source)
|
||||
mod_nid = _make_id(stem, mod_name)
|
||||
mod_nid = decl_id(_make_id(stem, mod_name), mod_name, "ns")
|
||||
line = node.start_point[0] + 1
|
||||
add_node(mod_nid, mod_name, line)
|
||||
add_edge(file_nid, mod_nid, "defines", line)
|
||||
@@ -291,7 +296,7 @@ def extract_julia(path: Path) -> dict:
|
||||
struct_name, super_name = _type_head_names(type_head)
|
||||
if not struct_name:
|
||||
return
|
||||
struct_nid = _make_id(stem, struct_name)
|
||||
struct_nid = decl_id(_make_id(stem, struct_name), struct_name, "type")
|
||||
line = node.start_point[0] + 1
|
||||
add_node(struct_nid, struct_name, line)
|
||||
add_edge(scope_nid, struct_nid, "defines", line)
|
||||
@@ -324,7 +329,7 @@ def extract_julia(path: Path) -> dict:
|
||||
if type_head:
|
||||
abs_name, super_name = _type_head_names(type_head)
|
||||
if abs_name:
|
||||
abs_nid = _make_id(stem, abs_name)
|
||||
abs_nid = decl_id(_make_id(stem, abs_name), abs_name, "type")
|
||||
line = node.start_point[0] + 1
|
||||
add_node(abs_nid, abs_name, line)
|
||||
add_edge(scope_nid, abs_nid, "defines", line)
|
||||
@@ -340,7 +345,7 @@ def extract_julia(path: Path) -> dict:
|
||||
named = _func_name_from_signature(sig_node)
|
||||
if named:
|
||||
func_name, label = named
|
||||
func_nid = _make_id(stem, func_name)
|
||||
func_nid = decl_id(_make_id(stem, func_name), func_name, "fn")
|
||||
line = node.start_point[0] + 1
|
||||
add_node(func_nid, f"{label}()", line)
|
||||
add_edge(scope_nid, func_nid, "defines", line)
|
||||
@@ -405,7 +410,7 @@ def extract_julia(path: Path) -> dict:
|
||||
if type_node is not None:
|
||||
enum_name = _read_text(type_node, source)
|
||||
line = node.start_point[0] + 1
|
||||
enum_nid = _make_id(stem, enum_name)
|
||||
enum_nid = decl_id(_make_id(stem, enum_name), enum_name, "type")
|
||||
add_node(enum_nid, enum_name, line)
|
||||
add_edge(scope_nid, enum_nid, "defines", line)
|
||||
for member in arg_nodes[1:]:
|
||||
@@ -430,7 +435,7 @@ def extract_julia(path: Path) -> dict:
|
||||
named = _def_name(_unwrap_call_expression(lhs))
|
||||
if named:
|
||||
func_name, label = named
|
||||
func_nid = _make_id(stem, func_name)
|
||||
func_nid = decl_id(_make_id(stem, func_name), func_name, "fn")
|
||||
line = node.start_point[0] + 1
|
||||
add_node(func_nid, f"{label}()", line)
|
||||
add_edge(scope_nid, func_nid, "defines", line)
|
||||
|
||||
+251
-59
@@ -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,58 @@ _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
|
||||
# `#` preceded by whitespace is not part of the text: `## Setup ##` is "Setup",
|
||||
# while `## C#` and `## Trailing \#` keep their `#`.
|
||||
_MD_ATX_HEADING_RE = re.compile(r'^ {0,3}(#{1,6})[ \t]+(.+)$')
|
||||
_MD_ATX_CLOSING_RE = re.compile(r'(?:^|[ \t]+)#+[ \t]*$')
|
||||
|
||||
# A fenced code block line: a run of 3+ backticks or 3+ tildes, then the rest of
|
||||
# the line (an info string on an opener). Leading whitespace is accepted at any
|
||||
# depth, as before, so a fence inside a nested list item still counts.
|
||||
_MD_FENCE_RE = re.compile(r'^\s*(`{3,}|~{3,})(.*)$')
|
||||
|
||||
|
||||
def _fence_open(line: str) -> "tuple[str, int] | None":
|
||||
"""(fence char, run length) when ``line`` opens a fenced code block.
|
||||
|
||||
CommonMark: a backtick fence's info string may not contain a backtick, so
|
||||
a line that starts with an inline ```` ```code``` ```` span is prose, not a
|
||||
fence. Tilde fences have no such restriction.
|
||||
"""
|
||||
m = _MD_FENCE_RE.match(line)
|
||||
if not m:
|
||||
return None
|
||||
run, rest = m.group(1), m.group(2)
|
||||
if run[0] == "`" and "`" in rest:
|
||||
return None
|
||||
return run[0], len(run)
|
||||
|
||||
|
||||
def _fence_closes(line: str, fence: "tuple[str, int]") -> bool:
|
||||
"""True when ``line`` closes the block opened by ``fence``.
|
||||
|
||||
CommonMark: the closing run uses the opener's character, is at least as
|
||||
long, and carries nothing but whitespace after it. So ``` does not close a
|
||||
~~~ block, ``` does not close a ```` block (the usual way a doc shows a
|
||||
fenced example), and ``` followed by text is content.
|
||||
"""
|
||||
m = _MD_FENCE_RE.match(line)
|
||||
if not m:
|
||||
return False
|
||||
run, rest = m.group(1), m.group(2)
|
||||
return run[0] == fence[0] and len(run) >= fence[1] and not rest.strip()
|
||||
|
||||
# A YAML frontmatter block is only frontmatter when the opening `---` is the
|
||||
# very first line of the file. A `---` further down is a horizontal rule and
|
||||
@@ -257,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``.
|
||||
@@ -301,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
|
||||
@@ -334,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:
|
||||
@@ -351,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:
|
||||
@@ -390,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
|
||||
@@ -403,12 +497,16 @@ 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 (``` ... ```) are skipped during parsing so their
|
||||
contents don't get treated as headings, but no node is emitted for
|
||||
Fenced code blocks (``` ... ``` or ~~~ ... ~~~, closed by a run of the
|
||||
same character at least as long, per CommonMark) are skipped during
|
||||
parsing so their contents don't get treated as headings, but no node is emitted for
|
||||
them — they were always orphans (only a single contains edge to the
|
||||
parent doc) and inflated the disconnected-component count (#1077).
|
||||
|
||||
@@ -443,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(),
|
||||
@@ -454,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",
|
||||
@@ -481,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
|
||||
@@ -521,44 +682,48 @@ def extract_markdown(path: Path) -> dict:
|
||||
|
||||
# Track heading stack for nesting: [(level, nid), ...]
|
||||
heading_stack: list[tuple[int, str]] = []
|
||||
in_code_block = False
|
||||
fence: "tuple[str, int] | None" = None # (char, length) of the open fence
|
||||
|
||||
for line_num_0, line_text in enumerate(lines):
|
||||
line_num = line_num_0 + 1
|
||||
|
||||
# Skip over fenced code blocks so their contents are not parsed as
|
||||
# headings, but do not emit nodes/edges for them (#1077).
|
||||
stripped = line_text.strip()
|
||||
if stripped.startswith("```"):
|
||||
in_code_block = not in_code_block
|
||||
if fence is not None:
|
||||
if _fence_closes(line_text, fence):
|
||||
fence = None
|
||||
continue
|
||||
|
||||
if in_code_block:
|
||||
opened = _fence_open(line_text)
|
||||
if opened is not None:
|
||||
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.
|
||||
heading_match = re.match(r'^(#{1,6})\s+(.+)', line_text)
|
||||
if heading_match:
|
||||
heading_match = _MD_ATX_HEADING_RE.match(line_text)
|
||||
title = _MD_ATX_CLOSING_RE.sub("", heading_match.group(2).strip()) if heading_match else ""
|
||||
if heading_match and title:
|
||||
level = len(heading_match.group(1))
|
||||
title = heading_match.group(2).strip()
|
||||
h_nid = _make_id(stem, title)
|
||||
# Avoid duplicate heading IDs by appending line number
|
||||
if h_nid in seen_ids:
|
||||
@@ -574,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)
|
||||
|
||||
|
||||
@@ -295,7 +295,9 @@ def extract_objc(path: Path) -> dict:
|
||||
accepted = []
|
||||
for macro in descendants(root, "macro_type_specifier"):
|
||||
macro_name = macro.child_by_field_name("name")
|
||||
if macro_name is None or _read(macro_name) not in ("NS_ENUM", "NS_OPTIONS"):
|
||||
if macro_name is None or _read(macro_name) not in (
|
||||
"NS_ENUM", "NS_OPTIONS", "NS_CLOSED_ENUM"
|
||||
):
|
||||
continue
|
||||
|
||||
# The closest preceding structural token in an enclosing node must
|
||||
@@ -622,7 +624,7 @@ def extract_objc(path: Path) -> dict:
|
||||
# `typedef enum { ... } Name;` / `typedef enum Tag { ... } Name;`.
|
||||
# The enum body sits on a child enum_specifier that carries no usable
|
||||
# name; the name callers reference is the typedef alias (the trailing
|
||||
# type_identifier). NS_ENUM/NS_OPTIONS are handled separately through
|
||||
# type_identifier). NS_ENUM/NS_OPTIONS/NS_CLOSED_ENUM are handled separately through
|
||||
# their structural macro headers and isolated enum body fragments.
|
||||
enum_spec = next((c for c in node.children if c.type == "enum_specifier"), None)
|
||||
if enum_spec is not None and any(
|
||||
|
||||
@@ -193,11 +193,19 @@ def extract_ocaml(path: Path) -> dict:
|
||||
return
|
||||
|
||||
if t == "module_definition":
|
||||
binding = next((c for c in node.children if c.type == "module_binding"), None)
|
||||
if binding is not None:
|
||||
# `module A = ... and B = ...` (mutually recursive modules) nests
|
||||
# every binding under the ONE module_definition node, so taking
|
||||
# only the first `module_binding` silently dropped every module
|
||||
# after it, along with everything defined inside it. Walk every
|
||||
# binding, each with its own line (the node's own line is only
|
||||
# the first binding's), matching how type_definition already
|
||||
# walks every type_binding in a type ... and ... chain.
|
||||
for binding in node.children:
|
||||
if binding.type != "module_binding":
|
||||
continue
|
||||
mname = named_child_text(binding, "module_name")
|
||||
if mname:
|
||||
line = line_of(node)
|
||||
line = line_of(binding)
|
||||
mnid = _make_id(stem, mname)
|
||||
add_node(mnid, mname, line)
|
||||
add_edge(container_nid, mnid,
|
||||
@@ -206,7 +214,7 @@ def extract_ocaml(path: Path) -> dict:
|
||||
local_modules.add(mname)
|
||||
for child in binding.children:
|
||||
walk(child, mnid, enclosing_value)
|
||||
return
|
||||
return
|
||||
|
||||
if t == "module_type_definition": # .mli
|
||||
mname = named_child_text(node, "module_type_name")
|
||||
@@ -273,51 +281,58 @@ def extract_ocaml(path: Path) -> dict:
|
||||
# tree-sitter nests the name and the `object` body under a
|
||||
# class_binding; the body is an `object_expression` in .ml and a
|
||||
# `class_body_type` in .mli.
|
||||
binding = next((c for c in node.children
|
||||
if c.type == "class_binding"), None)
|
||||
if binding is not None:
|
||||
#
|
||||
# `class a = ... and b = ...` (mutually recursive classes) nests
|
||||
# every binding under the ONE class_definition node, so taking
|
||||
# only the first `class_binding` silently dropped every class
|
||||
# after it. Walk every binding, each with its own line (the
|
||||
# node's own line is only the first binding's).
|
||||
for binding in node.children:
|
||||
if binding.type != "class_binding":
|
||||
continue
|
||||
cname = named_child_text(binding, "class_name")
|
||||
if cname:
|
||||
line = line_of(node)
|
||||
cnid = _make_id(stem, cname)
|
||||
add_node(cnid, cname, line)
|
||||
add_edge(container_nid, cnid,
|
||||
"defines" if container_nid == file_nid else "contains", line)
|
||||
register_def(cname, cnid)
|
||||
body = _find_object_body(binding)
|
||||
if body is not None:
|
||||
for member in body.children:
|
||||
if member.type in ("method_definition", "method_specification"):
|
||||
mname = named_child_text(member, "method_name")
|
||||
if not mname:
|
||||
continue
|
||||
mline = line_of(member)
|
||||
mnid = _make_id(stem, cname, mname)
|
||||
add_node(mnid, mname, mline)
|
||||
# A method is a callable class member, so use the
|
||||
# "method" relation every other extractor emits
|
||||
# (an instance `val` stays "contains" - it's a
|
||||
# field). This keeps OCaml methods first-class in
|
||||
# the call-flow view and caller/callee index,
|
||||
# which key on "method" not "contains".
|
||||
add_edge(cnid, mnid, "method", mline)
|
||||
# Attribute calls in the method body to the
|
||||
# method. Methods are NOT registered as local
|
||||
# defs: they are only reachable through `obj#m`,
|
||||
# never as a bare `m ...`, so binding a bare call
|
||||
# to a same-named method would be a false edge.
|
||||
for child in member.children:
|
||||
walk(child, cnid, mnid)
|
||||
elif member.type in ("instance_variable_definition",
|
||||
"instance_variable_specification"):
|
||||
vname = named_child_text(member, "instance_variable_name")
|
||||
if not vname:
|
||||
continue
|
||||
vline = line_of(member)
|
||||
vnid = _make_id(stem, cname, vname)
|
||||
add_node(vnid, vname, vline)
|
||||
add_edge(cnid, vnid, "contains", vline)
|
||||
return
|
||||
if not cname:
|
||||
continue
|
||||
line = line_of(binding)
|
||||
cnid = _make_id(stem, cname)
|
||||
add_node(cnid, cname, line)
|
||||
add_edge(container_nid, cnid,
|
||||
"defines" if container_nid == file_nid else "contains", line)
|
||||
register_def(cname, cnid)
|
||||
body = _find_object_body(binding)
|
||||
if body is not None:
|
||||
for member in body.children:
|
||||
if member.type in ("method_definition", "method_specification"):
|
||||
mname = named_child_text(member, "method_name")
|
||||
if not mname:
|
||||
continue
|
||||
mline = line_of(member)
|
||||
mnid = _make_id(stem, cname, mname)
|
||||
add_node(mnid, mname, mline)
|
||||
# A method is a callable class member, so use the
|
||||
# "method" relation every other extractor emits
|
||||
# (an instance `val` stays "contains" - it's a
|
||||
# field). This keeps OCaml methods first-class in
|
||||
# the call-flow view and caller/callee index,
|
||||
# which key on "method" not "contains".
|
||||
add_edge(cnid, mnid, "method", mline)
|
||||
# Attribute calls in the method body to the
|
||||
# method. Methods are NOT registered as local
|
||||
# defs: they are only reachable through `obj#m`,
|
||||
# never as a bare `m ...`, so binding a bare call
|
||||
# to a same-named method would be a false edge.
|
||||
for child in member.children:
|
||||
walk(child, cnid, mnid)
|
||||
elif member.type in ("instance_variable_definition",
|
||||
"instance_variable_specification"):
|
||||
vname = named_child_text(member, "instance_variable_name")
|
||||
if not vname:
|
||||
continue
|
||||
vline = line_of(member)
|
||||
vnid = _make_id(stem, cname, vname)
|
||||
add_node(vnid, vname, vline)
|
||||
add_edge(cnid, vnid, "contains", vline)
|
||||
return
|
||||
|
||||
if t == "application_expression":
|
||||
fn = node.named_children[0] if node.named_children else None
|
||||
|
||||
@@ -28,7 +28,7 @@ _PAS_USES_RE = re.compile(
|
||||
|
||||
_PAS_TYPE_HEADER_RE = re.compile(
|
||||
r"\b(?P<name>[A-Za-z_]\w*)(?:\s*<[^>]+>)?\s*=\s*(?:packed\s+)?"
|
||||
r"(?P<kind>class|interface)\b"
|
||||
r"(?P<kind>class|interface|record)\b"
|
||||
r"(?:\s*\(\s*(?P<bases>[^)]*)\s*\))?",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
@@ -36,7 +36,7 @@ _PAS_TYPE_HEADER_RE = re.compile(
|
||||
_PAS_END_SEMI_RE = re.compile(r"\bend\s*;", re.IGNORECASE)
|
||||
|
||||
_PAS_METHOD_DECL_RE = re.compile(
|
||||
r"\b(?:procedure|function|constructor|destructor)\s+"
|
||||
r"\b(?:procedure|function|constructor|destructor|operator)\s+"
|
||||
r"(?P<name>[A-Za-z_]\w*)"
|
||||
r"(?:\s*\([^)]*\))?"
|
||||
r"(?:\s*:\s*[\w<>,\s.]+)?"
|
||||
@@ -45,7 +45,7 @@ _PAS_METHOD_DECL_RE = re.compile(
|
||||
)
|
||||
|
||||
_PAS_IMPL_HEADER_RE = re.compile(
|
||||
r"\b(?:procedure|function|constructor|destructor)\s+"
|
||||
r"\b(?:procedure|function|constructor|destructor|operator)\s+"
|
||||
r"(?P<qual>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)?)"
|
||||
r"(?:\s*<[^>]+>)?"
|
||||
r"(?:\s*\([^)]*\))?"
|
||||
@@ -66,8 +66,8 @@ _PAS_KEYWORDS = frozenset({
|
||||
"with", "inherited", "result", "var", "const", "type", "nil", "true",
|
||||
"false", "exit", "break", "continue", "uses", "unit", "program",
|
||||
"library", "interface", "implementation", "initialization", "finalization",
|
||||
"procedure", "function", "constructor", "destructor", "class", "record",
|
||||
"object", "array", "string", "integer", "boolean", "real", "char",
|
||||
"procedure", "function", "constructor", "destructor", "operator", "class",
|
||||
"record", "object", "array", "string", "integer", "boolean", "real", "char",
|
||||
"writeln", "write", "readln", "read", "assigned", "length", "high",
|
||||
"low", "inc", "dec", "new", "dispose", "setlength", "copy", "pos",
|
||||
"trim", "format", "inttostr", "strtoint", "ord", "chr", "sizeof",
|
||||
|
||||
@@ -70,7 +70,7 @@ def extract_lazarus_form(path: Path) -> dict:
|
||||
file_nid = _make_id(str(path))
|
||||
add_node(file_nid, path.name, 1)
|
||||
|
||||
obj_re = re.compile(r"^\s*object\s+\w+\s*:\s*(\w+)", re.IGNORECASE)
|
||||
obj_re = re.compile(r"^\s*(?:object|inherited|inline)\s+\w+\s*:\s*(\w+)", re.IGNORECASE)
|
||||
event_re = re.compile(r"^\s*On\w+\s*=\s*(\w+)", re.IGNORECASE)
|
||||
end_re = re.compile(r"^\s*end\s*$", re.IGNORECASE)
|
||||
|
||||
@@ -169,7 +169,7 @@ def extract_delphi_form(path: Path) -> dict:
|
||||
file_nid = _make_id(str(path))
|
||||
add_node(file_nid, path.name, 1)
|
||||
|
||||
obj_re = re.compile(r"^\s*object\s+\w+\s*:\s*(\w+)", re.IGNORECASE)
|
||||
obj_re = re.compile(r"^\s*(?:object|inherited|inline)\s+\w+\s*:\s*(\w+)", re.IGNORECASE)
|
||||
event_re = re.compile(r"^\s*On\w+\s*=\s*(\w+)", re.IGNORECASE)
|
||||
end_re = re.compile(r"^\s*end\s*$", re.IGNORECASE)
|
||||
stack: list[str] = [file_nid]
|
||||
|
||||
@@ -292,12 +292,28 @@ def extract_powershell(path: Path) -> dict:
|
||||
for el in child.children:
|
||||
if el.type == "generic_token":
|
||||
tokens.append(_read_text(el, source))
|
||||
using_kind = tokens[0].lower() if tokens else ""
|
||||
module_tokens = [t for t in tokens
|
||||
if t.lower() not in ("namespace", "module", "assembly")]
|
||||
if module_tokens:
|
||||
module_name = module_tokens[-1].split(".")[-1]
|
||||
add_edge(file_nid, _make_id(module_name), "imports_from",
|
||||
node.start_point[0] + 1)
|
||||
raw = module_tokens[-1]
|
||||
if using_kind == "namespace":
|
||||
module_name = raw.split(".")[-1]
|
||||
else:
|
||||
# `module`/`assembly` name a file or library
|
||||
# (Helpers.psm1, System.Data.dll): a trailing module
|
||||
# or assembly extension is not a namespace separator,
|
||||
# so splitting on it like the namespace form returned
|
||||
# the extension itself instead of the name. Strip only
|
||||
# a known extension, so a dotted module name with no
|
||||
# file extension (Az.Accounts) keeps its full name
|
||||
# rather than losing its last segment.
|
||||
module_name = re.sub(
|
||||
r'\.(psm1|psd1|ps1|dll|exe)$', '', raw, flags=re.IGNORECASE
|
||||
).split('/')[-1].split('\\')[-1]
|
||||
if module_name:
|
||||
add_edge(file_nid, _make_id(module_name), "imports_from",
|
||||
node.start_point[0] + 1)
|
||||
elif cmd_text == "import-module":
|
||||
# Collect generic_token args; skip command_parameter flags like -Name
|
||||
# The module name is the first generic_token (or the one after -Name)
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -125,6 +125,15 @@ def extract_razor(path: Path) -> dict:
|
||||
_add_ref(m.group(1), "inherits", i)
|
||||
continue
|
||||
|
||||
# A component can list one @implements per line for each interface it
|
||||
# satisfies (IDisposable, IAsyncDisposable, a custom one, ...), same as
|
||||
# a C# class heritage clause. Only @inherits (the base class) was ever
|
||||
# recorded; every @implements interface was silently invisible.
|
||||
m = re.match(r'@implements\s+([\w.<>\[\]]+)', line)
|
||||
if m:
|
||||
_add_ref(m.group(1), "implements", i)
|
||||
continue
|
||||
|
||||
m = re.match(r'@model\s+([\w.<>\[\]]+)', line)
|
||||
if m:
|
||||
_add_ref(m.group(1), "references", i)
|
||||
|
||||
@@ -12,6 +12,7 @@ from graphify.extractors.base import ( # noqa: F401
|
||||
_read_source_text,
|
||||
_read_text,
|
||||
)
|
||||
from graphify.ids import normalize_id
|
||||
from graphify.rcfile import effective_suffix, get_language_overrides
|
||||
import functools
|
||||
import hashlib
|
||||
@@ -422,7 +423,16 @@ def _pnpm_workspace_globs(workspace_file: Path) -> list[str]:
|
||||
in_packages = True
|
||||
continue
|
||||
if in_packages and line.startswith("-"):
|
||||
value = line[1:].strip().strip("'\"")
|
||||
value = line[1:].strip()
|
||||
if value[:1] in ("'", '"'):
|
||||
# Quoted: the value ends at the closing quote, so a `# comment` after it is dropped.
|
||||
end = value.find(value[0], 1)
|
||||
if end < 0:
|
||||
continue
|
||||
value = value[1:end].strip()
|
||||
else:
|
||||
# Unquoted: a `#` only starts a comment after whitespace.
|
||||
value = re.split(r"(?:^|\s)#", value, maxsplit=1)[0].strip()
|
||||
if value and not value.startswith("!"):
|
||||
globs.append(value)
|
||||
continue
|
||||
@@ -465,7 +475,11 @@ def _load_workspace_packages(start_dir: Path) -> dict[str, Path]:
|
||||
|
||||
packages: dict[str, Path] = {}
|
||||
for pattern in _workspace_globs(root):
|
||||
package_dirs: list[Path] = [root] if pattern in (".", "./") else list(root.glob(pattern))
|
||||
try:
|
||||
package_dirs: list[Path] = [root] if pattern in (".", "./") else list(root.glob(pattern))
|
||||
except (ValueError, NotImplementedError) as e:
|
||||
print(f" warning: skipped workspace glob {pattern!r} ({type(e).__name__}: {e})", file=sys.stderr, flush=True)
|
||||
continue
|
||||
for package_dir in package_dirs:
|
||||
manifest = package_dir / "package.json"
|
||||
if not manifest.is_file():
|
||||
@@ -853,7 +867,9 @@ def _resolve_js_module_path(raw: str | Path, start_dir: Path | None = None) -> P
|
||||
if start_dir is None:
|
||||
return _resolve_js_import_path(Path(raw))
|
||||
if raw.startswith("."):
|
||||
return _resolve_js_import_path(start_dir / raw)
|
||||
# Strip ?query / #fragment before resolving, as bundlers do (#4860).
|
||||
specifier = raw.split("#", 1)[0].split("?", 1)[0]
|
||||
return _resolve_js_import_path(start_dir / specifier)
|
||||
|
||||
aliases = _load_tsconfig_aliases(start_dir)
|
||||
hit = _resolve_tsconfig_alias(raw, aliases,
|
||||
@@ -1197,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":
|
||||
@@ -1206,7 +1228,9 @@ def _is_type_like_definition(node: dict) -> bool:
|
||||
return False
|
||||
if label.endswith(")") or label.startswith("."):
|
||||
return False
|
||||
if "." in label:
|
||||
# A dotted label names a namespace or module in most languages, but a SQL
|
||||
# table is `schema.name`: it is a type-like definition a reference can bind to.
|
||||
if "." in label and not str(node.get("source_file", "")).lower().endswith(".sql"):
|
||||
return False
|
||||
return node.get("file_type") == "code"
|
||||
|
||||
@@ -1250,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 (
|
||||
@@ -1262,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}
|
||||
@@ -1352,6 +1380,58 @@ def _apply_symbol_resolution_facts(
|
||||
})
|
||||
return node_id
|
||||
|
||||
# #4854: a reference to an imported name can be minted before the imported
|
||||
# declaration is known, as a sourceless stub (or as this file's own id when
|
||||
# the name equals the extension). Bind it to the declaration in the target
|
||||
# file, keyed by (path, name) so two modules may declare the same symbol.
|
||||
if facts.imports:
|
||||
declared: dict[tuple[Path, str], str] = {}
|
||||
for node in nodes:
|
||||
node_path = _js_source_path(str(node.get("source_file") or ""), root)
|
||||
if node_path is None:
|
||||
continue
|
||||
label = str(node.get("label") or "").strip()
|
||||
if not label or label.startswith("."):
|
||||
continue
|
||||
bare = label[:-2] if label.endswith("()") else label
|
||||
if "." in bare:
|
||||
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"
|
||||
):
|
||||
continue
|
||||
source_path = _resolve_cached(fact.file_path)
|
||||
target_path = _resolve_cached(fact.target_path)
|
||||
names = {normalize_id(fact.imported_name), normalize_id(fact.local_name)}
|
||||
target_nid = next(
|
||||
(declared[(target_path, name)] for name in names
|
||||
if (target_path, name) in declared),
|
||||
None,
|
||||
)
|
||||
if not target_nid:
|
||||
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"))
|
||||
if node is None or node.get("source_file"):
|
||||
continue
|
||||
stub_label = normalize_id(
|
||||
str(node.get("label") or "").strip("()").lstrip(".")
|
||||
)
|
||||
if stub_label in names:
|
||||
edge["target"] = target_nid
|
||||
|
||||
# Keyed by the emitting file as well: two files whose ids collide (`a-b/x.ts`
|
||||
# and `a/b/x.ts` both make `a_b_x`) share `source` until
|
||||
# _disambiguate_colliding_node_ids salts them by source_file, so without the
|
||||
@@ -1563,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.
|
||||
@@ -1620,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
|
||||
@@ -1748,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
|
||||
@@ -1765,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.
|
||||
@@ -1841,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()
|
||||
@@ -1950,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
|
||||
@@ -1963,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)
|
||||
@@ -2196,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",
|
||||
@@ -2216,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
|
||||
@@ -2228,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":
|
||||
@@ -2237,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)
|
||||
@@ -2267,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):
|
||||
@@ -2274,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
|
||||
@@ -2370,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)
|
||||
@@ -2392,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 (
|
||||
@@ -2413,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):
|
||||
@@ -2762,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:
|
||||
@@ -2792,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":
|
||||
@@ -2865,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)
|
||||
@@ -2893,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)
|
||||
@@ -2904,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)
|
||||
|
||||
@@ -2975,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)
|
||||
@@ -3152,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")
|
||||
@@ -3453,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:
|
||||
@@ -3463,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":
|
||||
@@ -3510,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,
|
||||
|
||||
@@ -187,6 +187,20 @@ def extract_robot(path: Path) -> dict:
|
||||
for tgt in kw_targets(name):
|
||||
add_edge(src, tgt, "calls", line, context="call")
|
||||
|
||||
# Robot Framework allows two test cases in one file to share a name (it
|
||||
# only warns, never a parse/run error, unlike a duplicate keyword
|
||||
# definition) - stem-qualifying by name alone then collapses both onto
|
||||
# one node, so the second test's own keyword calls land on the first
|
||||
# test's id and line. Counted up front so every occurrence of a
|
||||
# duplicated name salts by its own line number regardless of visit
|
||||
# order, and a name used only once keeps the plain id it always had.
|
||||
test_name_counts: dict[str, int] = {}
|
||||
|
||||
class _TestCaseCountVisitor(ModelVisitor):
|
||||
def visit_TestCase(self, node):
|
||||
if node.name:
|
||||
test_name_counts[node.name] = test_name_counts.get(node.name, 0) + 1
|
||||
|
||||
class _RobotVisitor(ModelVisitor):
|
||||
def __init__(self):
|
||||
self.scope_nid = file_nid
|
||||
@@ -253,7 +267,10 @@ def extract_robot(path: Path) -> dict:
|
||||
def visit_TestCase(self, node):
|
||||
if not node.name:
|
||||
return
|
||||
tc_nid = _make_id(stem, node.name)
|
||||
if test_name_counts.get(node.name, 0) >= 2:
|
||||
tc_nid = _make_id(stem, node.name, f"L{node.lineno}")
|
||||
else:
|
||||
tc_nid = _make_id(stem, node.name)
|
||||
add_node(tc_nid, node.name, node.lineno)
|
||||
add_edge(file_nid, tc_nid, "contains", node.lineno)
|
||||
prev, self.scope_nid = self.scope_nid, tc_nid
|
||||
@@ -290,6 +307,7 @@ def extract_robot(path: Path) -> dict:
|
||||
add_call_edges(self.scope_nid, node.value, node.lineno)
|
||||
|
||||
try:
|
||||
_TestCaseCountVisitor().visit(model)
|
||||
_RobotVisitor().visit(model)
|
||||
except Exception as e:
|
||||
return {"nodes": nodes, "edges": edges, "error": str(e)}
|
||||
|
||||
+192
-22
@@ -5,6 +5,7 @@ from __future__ import annotations
|
||||
import hashlib
|
||||
import re
|
||||
from pathlib import Path
|
||||
from graphify.ids import DeclIdRegistry
|
||||
from graphify.extractors.base import (
|
||||
_LANGUAGE_BUILTIN_GLOBALS,
|
||||
_file_stem,
|
||||
@@ -200,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.
|
||||
|
||||
@@ -274,27 +317,48 @@ def extract_rust(path: Path) -> dict:
|
||||
_scan_local_types(root)
|
||||
local_type_names = frozenset(local_types)
|
||||
|
||||
# Where each imported name comes from: `crate` for this crate's own paths, otherwise
|
||||
# the first path segment (`serde_json`, or a workspace crate's name). A sourceless
|
||||
# stub under such a name carries it, so the corpus rewire can scope the binding.
|
||||
use_roots: dict[str, set[str]] = {}
|
||||
|
||||
# `macro_rules!` macros defined in this file, keyed by bare name. A macro and a
|
||||
# function can share a name in Rust (`vec!` vs `vec`), and a macro is invoked
|
||||
# as `name!(...)` (a `macro_invocation`, never a `call_expression`), so macros
|
||||
# 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.
|
||||
impl_methods: dict[tuple[str, str], set[str]] = {}
|
||||
|
||||
# Nodes by id, so a declaration's node is found without scanning every node
|
||||
# (once per declaration, that scan was quadratic in the file's size).
|
||||
node_by_id: dict[str, dict] = {}
|
||||
|
||||
def add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({
|
||||
node_by_id[nid] = {
|
||||
"id": nid,
|
||||
"label": label,
|
||||
"file_type": "code",
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
})
|
||||
}
|
||||
nodes.append(node_by_id[nid])
|
||||
|
||||
def add_edge(src: str, tgt: str, relation: str, line: int,
|
||||
confidence: str = "EXTRACTED", weight: float = 1.0,
|
||||
@@ -314,6 +378,7 @@ def extract_rust(path: Path) -> dict:
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
add_node(file_nid, path.name, 1)
|
||||
decl_registry = DeclIdRegistry(reserved_ids=(file_nid,))
|
||||
|
||||
# Pre-scan the struct/enum/trait names declared in this file so a type used
|
||||
# above its declaration resolves exactly as a use below it already does,
|
||||
@@ -337,15 +402,15 @@ def extract_rust(path: Path) -> dict:
|
||||
|
||||
def _scan_type_items(node) -> None:
|
||||
t = node.type
|
||||
if t in ("struct_item", "enum_item", "trait_item", "function_item",
|
||||
"function_signature_item", "static_item", "const_item"):
|
||||
if t in ("struct_item", "enum_item", "trait_item", "union_item", "type_item",
|
||||
"function_item", "function_signature_item", "static_item", "const_item"):
|
||||
name_node = node.child_by_field_name("name")
|
||||
if name_node:
|
||||
name = _read_text(name_node, source)
|
||||
if t in ("static_item", "const_item") and name == "_":
|
||||
return
|
||||
nid = _make_id(stem, name)
|
||||
is_type = t in ("struct_item", "enum_item", "trait_item")
|
||||
is_type = t in ("struct_item", "enum_item", "trait_item", "union_item", "type_item")
|
||||
items_by_id.setdefault(nid, set()).add((is_type, name))
|
||||
if is_type:
|
||||
declared_type_names.setdefault(nid, set()).add(name)
|
||||
@@ -385,13 +450,12 @@ def extract_rust(path: Path) -> dict:
|
||||
# outcome never depends on declaration order. Repeats of one name (`#[cfg]`
|
||||
# twins, an `impl` of a local type) are one member and still share a node.
|
||||
def file_item_nid(plain_nid: str, name: str) -> str:
|
||||
nid = plain_nid
|
||||
names = {item_name for _is_type, item_name in items_by_id.get(plain_nid, ())}
|
||||
if len(names) < 2 or name not in names:
|
||||
return plain_nid
|
||||
if declared_type_names.get(plain_nid) == {name}:
|
||||
return plain_nid
|
||||
salt = hashlib.sha1(name.encode("utf-8"), usedforsecurity=False).hexdigest()[:6]
|
||||
return _make_id(plain_nid, salt)
|
||||
if len(names) >= 2 and name in names and declared_type_names.get(plain_nid) != {name}:
|
||||
salt = hashlib.sha1(name.encode("utf-8"), usedforsecurity=False).hexdigest()[:6]
|
||||
nid = _make_id(plain_nid, salt)
|
||||
return decl_registry.resolve(nid, name, "type", seen_ids)
|
||||
|
||||
def ensure_named_node(name: str, line: int) -> str:
|
||||
nid = file_item_nid(_make_id(stem, name), name)
|
||||
@@ -407,14 +471,15 @@ def extract_rust(path: Path) -> dict:
|
||||
# file's path (with extension) into the id and blocks the rewire, which is
|
||||
# the phantom-duplicate-node bug (#1402).
|
||||
seen_ids.add(nid)
|
||||
nodes.append({
|
||||
node_by_id[nid] = {
|
||||
"id": nid,
|
||||
"label": name,
|
||||
"file_type": "code",
|
||||
"source_file": "",
|
||||
"source_location": "",
|
||||
"origin_file": str_path,
|
||||
})
|
||||
}
|
||||
nodes.append(node_by_id[nid])
|
||||
return nid
|
||||
|
||||
def emit_param_return_refs(func_node, func_nid: str, line: int) -> None:
|
||||
@@ -514,14 +579,20 @@ def extract_rust(path: Path) -> dict:
|
||||
macro_nids_by_name.setdefault(macro_name, macro_nid)
|
||||
return
|
||||
|
||||
if t in ("struct_item", "enum_item", "trait_item"):
|
||||
# An associated type in an `impl` body (`type Output = Meters;`) is a
|
||||
# type_item too, but not a file-level item: it would mint one colliding
|
||||
# `Output` node per `impl Add`. Only an alias at module level is one.
|
||||
if t == "type_item" and node.parent is not None and node.parent.parent is not None \
|
||||
and node.parent.parent.type == "impl_item":
|
||||
return
|
||||
if t in ("struct_item", "enum_item", "trait_item", "union_item", "type_item"):
|
||||
name_node = node.child_by_field_name("name")
|
||||
if name_node:
|
||||
item_name = _read_text(name_node, source)
|
||||
line = node.start_point[0] + 1
|
||||
item_nid = file_item_nid(_make_id(stem, item_name), item_name)
|
||||
add_node(item_nid, item_name, line)
|
||||
declaration_node = next(n for n in nodes if n["id"] == item_nid)
|
||||
declaration_node = node_by_id[item_nid]
|
||||
declaration_node["_rust_declaration_count"] = (
|
||||
declaration_node.get("_rust_declaration_count", 0) + 1
|
||||
)
|
||||
@@ -545,7 +616,7 @@ def extract_rust(path: Path) -> dict:
|
||||
else:
|
||||
add_edge(item_nid, tgt, "references", line,
|
||||
context="generic_arg")
|
||||
if t == "struct_item":
|
||||
if t in ("struct_item", "union_item"):
|
||||
for c in node.children:
|
||||
if c.type != "field_declaration_list":
|
||||
continue
|
||||
@@ -729,7 +800,7 @@ def extract_rust(path: Path) -> dict:
|
||||
impl_keys[impl_nid] = impl_key
|
||||
elif impl_keys[impl_nid] != impl_key:
|
||||
impl_keys[impl_nid] = None
|
||||
impl_node = next(n for n in nodes if n["id"] == impl_nid)
|
||||
impl_node = node_by_id[impl_nid]
|
||||
if impl_keys[impl_nid]:
|
||||
impl_node["_rust_impl_key"] = impl_keys[impl_nid]
|
||||
else:
|
||||
@@ -756,6 +827,17 @@ def extract_rust(path: Path) -> dict:
|
||||
and (name_node := sibling.child_by_field_name("name")) is not None
|
||||
}
|
||||
|
||||
# A plain `pub use` re-exports the named item from the crate its path
|
||||
# starts with, so a later `use this_crate::Item` may reach a definition
|
||||
# that lives in that crate (#4699). `pub(crate)` and `pub(super)` stay
|
||||
# inside the re-exporting crate, so only a bare `pub` counts.
|
||||
visibility = next(
|
||||
(child for child in node.children if child.type == "visibility_modifier"),
|
||||
None,
|
||||
)
|
||||
reexport = visibility is not None and _read_text(
|
||||
visibility, source).strip() == "pub"
|
||||
|
||||
def name_use(written: str, path: str) -> None:
|
||||
# The name as written, for the corpus rewire (#4439): the id folds its
|
||||
# case. Only for a path rooted in this crate: `serde::Serialize` or
|
||||
@@ -764,6 +846,7 @@ def extract_rust(path: Path) -> dict:
|
||||
# too (`mod item; pub use item::Invoice;`), unless the path starts with
|
||||
# `::`, which always names a crate (#4564).
|
||||
first = path.lstrip(": ").split("::")[0].strip()
|
||||
bound = written.split(" as ")[-1].strip()
|
||||
ident = re.match(r"[A-Za-z_][A-Za-z0-9_]*", first) # `item as items` -> `item`
|
||||
if first in ("crate", "self", "super") or (
|
||||
ident is not None
|
||||
@@ -771,6 +854,11 @@ def extract_rust(path: Path) -> dict:
|
||||
and not path.lstrip().startswith("::")
|
||||
):
|
||||
edges[-1]["_rust_use_name"] = written.split(" as ")[0].strip()
|
||||
use_roots.setdefault(bound, set()).add("crate")
|
||||
else:
|
||||
use_roots.setdefault(bound, set()).add(first)
|
||||
if reexport and bound.isidentifier():
|
||||
edges[-1]["_rust_pub_use"] = {"label": bound, "root": first}
|
||||
module_name = _rust_use_module(_read_text(arg, source))
|
||||
grouped = arg.type in ("use_list", "scoped_use_list")
|
||||
if module_name:
|
||||
@@ -816,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,
|
||||
@@ -849,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
|
||||
@@ -903,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:
|
||||
@@ -921,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,
|
||||
@@ -939,6 +1098,17 @@ 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:
|
||||
node["_rust_use_roots"] = sorted(use_roots[node["label"]])
|
||||
|
||||
valid_ids = seen_ids
|
||||
clean_edges = []
|
||||
|
||||
+863
-44
File diff suppressed because it is too large.
Load diff
+219
-11
@@ -59,6 +59,22 @@ _TRIGGER_RECOVERY_RX = re.compile(
|
||||
re.IGNORECASE | re.DOTALL,
|
||||
)
|
||||
|
||||
# CREATE TABLE recovery, sibling to the routine/trigger patterns above. A
|
||||
# column default the grammar cannot model — MySQL/MariaDB
|
||||
# `DEFAULT current_timestamp()` / `ON UPDATE current_timestamp()`, whose
|
||||
# parentheses tree-sitter-sql rejects (upstream DerekStride/tree-sitter-sql)
|
||||
# — puts the whole statement in an ERROR node, so walk() never dispatches on
|
||||
# it and the table vanished, leaving only the sourceless stub that other
|
||||
# tables' REFERENCES minted for it (#4613). The name atom is _TRIGGER_IDENT
|
||||
# (the same delimited-identifier shape); the label is the bare name, with no
|
||||
# `()` suffix — a table is not callable either.
|
||||
_TABLE_RECOVERY_RX = re.compile(
|
||||
r"\bCREATE\s+(?:OR\s+(?:REPLACE|ALTER)\s+)?TABLE\s+"
|
||||
r"(?:IF\s+NOT\s+EXISTS\s+)?"
|
||||
r"(" + _TRIGGER_IDENT + r")",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
# _mask_sql_comments is a linear character scanner, not a regex: the four
|
||||
# span kinds interact in ways a single pattern cannot express safely —
|
||||
# comment-opener parity inside strings, nested block comments, and
|
||||
@@ -263,27 +279,173 @@ def _scan_sql(text: str) -> tuple[str, list[tuple[int, int]]]:
|
||||
return "".join(out), ident_spans
|
||||
|
||||
|
||||
# A procedure body is read as TEXT, not from the tree: tree-sitter-sql has no
|
||||
# procedure production, and without `;` it merges the body's statements into
|
||||
# one malformed expression. The body of a recovered routine runs from the end
|
||||
# of its name to the next CREATE/ALTER at the start of a line (`CREATE TABLE
|
||||
# #tmp` / `@tbl` inside a body does not end it), a line holding only `GO [n]`,
|
||||
# or EOF. Run over the comment- and string-masked text from _scan_sql.
|
||||
_BODY_END_RX = re.compile(
|
||||
r"^[ \t]*(?:GO(?:[ \t]+\d+)?[ \t\r]*;?[ \t\r]*$|(?:CREATE|ALTER)\b(?!\s+TABLE\s+[#@]))",
|
||||
re.IGNORECASE | re.MULTILINE,
|
||||
)
|
||||
# `(?![\w$]|\s*\.)` stops the identifier atom from backtracking to a prefix of
|
||||
# a longer name (`tempdb..#x`, `dbo.fn(`) and matching that instead.
|
||||
_BODY_TAIL = r"(?![\w$]|\s*\.)"
|
||||
_BODY_READ_RX = re.compile(r"\b(?:FROM|JOIN)\s+(" + _TRIGGER_IDENT + r")" + _BODY_TAIL, re.IGNORECASE)
|
||||
_BODY_WRITE_RX = re.compile(
|
||||
r"\b(INSERT(?:\s+INTO)?|UPDATE(?:\s+TOP\s*\([^)]*\))?|DELETE(?:\s+TOP\s*\([^)]*\))?(?:\s+FROM)?"
|
||||
r"|MERGE(?:\s+INTO)?|INTO)\s+(" + _TRIGGER_IDENT + r")" + _BODY_TAIL,
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_BODY_ALIAS_RX = re.compile(r"\s+(?:AS\s+)?([A-Za-z_][\w$]*)", re.IGNORECASE)
|
||||
_BODY_CTE_RX = re.compile(r"(?:\bWITH\s+(?:RECURSIVE\s+)?|,\s*)([\w$]+)\s*(?:\([^()]*\))?\s+AS\s*\(", re.IGNORECASE)
|
||||
# `ON DELETE`, `FOR UPDATE`, `AFTER INSERT, UPDATE`: an event or lock clause, not a statement.
|
||||
_BODY_EVENT_RX = re.compile(r"(?:\b(?:ON|FOR|AFTER|BEFORE|OF)|,)\s*$", re.IGNORECASE)
|
||||
# `EXTRACT(year FROM d)`, `TRIM(x FROM y)` and `FETCH NEXT FROM cur`: a FROM that names no table.
|
||||
_BODY_FROM_NOT_TABLE_RX = re.compile(
|
||||
r"(?:\b(?:EXTRACT|TRIM|SUBSTRING|OVERLAY|POSITION)\s*\([^()]*|\bDISTINCT\s+"
|
||||
r"|\bFETCH\s+(?:NEXT|PRIOR|FIRST|LAST|(?:ABSOLUTE|RELATIVE)\s+\S+)\s+)$",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
# Words that can follow FROM/JOIN/INTO/UPDATE/... without naming a table, and
|
||||
# words that cannot be an alias.
|
||||
_BODY_NON_TABLES = frozenset({
|
||||
"select", "where", "set", "dual", "null", "true", "false", "first", "skip",
|
||||
"rows", "next", "only", "lateral", "values", "when", "then", "output", "default",
|
||||
"cascade", "with", "top", "statistics", "into", "as", "on", "using", "not",
|
||||
"exists", "inserted", "deleted", "openquery", "openrowset", "opendatasource",
|
||||
"inner", "left", "right", "full", "cross", "outer", "join", "group", "order",
|
||||
"having", "union", "except", "intersect", "option", "for", "from", "where",
|
||||
"pivot", "unpivot", "tablesample", "natural", "apply",
|
||||
})
|
||||
|
||||
|
||||
def _routine_body_refs(masked: str) -> list[tuple[str, str, int]]:
|
||||
"""(relation, table name as written, offset) for each table a masked
|
||||
routine body reads (`FROM`/`JOIN`) or writes (`INSERT`/`UPDATE`/`DELETE`/
|
||||
`MERGE`/`SELECT ... INTO`), in source order. Temp tables and variables never
|
||||
match the identifier atom; CTE names and keywords are dropped; the target of
|
||||
`UPDATE o ... FROM dbo.Orders o` is resolved through the alias."""
|
||||
non_tables = set(_BODY_NON_TABLES)
|
||||
for cm in _BODY_CTE_RX.finditer(masked):
|
||||
non_tables.add(_norm_ident(cm.group(1)))
|
||||
|
||||
def _usable(name: str) -> bool:
|
||||
return _norm_ident(name) not in non_tables
|
||||
|
||||
writes: list[tuple[int, int, str, str]] = [] # (start, end, relation, name)
|
||||
for m in _BODY_WRITE_RX.finditer(masked):
|
||||
if m.group(1).upper() != "INTO" and _BODY_EVENT_RX.search(masked[max(0, m.start() - 30):m.start()]):
|
||||
continue
|
||||
if _usable(m.group(2)):
|
||||
writes.append((m.start(), m.end(), "writes_to", m.group(2)))
|
||||
|
||||
reads: list[tuple[int, str]] = []
|
||||
aliases: dict[str, str] = {}
|
||||
for m in _BODY_READ_RX.finditer(masked):
|
||||
if any(s <= m.start() < e for s, e, _r, _n in writes):
|
||||
continue # the FROM directly after DELETE names the write target
|
||||
if _BODY_FROM_NOT_TABLE_RX.search(masked[max(0, m.start() - 200):m.start()]):
|
||||
continue
|
||||
# `FROM dbo.fn_split(@x)` calls a table-valued function: not a table.
|
||||
if not _usable(m.group(1)) or masked[m.end():].lstrip().startswith("("):
|
||||
continue
|
||||
reads.append((m.start(), m.group(1)))
|
||||
am = _BODY_ALIAS_RX.match(masked, m.end())
|
||||
if am and am.group(1).lower() not in non_tables:
|
||||
aliases.setdefault(am.group(1).lower(), m.group(1))
|
||||
|
||||
refs = [(pos, "reads_from", name) for pos, name in reads]
|
||||
for pos, _end, relation, name in writes:
|
||||
if "." not in name:
|
||||
name = aliases.get(name.lower(), name)
|
||||
refs.append((pos, relation, name))
|
||||
return [(relation, name, pos) for pos, relation, name in sorted(refs)]
|
||||
|
||||
|
||||
# A `GO` batch separator is a client-tool command, not SQL: tree-sitter-sql reads it as an
|
||||
# identifier, so without a `;` before it the next statement is swallowed into an ERROR node.
|
||||
# Found on the masked text (comments and strings blanked), alone on its line, optionally
|
||||
# followed by a repeat count.
|
||||
_GO_LINE_RX = re.compile(r"^[ \t]*(GO(?:[ \t]+\d+)?)[ \t\r]*;?[ \t\r]*$", re.IGNORECASE | re.MULTILINE)
|
||||
|
||||
|
||||
def _go_separators(source: bytes) -> list[tuple[int, int]]:
|
||||
"""Byte spans of the `GO [n]` batch-separator lines in a T-SQL script.
|
||||
|
||||
A bare `go` on its own line is a column or alias, not a separator, only when the last
|
||||
non-blank character before it is a comma or the first one after it is a comma or `)`.
|
||||
Any keyword may precede a real separator (`SET NOCOUNT ON` / `GO`), so none is consulted.
|
||||
"""
|
||||
try:
|
||||
text = source.decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
return []
|
||||
masked = _scan_sql(text)[0]
|
||||
spans: list[tuple[int, int]] = []
|
||||
size = len(masked)
|
||||
char_pos = byte_pos = 0 # a character offset and its byte offset, advanced as matches are met
|
||||
for m in _GO_LINE_RX.finditer(masked):
|
||||
before, after = m.start() - 1, m.end()
|
||||
while before >= 0 and masked[before].isspace():
|
||||
before -= 1
|
||||
while after < size and masked[after].isspace():
|
||||
after += 1
|
||||
start, end = m.start(1), m.end(1)
|
||||
byte_start = byte_pos + len(text[char_pos:start].encode("utf-8"))
|
||||
byte_end = byte_start + len(text[start:end].encode("utf-8"))
|
||||
char_pos, byte_pos = end, byte_end
|
||||
if (before >= 0 and masked[before] == ",") or (after < size and masked[after] in ",)"):
|
||||
continue
|
||||
spans.append((byte_start, byte_end))
|
||||
return spans
|
||||
|
||||
|
||||
def _mask_sql_comments(text: str) -> str:
|
||||
"""Masked text only — see _scan_sql for the span-reporting form."""
|
||||
return _scan_sql(text)[0]
|
||||
|
||||
|
||||
def _clean_part(part: str) -> str:
|
||||
"""One name part without T-SQL brackets. The parser hands over `dbo].[Orders`
|
||||
for `[dbo].[Orders]`, so a part may keep only one of its two brackets; `]]`
|
||||
inside a bracketed name is an escaped `]`."""
|
||||
return part.removeprefix("[").removesuffix("]").replace("]]", "]")
|
||||
|
||||
|
||||
def _clean_ident(name: str) -> str:
|
||||
"""Display form of an object name: T-SQL brackets removed, schema kept.
|
||||
|
||||
`[dbo].[Orders]` and the parser's `dbo].[Orders` both give `dbo.Orders`.
|
||||
Double-quoted parts keep their quotes. Labels only: node ids come from the
|
||||
text as written and are not touched.
|
||||
"""
|
||||
if "[" not in name and "]" not in name:
|
||||
return name
|
||||
return ".".join(
|
||||
p if p.startswith('"') else _clean_part(p) for p in (part.strip() for part in name.split("."))
|
||||
)
|
||||
|
||||
|
||||
def _norm_ident(name: str) -> str:
|
||||
"""Normalize a SQL identifier for name-based reference resolution.
|
||||
|
||||
Splits on `.`, strips one pair of surrounding delimiters from each part
|
||||
(double quotes for Postgres/ANSI, backticks for MySQL, brackets for
|
||||
T-SQL), lowercases, and rejoins. So `"public"."users"`, `public.users`,
|
||||
and `PUBLIC.USERS` all normalize to `public.users`. Used ONLY for
|
||||
and `PUBLIC.USERS` all normalize to `public.users`, and `[dbo].[Orders]`,
|
||||
the parser's `dbo].[Orders` and `dbo.Orders` to `dbo.orders`. Used ONLY for
|
||||
`table_nids` keys and lookups — node ids and display labels keep the
|
||||
original text.
|
||||
"""
|
||||
parts = []
|
||||
for part in name.split("."):
|
||||
p = part.strip()
|
||||
if len(p) >= 2 and ((p[0] == p[-1] and p[0] in ('"', "`"))
|
||||
or (p[0] == "[" and p[-1] == "]")):
|
||||
if len(p) >= 2 and p[0] == p[-1] and p[0] in ('"', "`"):
|
||||
p = p[1:-1]
|
||||
else:
|
||||
p = _clean_part(p)
|
||||
parts.append(p.lower())
|
||||
return ".".join(parts)
|
||||
|
||||
@@ -314,7 +476,11 @@ def extract_sql(path: Path, content: str | bytes | None = None) -> dict:
|
||||
else content if content is not None
|
||||
else _read_source_bytes(path)
|
||||
)
|
||||
tree = parser.parse(source)
|
||||
# `GO` is not SQL; as `;` (same length, so offsets and lines hold) it ends the statement.
|
||||
patched = bytearray(source)
|
||||
for start, end in _go_separators(source):
|
||||
patched[start:end] = b";" + b" " * (end - start - 1)
|
||||
tree = parser.parse(bytes(patched))
|
||||
root = tree.root_node
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
@@ -371,7 +537,7 @@ def extract_sql(path: Path, content: str | bytes | None = None) -> dict:
|
||||
nid = _make_id(name)
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({"id": nid, "label": name, "file_type": "code",
|
||||
nodes.append({"id": nid, "label": _clean_ident(name), "file_type": "code",
|
||||
"source_file": "", "source_location": "",
|
||||
"origin_file": str_path})
|
||||
return nid
|
||||
@@ -384,7 +550,7 @@ def extract_sql(path: Path, content: str | bytes | None = None) -> dict:
|
||||
name = _obj_name(node)
|
||||
if name:
|
||||
nid = _make_id(stem, name)
|
||||
_add_node(nid, name, line)
|
||||
_add_node(nid, _clean_ident(name), line)
|
||||
table_nids[_norm_ident(name)] = nid
|
||||
# Foreign key REFERENCES
|
||||
for col in node.children:
|
||||
@@ -439,7 +605,7 @@ def extract_sql(path: Path, content: str | bytes | None = None) -> dict:
|
||||
name = _obj_name(node)
|
||||
if name:
|
||||
nid = _make_id(stem, name)
|
||||
_add_node(nid, name, line)
|
||||
_add_node(nid, _clean_ident(name), line)
|
||||
table_nids[_norm_ident(name)] = nid
|
||||
# FROM/JOIN table references inside view body
|
||||
_walk_from_refs(node, nid, line)
|
||||
@@ -448,7 +614,7 @@ def extract_sql(path: Path, content: str | bytes | None = None) -> dict:
|
||||
name = _obj_name(node)
|
||||
if name:
|
||||
nid = _make_id(stem, name)
|
||||
_add_node(nid, f"{name}()", line)
|
||||
_add_node(nid, f"{_clean_ident(name)}()", line)
|
||||
routine_nids[_norm_ident(name)] = nid
|
||||
_walk_from_refs(node, nid, line)
|
||||
|
||||
@@ -456,7 +622,7 @@ def extract_sql(path: Path, content: str | bytes | None = None) -> dict:
|
||||
name = _obj_name(node)
|
||||
if name:
|
||||
nid = _make_id(stem, name)
|
||||
_add_node(nid, f"{name}()", line)
|
||||
_add_node(nid, f"{_clean_ident(name)}()", line)
|
||||
routine_nids[_norm_ident(name)] = nid
|
||||
_walk_from_refs(node, nid, line)
|
||||
|
||||
@@ -663,6 +829,8 @@ def extract_sql(path: Path, content: str | bytes | None = None) -> dict:
|
||||
for child in node.children:
|
||||
_walk_from_refs(child, caller_nid, line, cte_names)
|
||||
|
||||
src_text = source.decode("utf-8", errors="replace")
|
||||
|
||||
# Pre-pass: register every table/view DEFINED in this file before walking,
|
||||
# so forward references (a FK to a table created later in the same file)
|
||||
# still resolve to the real sourced node instead of falling back to a stub.
|
||||
@@ -676,6 +844,21 @@ def extract_sql(path: Path, content: str | bytes | None = None) -> dict:
|
||||
|
||||
_collect_defined_names(root)
|
||||
|
||||
# A CREATE TABLE the grammar failed on (#4613) never reaches the pre-pass
|
||||
# — its statement sits inside an ERROR node — so references to it would
|
||||
# mint sourceless stubs and the REFERENCES fallback below would skip it.
|
||||
# When the parse failed, pre-register the recovered table names from the
|
||||
# masked source so resolution sees the real id; the node itself is
|
||||
# emitted in the has_error fallback, alongside the recovered routines
|
||||
# and triggers.
|
||||
if root.has_error:
|
||||
_masked, _ident_spans = _scan_sql(src_text)
|
||||
for m in _TABLE_RECOVERY_RX.finditer(_masked):
|
||||
if any(s <= m.start() < e for s, e in _ident_spans):
|
||||
continue
|
||||
table_nids.setdefault(
|
||||
_norm_ident(m.group(1)), _make_id(stem, m.group(1)))
|
||||
|
||||
# Secondary bare-name aliases: a reference written without a schema
|
||||
# (`REFERENCES users`) should resolve to a schema-qualified definition
|
||||
# (`public.users`) when that is unambiguous. Never shadow an explicit
|
||||
@@ -711,7 +894,6 @@ def extract_sql(path: Path, content: str | bytes | None = None) -> dict:
|
||||
# (e.g. Firebird COMPUTED BY columns push constraints out of the tree entirely).
|
||||
# Snapshot after tree walk so we don't re-emit edges already captured above.
|
||||
emitted = {(e["source"], e["target"]) for e in edges if e["relation"] == "references"}
|
||||
src_text = source.decode("utf-8", errors="replace")
|
||||
for m in re.finditer(r"CREATE\s+TABLE\s+([\w$]+)\s*\(", src_text, re.IGNORECASE):
|
||||
tbl_name = m.group(1)
|
||||
tbl_nid = table_nids.get(_norm_ident(tbl_name))
|
||||
@@ -765,7 +947,21 @@ def extract_sql(path: Path, content: str | bytes | None = None) -> dict:
|
||||
continue
|
||||
fn_name = m.group(1)
|
||||
fn_line = src_text[: m.start()].count("\n") + 1
|
||||
_add_node(_make_id(stem, fn_name), f"{fn_name}()", fn_line)
|
||||
fn_nid = _make_id(stem, fn_name)
|
||||
# A routine the tree already produced (a cleanly parsed function)
|
||||
# keeps its tree-based reads_from; scanning it too would double them.
|
||||
from_tree = fn_nid in seen_ids
|
||||
_add_node(fn_nid, f"{_clean_ident(fn_name)}()", fn_line)
|
||||
if from_tree:
|
||||
continue
|
||||
end = _BODY_END_RX.search(masked_src, m.end())
|
||||
seen_refs: set[tuple[str, str]] = set()
|
||||
for relation, tbl, pos in _routine_body_refs(masked_src[m.end():end.start() if end else len(masked_src)]):
|
||||
tbl_nid = table_nids.get(_norm_ident(tbl)) or _ref_stub(_clean_ident(tbl))
|
||||
if (relation, tbl_nid) in seen_refs:
|
||||
continue
|
||||
seen_refs.add((relation, tbl_nid))
|
||||
_add_edge(fn_nid, tbl_nid, relation, masked_src.count("\n", 0, m.end() + pos) + 1)
|
||||
|
||||
for m in _TRIGGER_RECOVERY_RX.finditer(masked_src):
|
||||
if any(s <= m.start() < e for s, e in ident_spans):
|
||||
@@ -782,4 +978,16 @@ def extract_sql(path: Path, content: str | bytes | None = None) -> dict:
|
||||
tbl_nid = table_nids.get(_norm_ident(tbl_name)) or _ref_stub(tbl_name)
|
||||
_add_edge(trig_nid, tbl_nid, "triggers", trig_line)
|
||||
|
||||
# Tables the grammar dropped into an ERROR node (#4613), pre-registered
|
||||
# above so references already resolved to this id. _add_node dedupes,
|
||||
# so a table that parsed cleanly keeps its walk-emitted node.
|
||||
for m in _TABLE_RECOVERY_RX.finditer(masked_src):
|
||||
if any(s <= m.start() < e for s, e in ident_spans):
|
||||
continue
|
||||
tbl_name = m.group(1)
|
||||
tbl_line = src_text[: m.start()].count("\n") + 1
|
||||
# Clean the label (brackets/quotes) for display but key the id off the
|
||||
# raw name so it matches the pre-pass registration the FK edges resolved to.
|
||||
_add_node(_make_id(stem, tbl_name), _clean_ident(tbl_name), tbl_line)
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
@@ -9,6 +9,7 @@ from collections.abc import Sequence
|
||||
from pathlib import Path
|
||||
from graphify.extractors.base import _make_id, _read_source_bytes
|
||||
from graphify.security import (
|
||||
REDACTED_MARKER,
|
||||
_CONTROL_CHAR_RE,
|
||||
_METADATA_MAX_ATTRIBUTES,
|
||||
_METADATA_MAX_LIST_ITEMS,
|
||||
@@ -31,7 +32,7 @@ _SENSITIVE_KEY_RE = re.compile(
|
||||
r"sas[-_]?token|auth|passphrase)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_REDACTED = "[redacted]"
|
||||
_REDACTED = REDACTED_MARKER
|
||||
_PAIRED_VALUE_KEYS = frozenset({"value", "valuefrom", "value_from"})
|
||||
|
||||
|
||||
@@ -78,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 + "_"):
|
||||
@@ -257,7 +262,7 @@ def extract_terraform(path: Path) -> dict:
|
||||
labels.append(_label_text(c))
|
||||
return btype, labels
|
||||
|
||||
def _ref_address(expr):
|
||||
def _head_and_attrs(expr) -> tuple[str, list[str]]:
|
||||
head = _read(expr)
|
||||
parent = expr.parent
|
||||
attrs: list[str] = []
|
||||
@@ -278,6 +283,10 @@ def extract_terraform(path: Path) -> dict:
|
||||
attrs.append(name)
|
||||
elif seen_self and c.type not in ("get_attr",):
|
||||
break
|
||||
return head, attrs
|
||||
|
||||
def _ref_address(expr):
|
||||
head, attrs = _head_and_attrs(expr)
|
||||
if head in _TF_META_HEADS or not head:
|
||||
return None
|
||||
if head == "var":
|
||||
@@ -290,21 +299,36 @@ def extract_terraform(path: Path) -> dict:
|
||||
return f"data.{attrs[0]}.{attrs[1]}" if len(attrs) >= 2 else None
|
||||
return f"{head}.{attrs[0]}" if attrs else None
|
||||
|
||||
def _collect_refs(node, owner_nid: str, relation: str) -> None:
|
||||
def _provider_ref_address(expr):
|
||||
# A `provider = aws.west` value names a provider BLOCK by type and
|
||||
# alias, the same `head.attr` shape `_ref_address` already reads for
|
||||
# a resource reference (`aws_instance.web.id` -> `aws_instance.web`).
|
||||
# Without this, `aws.west` fell through to that generic reading and
|
||||
# pointed at a node that was never minted.
|
||||
head, attrs = _head_and_attrs(expr)
|
||||
if not head:
|
||||
return None
|
||||
return f"provider.{head}.{attrs[0]}" if attrs else f"provider.{head}"
|
||||
|
||||
def _collect_refs(node, owner_nid: str, relation: str, in_provider_attr: bool = False) -> None:
|
||||
rel = relation
|
||||
provider_attr = in_provider_attr
|
||||
if node.type == "attribute":
|
||||
key_node = node.child_by_field_name("key") or (
|
||||
node.children[0] if node.children else None
|
||||
)
|
||||
if key_node is not None and _read(key_node) == "depends_on":
|
||||
rel = "depends_on"
|
||||
if key_node is not None:
|
||||
key_text = _read(key_node)
|
||||
if key_text == "depends_on":
|
||||
rel = "depends_on"
|
||||
provider_attr = key_text == "provider"
|
||||
if node.type == "variable_expr":
|
||||
addr = _ref_address(node)
|
||||
addr = _provider_ref_address(node) if provider_attr else _ref_address(node)
|
||||
if addr:
|
||||
_add_edge(owner_nid, addr, rel, node.start_point[0] + 1)
|
||||
for c in node.children:
|
||||
if c.is_named:
|
||||
_collect_refs(c, owner_nid, rel)
|
||||
_collect_refs(c, owner_nid, rel, provider_attr)
|
||||
|
||||
def _clean_val_str(text: str) -> str:
|
||||
text = _CONTROL_CHAR_RE.sub("", str(text))
|
||||
@@ -428,7 +452,29 @@ def extract_terraform(path: Path) -> dict:
|
||||
elif btype == "output" and labels:
|
||||
owner = _add_node(f"output.{labels[0]}", f"output.{labels[0]}", line)
|
||||
elif btype == "provider" and labels:
|
||||
owner = _add_node(f"provider.{labels[0]}", f"provider.{labels[0]}", line)
|
||||
# An aliased provider block (`provider "aws" { alias = "west" }`)
|
||||
# configures a SECOND, distinct provider of the same type. Without
|
||||
# the alias in the id, a second `provider "aws" {...}` block for a
|
||||
# different alias collapsed onto the same node as the first,
|
||||
# silently losing its own attributes to whichever block the walk
|
||||
# reached last.
|
||||
alias = None
|
||||
if blk_body is not None:
|
||||
for attr in blk_body.children:
|
||||
if attr.type != "attribute":
|
||||
continue
|
||||
k_node = attr.children[0] if attr.children else None
|
||||
if k_node is None or _read(k_node) != "alias":
|
||||
continue
|
||||
v_node = attr.named_children[-1] if attr.named_children else None
|
||||
if v_node is None:
|
||||
continue
|
||||
alias_val = _parse_attr_value(v_node)
|
||||
if isinstance(alias_val, str) and alias_val:
|
||||
alias = alias_val
|
||||
break
|
||||
address = f"provider.{labels[0]}.{alias}" if alias else f"provider.{labels[0]}"
|
||||
owner = _add_node(address, address, line)
|
||||
elif btype == "locals" and blk_body is not None:
|
||||
for attr in blk_body.children:
|
||||
if attr.type != "attribute":
|
||||
@@ -438,7 +484,14 @@ def extract_terraform(path: Path) -> dict:
|
||||
continue
|
||||
key = _read(key_node)
|
||||
lnid = _add_node(f"local.{key}", f"local.{key}", attr.start_point[0] + 1)
|
||||
_collect_refs(attr, lnid, "references")
|
||||
# Walk the VALUE only, not the attribute itself -- the local's
|
||||
# own name sits in the same `key` slot `_collect_refs` reads to
|
||||
# detect a `provider = ...`/`depends_on = ...` attribute, so a
|
||||
# local literally named either would otherwise be misread as
|
||||
# one.
|
||||
value_node = attr.named_children[-1] if attr.named_children else None
|
||||
if value_node is not None:
|
||||
_collect_refs(value_node, lnid, "references")
|
||||
continue
|
||||
else:
|
||||
continue
|
||||
@@ -459,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}
|
||||
@@ -128,11 +128,10 @@ def extract_vbnet(path: Path) -> dict:
|
||||
"id": nid,
|
||||
"label": label,
|
||||
"file_type": "code",
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
"source_file": source_file if source_backed else "",
|
||||
"source_location": f"L{node.start_point[0] + 1}" if source_backed else "",
|
||||
"metadata": details,
|
||||
}
|
||||
if source_backed:
|
||||
item["source_file"] = source_file
|
||||
if callable_node:
|
||||
item["_callable"] = True
|
||||
nodes.append(item)
|
||||
@@ -267,7 +266,9 @@ def extract_vbnet(path: Path) -> dict:
|
||||
if member.type == "event_declaration":
|
||||
events[(owner_key, data_name.casefold())] = member_id
|
||||
continue
|
||||
if member.type not in {"method_declaration", "constructor_declaration"}:
|
||||
if member.type not in {
|
||||
"method_declaration", "constructor_declaration", "operator_declaration",
|
||||
}:
|
||||
continue
|
||||
|
||||
if member.type == "constructor_declaration":
|
||||
@@ -278,7 +279,9 @@ def extract_vbnet(path: Path) -> dict:
|
||||
if method_name_node is None:
|
||||
continue
|
||||
method_name = _read_text(method_name_node, source)
|
||||
method_kind = "method"
|
||||
method_kind = (
|
||||
"operator" if member.type == "operator_declaration" else "method"
|
||||
)
|
||||
parameters = member.child_by_field_name("parameters")
|
||||
parameter_nodes = (
|
||||
[child for child in parameters.named_children if child.type == "parameter"]
|
||||
@@ -381,7 +384,8 @@ def extract_vbnet(path: Path) -> dict:
|
||||
while stack:
|
||||
node = stack.pop()
|
||||
if node != body and node.type in {
|
||||
"method_declaration", "constructor_declaration", "property_declaration"
|
||||
"method_declaration", "constructor_declaration", "property_declaration",
|
||||
"operator_declaration",
|
||||
}:
|
||||
continue
|
||||
if node.type == "invocation":
|
||||
|
||||
@@ -47,8 +47,20 @@ _SV_PARENS_INNER = r"(?:[^()]|\([^()]*\))*"
|
||||
|
||||
_SV_PARENS = r"\(" + _SV_PARENS_INNER + r"\)"
|
||||
|
||||
# The return type is optional: a `new` constructor never has one, and a plain
|
||||
# `function foo(...);` implicitly returns a 1-bit value. Without the `?` here,
|
||||
# every constructor method - the single most common one in a SystemVerilog
|
||||
# class - matched nothing at all: no node, no parameter-type references.
|
||||
_SV_FUNC_RE = re.compile(
|
||||
r"\bfunction\s+([A-Za-z_]\w*(?:\s*#\s*" + _SV_PARENS + r")?)\s+(\w+)\s*"
|
||||
r"\bfunction\s+(?:([A-Za-z_]\w*(?:\s*#\s*" + _SV_PARENS + r")?)\s+)?(\w+)\s*"
|
||||
r"\((" + _SV_PARENS_INNER + r")\)\s*;",
|
||||
re.MULTILINE,
|
||||
)
|
||||
|
||||
# A class method declared `task` instead of `function` has no return type to
|
||||
# capture, otherwise the same header shape.
|
||||
_SV_TASK_RE = re.compile(
|
||||
r"\btask\s+(\w+)\s*"
|
||||
r"\((" + _SV_PARENS_INNER + r")\)\s*;",
|
||||
re.MULTILINE,
|
||||
)
|
||||
@@ -167,21 +179,30 @@ def _augment_systemverilog_semantics(
|
||||
for iface_name in _sv_split_type_list(impl.group(1)):
|
||||
add_edge(class_nid, iface_name.split("#", 1)[0].strip(), "implements", line)
|
||||
|
||||
body_without_functions = re.sub(
|
||||
# A `task` method's own locals (and any typed declaration inside its
|
||||
# body) must not leak into the field scan below, exactly like a
|
||||
# function's body already doesn't - so both get stripped the same way.
|
||||
body_without_methods = re.sub(
|
||||
r"\bfunction\b.*?\bendfunction\b",
|
||||
lambda m: "\n" * m.group(0).count("\n"),
|
||||
body,
|
||||
flags=re.DOTALL,
|
||||
)
|
||||
body_without_methods = re.sub(
|
||||
r"\btask\b.*?\bendtask\b",
|
||||
lambda m: "\n" * m.group(0).count("\n"),
|
||||
body_without_methods,
|
||||
flags=re.DOTALL,
|
||||
)
|
||||
# Optional leading class-property qualifiers (rand/local/protected/etc.)
|
||||
# must be consumed: otherwise a qualified field like `rand Config x;`
|
||||
# (three tokens) fails the `<type> <name>;` shape and its type reference
|
||||
# is silently dropped.
|
||||
for field in re.finditer(r"^\s*(?:(?:rand|randc|local|protected|static|const|automatic|var)\s+)*([A-Za-z_]\w*(?:\s*#\s*\([^;]+?\))?)\s+\w+\s*;", body_without_functions, re.MULTILINE):
|
||||
for field in re.finditer(r"^\s*(?:(?:rand|randc|local|protected|static|const|automatic|var)\s+)*([A-Za-z_]\w*(?:\s*#\s*\([^;]+?\))?)\s+\w+\s*;", body_without_methods, re.MULTILINE):
|
||||
# Count to the start of the type token (group 1), not the match
|
||||
# start: `^\s*` consumes the leading newline(s), so field.start()
|
||||
# would resolve to the class's line instead of the field's.
|
||||
field_line = line + body_without_functions.count("\n", 0, field.start(1))
|
||||
field_line = line + body_without_methods.count("\n", 0, field.start(1))
|
||||
for ref_name, role in _sv_collect_type_refs(field.group(1), skip=type_params):
|
||||
add_edge(class_nid, ref_name, "references", field_line, "generic_arg" if role == "generic_arg" else "field")
|
||||
|
||||
@@ -193,8 +214,9 @@ def _augment_systemverilog_semantics(
|
||||
edges.append({"source": class_nid, "target": func_nid, "relation": "method",
|
||||
"confidence": "EXTRACTED", "confidence_score": 1.0,
|
||||
"source_file": str_path, "source_location": f"L{func_line}", "weight": 1.0})
|
||||
for ref_name, role in _sv_collect_type_refs(return_type, skip=type_params):
|
||||
add_edge(func_nid, ref_name, "references", func_line, "generic_arg" if role == "generic_arg" else "return_type")
|
||||
if return_type:
|
||||
for ref_name, role in _sv_collect_type_refs(return_type, skip=type_params):
|
||||
add_edge(func_nid, ref_name, "references", func_line, "generic_arg" if role == "generic_arg" else "return_type")
|
||||
for param in _sv_split_type_list(params):
|
||||
pm = _SV_PARAM_RE.match(param)
|
||||
if not pm:
|
||||
@@ -202,6 +224,21 @@ def _augment_systemverilog_semantics(
|
||||
for ref_name, role in _sv_collect_type_refs(pm.group(1), skip=type_params):
|
||||
add_edge(func_nid, ref_name, "references", func_line, "generic_arg" if role == "generic_arg" else "parameter_type")
|
||||
|
||||
for tm in _SV_TASK_RE.finditer(body):
|
||||
task_name, params = tm.group(1), tm.group(2)
|
||||
task_line = line + body.count("\n", 0, tm.start())
|
||||
task_nid = _make_id(class_nid, task_name)
|
||||
add_node(task_nid, task_name, task_line)
|
||||
edges.append({"source": class_nid, "target": task_nid, "relation": "method",
|
||||
"confidence": "EXTRACTED", "confidence_score": 1.0,
|
||||
"source_file": str_path, "source_location": f"L{task_line}", "weight": 1.0})
|
||||
for param in _sv_split_type_list(params):
|
||||
pm = _SV_PARAM_RE.match(param)
|
||||
if not pm:
|
||||
continue
|
||||
for ref_name, role in _sv_collect_type_refs(pm.group(1), skip=type_params):
|
||||
add_edge(task_nid, ref_name, "references", task_line, "generic_arg" if role == "generic_arg" else "parameter_type")
|
||||
|
||||
def extract_verilog(path: Path) -> dict:
|
||||
"""Extract modules, functions, tasks, package imports, instantiations, and
|
||||
SystemVerilog class semantics (inherits/implements edges, field/parameter/
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
"""YAML structural extractor.
|
||||
|
||||
Deterministic, PyYAML-based extraction for ``.yaml``/``.yml`` files so that
|
||||
config-heavy repositories (Helm charts, Kubernetes manifests, CI pipelines)
|
||||
contribute nodes to code-only / AST-only runs (``graphify update``) instead of
|
||||
being skipped entirely (#2214).
|
||||
|
||||
Mirrors ``extract_json`` in shape: a file node plus ``contains`` edges to
|
||||
top-level (and nested) keys, with a pair/depth cap to keep data-heavy YAML from
|
||||
exploding into orphan nodes. Like ``extract_json``'s ``_is_config_json`` gate,
|
||||
data-shaped YAML (a top-level data array, an OpenAPI/Swagger spec, a flat
|
||||
key:value data bundle) is skipped so it does not mint up to 500 orphan nodes
|
||||
(the #1224/#2255 class of problem).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from graphify.extractors.base import _file_stem, _make_id
|
||||
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.
|
||||
_CONFIG_YAML_NAMES = frozenset({
|
||||
"values.yaml", "values.yml", "chart.yaml", "chart.yml",
|
||||
"docker-compose.yaml", "docker-compose.yml", "compose.yaml", "compose.yml",
|
||||
"kustomization.yaml", "kustomization.yml", "skaffold.yaml", "skaffold.yml",
|
||||
"serverless.yaml", "serverless.yml", "mkdocs.yaml", "mkdocs.yml",
|
||||
".gitlab-ci.yml", ".gitlab-ci.yaml", ".pre-commit-config.yaml",
|
||||
"cloudbuild.yaml", "cloudbuild.yml", "pubspec.yaml", "environment.yml",
|
||||
"action.yml", "action.yaml", "catalog-info.yaml", ".travis.yml",
|
||||
"appveyor.yml", "azure-pipelines.yml",
|
||||
})
|
||||
# Top-level keys that signal a config/manifest (k8s, CI, compose, ansible, helm).
|
||||
_CONFIG_YAML_KEYS = frozenset({
|
||||
"apiversion", "kind", "metadata", "spec", # k8s
|
||||
"services", "volumes", "networks", # compose
|
||||
"jobs", "steps", "stages", "on", "workflows", "pipeline", # CI
|
||||
"hosts", "tasks", "roles", # ansible
|
||||
"name", "version", "dependencies", "scripts", # generic
|
||||
"resources", "provider", "functions", # serverless
|
||||
})
|
||||
|
||||
|
||||
def _is_config_yaml(path: Path, data: Any, key_texts: set[str] | None = None) -> bool:
|
||||
"""True if a YAML document is a recognized config/manifest worth extracting.
|
||||
|
||||
Matches by filename first, then a ``.github/workflows`` path, then a
|
||||
top-level key probe. Skips clear data: a plain data array, an OpenAPI/Swagger
|
||||
spec, a JSON-Schema-in-YAML, and a flat all-scalar mapping with no config
|
||||
key (for example an i18n string bundle). Errs toward extracting (a mapping
|
||||
with any nested value is treated as config) so an arbitrarily-named real
|
||||
config is not silently dropped.
|
||||
|
||||
``key_texts`` are the top-level keys as written in the source. PyYAML
|
||||
resolves YAML 1.1 booleans, so the constructed key of a workflow's ``on:``
|
||||
is ``True``; the written spelling is what the key probe must see.
|
||||
"""
|
||||
name = path.name.casefold()
|
||||
if name in _CONFIG_YAML_NAMES:
|
||||
return True
|
||||
if "/.github/workflows/" in path.as_posix().casefold():
|
||||
return True
|
||||
if isinstance(data, list):
|
||||
# A top-level sequence is config only when it is an ansible-style list of
|
||||
# plays/tasks; a plain data array is not.
|
||||
return any(
|
||||
isinstance(item, dict)
|
||||
and ({"hosts", "tasks", "roles"} & {str(k).casefold() for k in item})
|
||||
for item in data
|
||||
)
|
||||
if not isinstance(data, dict):
|
||||
return False
|
||||
keys = key_texts if key_texts is not None else {str(k).casefold() for k in data.keys()}
|
||||
if ("openapi" in keys or "swagger" in keys) and "paths" in keys:
|
||||
return False # an API spec is data-heavy, not a config to walk (#2255-style)
|
||||
if "$schema" in keys and ({"$defs", "definitions", "$id"} & keys):
|
||||
return False # a JSON schema in YAML clothing
|
||||
if keys & _CONFIG_YAML_KEYS:
|
||||
return True
|
||||
# A mapping with at least one nested value is config-like; a flat all-scalar
|
||||
# mapping with no config key is treated as a data bundle and skipped.
|
||||
return any(isinstance(v, (dict, list)) for v in data.values())
|
||||
|
||||
|
||||
def _doc_label(doc: Any, index: int) -> str:
|
||||
"""A stable label for one document of a multi-document YAML stream."""
|
||||
if isinstance(doc, dict):
|
||||
kind = doc.get("kind")
|
||||
if isinstance(kind, str) and kind:
|
||||
meta = doc.get("metadata")
|
||||
nm = meta.get("name") if isinstance(meta, dict) else None
|
||||
return f"{kind} {nm}" if isinstance(nm, str) and nm else kind
|
||||
return f"doc {index}"
|
||||
|
||||
|
||||
_MERGE_TAG = "tag:yaml.org,2002:merge"
|
||||
|
||||
|
||||
def _mapping_pairs(node: Any) -> list[tuple[str, Any, Any]]:
|
||||
"""(key text, key node, value node) for a composed mapping, in the order the
|
||||
constructed dict would hold them.
|
||||
|
||||
Keys come back as written (``on``, not the YAML 1.1 boolean ``True``) and
|
||||
carry their own line. A ``<<`` merge contributes its mapping's pairs first,
|
||||
and a repeated key keeps its first position but takes the last value and
|
||||
line, mirroring PyYAML's ``flatten_mapping`` plus dict insertion. A non-scalar key
|
||||
has no written name to label a node with and is skipped.
|
||||
"""
|
||||
import yaml # type: ignore
|
||||
|
||||
merged: list[tuple[str, Any, Any]] = []
|
||||
explicit: 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]
|
||||
# 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):
|
||||
explicit.append((key_node.value, key_node, value_node))
|
||||
pairs: dict[str, tuple[str, Any, Any]] = {}
|
||||
for text, key_node, value_node in merged + explicit:
|
||||
# Reassigning keeps the dict position; the later key node (an explicit
|
||||
# override of a merged key) is the one whose line holds the value.
|
||||
pairs[text] = (text, key_node, value_node)
|
||||
return list(pairs.values())
|
||||
|
||||
|
||||
def extract_yaml(path: Path) -> dict:
|
||||
"""Extract structural nodes/edges from a ``.yaml``/``.yml`` file.
|
||||
|
||||
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
|
||||
except ImportError:
|
||||
return {"nodes": [], "edges": [],
|
||||
"error": "pyyaml not installed; install with `pip install pyyaml`"}
|
||||
|
||||
try:
|
||||
with path.open("rb") as _f:
|
||||
raw = _f.read(_YAML_MAX_BYTES + 1)
|
||||
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.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.
|
||||
trees = list(yaml.compose_all(text, Loader=yaml.SafeLoader))
|
||||
except Exception as exc: # noqa: BLE001 - surface any parse failure to caller
|
||||
return {"nodes": [], "edges": [], "error": str(exc)}
|
||||
|
||||
structured = [(d, n) for d, n in zip(docs, trees) if isinstance(d, (dict, list))]
|
||||
if not structured:
|
||||
return {"nodes": [], "edges": [], "skipped": "scalar yaml"}
|
||||
|
||||
def _top_keys(tree: Any) -> set[str] | None:
|
||||
if isinstance(tree, yaml.MappingNode):
|
||||
return {text.casefold() for text, _k, _v in _mapping_pairs(tree)}
|
||||
return None
|
||||
|
||||
config_docs = [(d, n) for d, n in structured if _is_config_yaml(path, d, _top_keys(n))]
|
||||
if not config_docs:
|
||||
return {"nodes": [], "edges": [], "skipped": "data yaml (not a config/manifest)"}
|
||||
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
|
||||
def add_node(nid: str, label: str, line: int = 1, file_type: str = "code") -> None:
|
||||
if nid and nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append(
|
||||
{"id": nid, "label": str(label), "file_type": file_type,
|
||||
"source_file": str_path, "source_location": f"L{line}"}
|
||||
)
|
||||
|
||||
def add_edge(src: str, tgt: str, relation: str, line: int = 1,
|
||||
context: str | None = None) -> None:
|
||||
if not src or not tgt or src == tgt:
|
||||
return
|
||||
edge = {"source": src, "target": tgt, "relation": relation,
|
||||
"confidence": "EXTRACTED", "source_file": str_path,
|
||||
"source_location": f"L{line}", "weight": 1.0}
|
||||
if context:
|
||||
edge["context"] = context
|
||||
edges.append(edge)
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
add_node(file_nid, path.name, 1)
|
||||
|
||||
pair_count = [0]
|
||||
|
||||
def walk(node: Any, parent_nid: str, parent_key: str | None, depth: int) -> None:
|
||||
if depth > _MAX_DEPTH:
|
||||
return
|
||||
if isinstance(node, yaml.MappingNode):
|
||||
for key_str, key_node, val in _mapping_pairs(node):
|
||||
if pair_count[0] >= _MAX_PAIRS:
|
||||
return
|
||||
pair_count[0] += 1
|
||||
if not normalize_id(key_str):
|
||||
continue
|
||||
key_nid = _make_id(stem, *(([parent_key] if parent_key else []) + [key_str]))
|
||||
if not key_nid:
|
||||
continue
|
||||
line = key_node.start_mark.line + 1
|
||||
add_node(key_nid, key_str, line)
|
||||
add_edge(parent_nid, key_nid, "contains", line)
|
||||
if isinstance(val, (yaml.MappingNode, yaml.SequenceNode)):
|
||||
walk(val, key_nid, key_str, depth + 1)
|
||||
elif isinstance(node, yaml.SequenceNode):
|
||||
# Lists of scalars carry no key structure; only recurse into
|
||||
# structured items without minting index nodes (avoids explosion).
|
||||
for item in node.value:
|
||||
if isinstance(item, (yaml.MappingNode, yaml.SequenceNode)):
|
||||
walk(item, parent_nid, parent_key, depth + 1)
|
||||
|
||||
multi = len(config_docs) > 1
|
||||
for index, (doc, tree) in enumerate(config_docs):
|
||||
if multi:
|
||||
# Keep each document of a multi-document stream distinct (a k8s file
|
||||
# holding a Deployment and a Service must not merge their metadata).
|
||||
label = _doc_label(doc, index)
|
||||
doc_nid = _make_id(stem, f"doc{index}", label) or _make_id(stem, f"doc{index}")
|
||||
if not doc_nid:
|
||||
continue
|
||||
doc_line = tree.start_mark.line + 1
|
||||
add_node(doc_nid, label, doc_line)
|
||||
add_edge(file_nid, doc_nid, "contains", doc_line)
|
||||
walk(tree, doc_nid, label, 1)
|
||||
else:
|
||||
walk(tree, file_nid, None, 0)
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
@@ -217,8 +217,14 @@ def extract_zig(path: Path) -> dict:
|
||||
fn_text = _read_text(fn, source)
|
||||
callee = fn_text.split(".")[-1]
|
||||
is_member_call = "." in fn_text
|
||||
tgt_nid = next((n["id"] for n in nodes if n["label"] in
|
||||
(f"{callee}()", f".{callee}()")), None)
|
||||
# A dotted call (`obj.helper()`) names a method, never a free
|
||||
# function; a bare call (`helper()`) names a free function,
|
||||
# never a method. Matching either label for both call shapes
|
||||
# let a bare call cross-resolve onto an unrelated struct's
|
||||
# method of the same name (and vice versa) whenever the two
|
||||
# just happened to coexist in the file.
|
||||
wanted_label = f".{callee}()" if is_member_call else f"{callee}()"
|
||||
tgt_nid = next((n["id"] for n in nodes if n["label"] == wanted_label), None)
|
||||
if tgt_nid and tgt_nid != caller_nid:
|
||||
pair = (caller_nid, tgt_nid)
|
||||
if pair not in seen_call_pairs:
|
||||
|
||||
+23
-5
@@ -32,14 +32,16 @@ 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({
|
||||
".md", ".mdx", ".markdown", ".txt", ".rst",
|
||||
".qmd", ".skill", ".html", ".yaml", ".yml",
|
||||
".qmd", ".skill", ".html",
|
||||
".j2", ".jinja", ".jinja2",
|
||||
})
|
||||
|
||||
@@ -67,6 +69,7 @@ def _pdf_text(path: Path) -> str:
|
||||
# rather than once per slice, and so a file rewritten mid-run is re-read instead
|
||||
# of served a stale body. Bounded: the entries are whole documents, and a large
|
||||
# corpus should not pin all of them in memory.
|
||||
# Resolve the path so relative names in different corpus roots cannot share text.
|
||||
_CONVERTED_TEXT_CACHE: "dict[tuple, str]" = {}
|
||||
_CONVERTED_TEXT_CACHE_MAX = 64
|
||||
|
||||
@@ -82,7 +85,7 @@ def unit_source_text(path: Path) -> str:
|
||||
return _read_source_text(path, warn=False)
|
||||
try:
|
||||
st = path.stat()
|
||||
key = (str(path), st.st_size, st.st_mtime_ns)
|
||||
key = (str(path.resolve()), st.st_size, st.st_mtime_ns)
|
||||
except OSError:
|
||||
return _pdf_text(path)
|
||||
hit = _CONVERTED_TEXT_CACHE.get(key)
|
||||
@@ -247,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):])
|
||||
@@ -29,7 +29,41 @@ def google_workspace_enabled(value: str | None = None) -> bool:
|
||||
|
||||
|
||||
def _safe_yaml_str(value: str) -> str:
|
||||
return value.replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ").replace("\r", " ")
|
||||
"""Escape a value for a YAML double-quoted scalar.
|
||||
|
||||
Same escaping as graphify.ingest._yaml_str (F-009): backslash, quote,
|
||||
tab, NUL and other C0/DEL controls, plus the Unicode line breaks
|
||||
U+2028, U+2029 and U+0085, so a hostile shortcut url or file id cannot
|
||||
break out of the scalar and inject sibling frontmatter keys.
|
||||
"""
|
||||
if value is None:
|
||||
return ""
|
||||
out: list[str] = []
|
||||
for ch in str(value):
|
||||
cp = ord(ch)
|
||||
if ch == "\\":
|
||||
out.append("\\\\")
|
||||
elif ch == '"':
|
||||
out.append('\\"')
|
||||
elif ch == "\n":
|
||||
out.append("\\n")
|
||||
elif ch == "\r":
|
||||
out.append("\\r")
|
||||
elif ch == "\t":
|
||||
out.append("\\t")
|
||||
elif ch == "\0":
|
||||
out.append("\\0")
|
||||
elif cp == 0x2028:
|
||||
out.append("\\L")
|
||||
elif cp == 0x2029:
|
||||
out.append("\\P")
|
||||
elif cp == 0x0085:
|
||||
out.append("\\x85")
|
||||
elif cp < 0x20 or cp == 0x7F:
|
||||
out.append(f"\\x{cp:02x}")
|
||||
else:
|
||||
out.append(ch)
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def _extract_file_id_from_url(url: str) -> str | None:
|
||||
|
||||
+31
-8
@@ -405,14 +405,37 @@ 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
|
||||
"""
|
||||
|
||||
|
||||
# Run the rest of each hook from the checkout's top level, shared by all hooks
|
||||
# and placed right after _WORKTREE_GUARD (it reuses _GFY_GITDIR/_GFY_COMMONDIR).
|
||||
# The rebuild reads graphify-out/ and its .graphify_root relative to the cwd,
|
||||
# but git does not always start hooks at the top: with GIT_DIR exported and no
|
||||
# GIT_WORK_TREE (a nested git call from another hook or tool), git takes the
|
||||
# caller's cwd as the work tree, and `--show-toplevel` echoes that same
|
||||
# subdirectory. A stray graphify-out/ left there by an earlier run then roots the
|
||||
# rebuild at the subdirectory - for .claude/worktrees/ that is every linked
|
||||
# worktree (#3258). In the standard layout the work tree is the parent of the
|
||||
# common .git dir; GIT_WORK_TREE and --separate-git-dir layouts keep git's own
|
||||
# answer. GIT_DIR is rewritten to its absolute form (not newly exported) so the
|
||||
# git calls below still resolve after the cd.
|
||||
_TOPLEVEL_ANCHOR = """\
|
||||
if [ -z "${GIT_WORK_TREE:-}" ] && [ "${_GFY_COMMONDIR##*/}" = ".git" ]; then
|
||||
_GFY_TOP=${_GFY_COMMONDIR%/*}
|
||||
else
|
||||
_GFY_TOP=$(git rev-parse --show-toplevel 2>/dev/null)
|
||||
fi
|
||||
[ -n "$_GFY_TOP" ] && cd "$_GFY_TOP" || exit 0
|
||||
[ -n "$_GFY_GITDIR" ] && GIT_DIR=$_GFY_GITDIR
|
||||
"""
|
||||
|
||||
|
||||
# Both hook bodies run inside a subshell `( ... )`. The generated block is
|
||||
# appended to whatever post-commit / post-checkout already exists, and other
|
||||
# tools chain their own logic after it; every skip condition in the block is a
|
||||
@@ -449,7 +472,7 @@ GIT_DIR=${GIT_DIR:-$(git rev-parse --git-dir 2>/dev/null)}
|
||||
[ -f "$GIT_DIR/MERGE_HEAD" ] && exit 0
|
||||
[ "${GRAPHIFY_SKIP_HOOK:-0}" = "1" ] && exit 0
|
||||
|
||||
""" + _WORKTREE_GUARD + """
|
||||
""" + _WORKTREE_GUARD + _TOPLEVEL_ANCHOR + """
|
||||
# CHERRY_PICK_HEAD can't be the skip signal: git leaves it on disk while post-commit
|
||||
# runs, so every pick was silenced (#4490, same trap as MERGE_HEAD in #4463). For a
|
||||
# range pick or revert, skip every step but the last and rebuild once from
|
||||
@@ -579,7 +602,7 @@ GIT_DIR=${GIT_DIR:-$(git rev-parse --git-dir 2>/dev/null)}
|
||||
# suppressed commit-triggered rebuilds but not branch-switch ones (#1809).
|
||||
[ "${GRAPHIFY_SKIP_HOOK:-0}" = "1" ] && exit 0
|
||||
|
||||
""" + _WORKTREE_GUARD + _PYTHON_DETECT + """
|
||||
""" + _WORKTREE_GUARD + _TOPLEVEL_ANCHOR + _PYTHON_DETECT + """
|
||||
_GRAPHIFY_LOG="${HOME}/.cache/graphify-rebuild.log"
|
||||
mkdir -p "$(dirname "$_GRAPHIFY_LOG")"
|
||||
export GRAPHIFY_REBUILD_LOG="$_GRAPHIFY_LOG"
|
||||
@@ -632,7 +655,7 @@ GIT_DIR=${GIT_DIR:-$(git rev-parse --git-dir 2>/dev/null)}
|
||||
# Honor the same opt out the commit and checkout hooks already respect.
|
||||
[ "${GRAPHIFY_SKIP_HOOK:-0}" = "1" ] && exit 0
|
||||
|
||||
""" + _WORKTREE_GUARD + _PYTHON_DETECT + """
|
||||
""" + _WORKTREE_GUARD + _TOPLEVEL_ANCHOR + _PYTHON_DETECT + """
|
||||
_GRAPHIFY_LOG="${HOME}/.cache/graphify-rebuild.log"
|
||||
mkdir -p "$(dirname "$_GRAPHIFY_LOG")"
|
||||
export GRAPHIFY_REBUILD_LOG="$_GRAPHIFY_LOG"
|
||||
@@ -684,7 +707,7 @@ fi
|
||||
# Honor the same opt out the commit and checkout hooks already respect.
|
||||
[ "${GRAPHIFY_SKIP_HOOK:-0}" = "1" ] && exit 0
|
||||
|
||||
""" + _WORKTREE_GUARD + _PYTHON_DETECT + """
|
||||
""" + _WORKTREE_GUARD + _TOPLEVEL_ANCHOR + _PYTHON_DETECT + """
|
||||
_GRAPHIFY_LOG="${HOME}/.cache/graphify-rebuild.log"
|
||||
mkdir -p "$(dirname "$_GRAPHIFY_LOG")"
|
||||
export GRAPHIFY_REBUILD_LOG="$_GRAPHIFY_LOG"
|
||||
@@ -753,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
|
||||
@@ -815,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,
|
||||
|
||||
+82
-1
@@ -41,10 +41,11 @@ how many times the caller has already casefolded.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
__all__ = ["normalize_id", "make_id"]
|
||||
__all__ = ["normalize_id", "make_id", "decl_salt", "DeclIdRegistry"]
|
||||
|
||||
|
||||
def normalize_id(s: str) -> str:
|
||||
@@ -83,6 +84,86 @@ def normalize_id(s: str) -> str:
|
||||
return cur.strip("_")
|
||||
|
||||
|
||||
def decl_salt(name: str) -> str:
|
||||
"""Stable 12-hex digest appended when a declaration id collides (#4854)."""
|
||||
return hashlib.sha1(
|
||||
name.encode("utf-8", "replace"), usedforsecurity=False
|
||||
).hexdigest()[:12]
|
||||
|
||||
|
||||
class DeclIdRegistry:
|
||||
"""Assign unique ids to declarations in one file.
|
||||
|
||||
Ownership is keyed by the id the declaration would have used, so two
|
||||
declarations whose names normalize alike (``Foo`` / ``_Foo``, or ``Base`` in
|
||||
two namespaces) stay distinct. A reference lookup by name only answers when
|
||||
exactly one declaration in the file spells that name; an ambiguous name
|
||||
keeps the caller's existing fallback.
|
||||
"""
|
||||
|
||||
def __init__(self, reserved_ids=()):
|
||||
self._assigned: dict[tuple[str, str], str] = {}
|
||||
self._owners: dict[str, tuple[str, str]] = {
|
||||
rid: ("file", rid) for rid in reserved_ids
|
||||
}
|
||||
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)
|
||||
owner = self._owners.get(nid)
|
||||
if owner == key:
|
||||
return self._assigned[key]
|
||||
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)
|
||||
if assigned is not None:
|
||||
return assigned
|
||||
# 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). 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 (owner[0] == kind or self._spelled.get(nid) == name)):
|
||||
return nid
|
||||
base = make_id(nid, decl_salt(name))
|
||||
candidate = base
|
||||
counter = 2
|
||||
while candidate in taken or candidate in self._owners:
|
||||
candidate = make_id(base, str(counter))
|
||||
counter += 1
|
||||
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:
|
||||
return next(iter(ids)) if len(ids) == 1 else None
|
||||
return None
|
||||
|
||||
|
||||
def make_id(*parts: str) -> str:
|
||||
"""Build a canonical node ID from one or more name parts.
|
||||
|
||||
|
||||
+39
-17
@@ -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
|
||||
@@ -221,24 +224,51 @@ Source: {url}
|
||||
return content, filename
|
||||
|
||||
|
||||
def _download_binary(url: str, suffix: str, target_dir: Path) -> Path:
|
||||
"""Save a sequential capture without replacing an existing directory entry.
|
||||
def _free_capture_path(target_dir: Path, filename: str) -> Path:
|
||||
"""Pick *filename*, or the first free numbered variant, in *target_dir*.
|
||||
|
||||
Selection and writing are separate; concurrent captures are not atomic.
|
||||
Uses lstat so no existing directory entry is replaced, including a
|
||||
dangling symlink that a write would otherwise follow out of the corpus.
|
||||
The writer still needs an exclusive open to reserve the selected name.
|
||||
"""
|
||||
filename = _safe_filename(url, suffix)
|
||||
stem = Path(filename).stem
|
||||
stem, suffix = Path(filename).stem, Path(filename).suffix
|
||||
out_path = target_dir / filename
|
||||
counter = 1
|
||||
while True:
|
||||
try:
|
||||
out_path.lstat()
|
||||
except FileNotFoundError:
|
||||
break
|
||||
return out_path
|
||||
out_path = target_dir / f"{stem}_{counter}{suffix}"
|
||||
counter += 1
|
||||
out_path.write_bytes(safe_fetch(url))
|
||||
return out_path
|
||||
|
||||
|
||||
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:
|
||||
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:
|
||||
@@ -282,15 +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 = target_dir / filename
|
||||
# Avoid overwriting - append counter if needed
|
||||
counter = 1
|
||||
while out_path.exists() and counter < 1000:
|
||||
stem = Path(filename).stem
|
||||
out_path = target_dir / f"{stem}_{counter}.md"
|
||||
counter += 1
|
||||
|
||||
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
|
||||
|
||||
|
||||
+318
-103
@@ -22,6 +22,7 @@ import re
|
||||
import shutil
|
||||
import stat
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
@@ -149,23 +150,34 @@ def _skill_lock(skill_dir: Path, *, wait: bool = True):
|
||||
def _write_version_stamp(skill_dst: Path, version: str) -> None:
|
||||
"""Atomically write ``.graphify_version`` beside ``skill_dst``.
|
||||
|
||||
Matches the SKILL.md install path: temp file in the same directory, then
|
||||
``os.replace``. Unlike ``Path.write_text`` (and unlike
|
||||
Matches the SKILL.md install path: unique temp file in the same directory,
|
||||
then ``os.replace``. Unlike ``Path.write_text`` (and unlike
|
||||
``paths.write_text_atomic``, which resolves through symlinks), ``os.replace``
|
||||
replaces a managed symlink in place — consistent with SKILL.md /
|
||||
``references/`` and crash-safe against a half-written stamp (#3286).
|
||||
"""
|
||||
version_file = skill_dst.parent / ".graphify_version"
|
||||
tmp = version_file.with_name(".graphify_version.tmp")
|
||||
fd, tmp_name = tempfile.mkstemp(
|
||||
dir=str(skill_dst.parent),
|
||||
prefix=".graphify_version.",
|
||||
suffix=".tmp",
|
||||
)
|
||||
tmp = Path(tmp_name)
|
||||
fd_closed = False
|
||||
try:
|
||||
tmp.write_text(version, encoding="utf-8")
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
||||
fd_closed = True
|
||||
fh.write(version)
|
||||
with contextlib.suppress(OSError):
|
||||
if version_file.exists() and not version_file.is_symlink():
|
||||
os.chmod(tmp, stat.S_IMODE(version_file.stat().st_mode))
|
||||
_os_replace_with_fallback(tmp, version_file)
|
||||
except Exception:
|
||||
try:
|
||||
finally:
|
||||
if not fd_closed:
|
||||
with contextlib.suppress(OSError):
|
||||
os.close(fd)
|
||||
with contextlib.suppress(OSError):
|
||||
tmp.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
@functools.lru_cache(maxsize=None)
|
||||
@@ -196,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":
|
||||
@@ -224,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
|
||||
@@ -280,15 +301,20 @@ def _packaged_skill_refs_dir(platform_name: str) -> Path | None:
|
||||
def _install_skill_references(skill_dst: Path, refs_src: Path) -> None:
|
||||
"""Atomically install a packaged references/ sidecar next to SKILL.md.
|
||||
|
||||
Stages the packaged dir into ``references.tmp`` (copytree), drops any stale
|
||||
``references/`` already on disk, then ``os.replace``-renames the staged dir
|
||||
into place. The rename is atomic on the same filesystem, so an interrupted
|
||||
install never leaves a half-written references/ visible to the agent.
|
||||
Stages the packaged dir into a unique temporary directory (copytree), drops
|
||||
any stale ``references/`` already on disk, then ``os.replace``-renames the
|
||||
staged dir into place. The rename is atomic on the same filesystem, so an
|
||||
interrupted install never leaves a half-written references/ visible to the
|
||||
agent.
|
||||
"""
|
||||
refs_dst = skill_dst.parent / "references"
|
||||
refs_staged = skill_dst.parent / "references.tmp"
|
||||
if refs_staged.exists():
|
||||
shutil.rmtree(refs_staged)
|
||||
legacy_staged = skill_dst.parent / "references.tmp"
|
||||
if not legacy_staged.is_symlink() and legacy_staged.is_dir():
|
||||
shutil.rmtree(legacy_staged, ignore_errors=True)
|
||||
staging_root = Path(
|
||||
tempfile.mkdtemp(dir=str(skill_dst.parent), prefix=".references.", suffix=".tmp")
|
||||
)
|
||||
refs_staged = staging_root / "references"
|
||||
try:
|
||||
shutil.copytree(refs_src, refs_staged)
|
||||
# copytree preserves the source's mode bits, and a packaged bundle can
|
||||
@@ -298,13 +324,17 @@ def _install_skill_references(skill_dst: Path, refs_src: Path) -> None:
|
||||
# below would fail with EACCES. Restore owner-write on the staged copy.
|
||||
for path in (refs_staged, *refs_staged.rglob("*")):
|
||||
path.chmod(path.stat().st_mode | stat.S_IWUSR)
|
||||
if refs_dst.exists():
|
||||
if refs_dst.is_symlink():
|
||||
refs_dst.unlink()
|
||||
elif refs_dst.exists():
|
||||
shutil.rmtree(refs_dst)
|
||||
os.replace(refs_staged, refs_dst)
|
||||
except Exception:
|
||||
if refs_staged.exists():
|
||||
shutil.rmtree(refs_staged, ignore_errors=True)
|
||||
raise
|
||||
finally:
|
||||
if staging_root.is_symlink():
|
||||
with contextlib.suppress(OSError):
|
||||
staging_root.unlink()
|
||||
elif staging_root.exists():
|
||||
shutil.rmtree(staging_root, ignore_errors=True)
|
||||
def _copy_skill_file(platform_name: str, *, project: bool = False, project_dir: Path | None = None) -> Path:
|
||||
"""Copy a packaged skill file and write its version stamp.
|
||||
|
||||
@@ -362,16 +392,26 @@ def _copy_skill_file(platform_name: str, *, project: bool = False, project_dir:
|
||||
except OSError:
|
||||
pass # a failed backup must not block the install
|
||||
# SKILL.md last (crash-safety), via an atomic temp + rename.
|
||||
tmp_dst = skill_dst.with_suffix(skill_dst.suffix + ".tmp")
|
||||
fd, tmp_name = tempfile.mkstemp(
|
||||
dir=str(skill_dst.parent),
|
||||
prefix=f".{skill_dst.name}.",
|
||||
suffix=".tmp",
|
||||
)
|
||||
tmp_dst = Path(tmp_name)
|
||||
fd_closed = False
|
||||
try:
|
||||
shutil.copy(skill_src, tmp_dst)
|
||||
with os.fdopen(fd, "wb") as dst_fh:
|
||||
fd_closed = True
|
||||
with open(skill_src, "rb") as src_fh:
|
||||
shutil.copyfileobj(src_fh, dst_fh)
|
||||
shutil.copymode(skill_src, tmp_dst)
|
||||
_os_replace_with_fallback(tmp_dst, skill_dst)
|
||||
except Exception:
|
||||
try:
|
||||
finally:
|
||||
if not fd_closed:
|
||||
with contextlib.suppress(OSError):
|
||||
os.close(fd)
|
||||
with contextlib.suppress(OSError):
|
||||
tmp_dst.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
_write_version_stamp(skill_dst, __version__)
|
||||
print(f" skill installed -> {skill_dst}")
|
||||
@@ -406,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:
|
||||
@@ -456,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
|
||||
@@ -472,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
|
||||
@@ -979,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)])
|
||||
@@ -996,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"
|
||||
@@ -1023,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"
|
||||
|
||||
@@ -1181,16 +1334,26 @@ def vscode_install(project_dir: Path | None = None) -> None:
|
||||
skill_dst = _vscode_skill_destination()
|
||||
with _skill_lock(skill_dst.parent):
|
||||
skill_dst.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp_dst = skill_dst.with_suffix(skill_dst.suffix + ".tmp")
|
||||
fd, tmp_name = tempfile.mkstemp(
|
||||
dir=str(skill_dst.parent),
|
||||
prefix=f".{skill_dst.name}.",
|
||||
suffix=".tmp",
|
||||
)
|
||||
tmp_dst = Path(tmp_name)
|
||||
fd_closed = False
|
||||
try:
|
||||
shutil.copy(skill_src, tmp_dst)
|
||||
with os.fdopen(fd, "wb") as dst_fh:
|
||||
fd_closed = True
|
||||
with open(skill_src, "rb") as src_fh:
|
||||
shutil.copyfileobj(src_fh, dst_fh)
|
||||
shutil.copymode(skill_src, tmp_dst)
|
||||
_os_replace_with_fallback(tmp_dst, skill_dst)
|
||||
except Exception:
|
||||
try:
|
||||
finally:
|
||||
if not fd_closed:
|
||||
with contextlib.suppress(OSError):
|
||||
os.close(fd)
|
||||
with contextlib.suppress(OSError):
|
||||
tmp_dst.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
# Progressive-capable: install the packaged references/ sidecar when present.
|
||||
refs_src = Path(__file__).parent / "skills" / refs_bundle / "references"
|
||||
if refs_src.exists():
|
||||
@@ -1724,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:
|
||||
@@ -1734,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
|
||||
@@ -1749,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")
|
||||
@@ -1762,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
|
||||
@@ -1780,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.
|
||||
|
||||
@@ -1849,6 +2025,12 @@ def _install_codex_hook(project_dir: Path, project: bool = False) -> None:
|
||||
existing = _read_settings_for_merge(hooks_path)
|
||||
|
||||
graphify_exe = _resolve_graphify_exe(project=project)
|
||||
if " " in graphify_exe and not graphify_exe.startswith('"'):
|
||||
# Mirror _claude_pretooluse_hooks/_gemini_hook: a resolved path with
|
||||
# spaces must be quoted, or every shell that runs the hook command
|
||||
# (Git Bash, cmd.exe, sh) word-splits it at the first space and the
|
||||
# hook can never fire.
|
||||
graphify_exe = f'"{graphify_exe}"'
|
||||
hook_entry = {
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
@@ -1916,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("."))
|
||||
|
||||
@@ -2067,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
|
||||
@@ -2077,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
|
||||
@@ -2091,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]:
|
||||
@@ -2113,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,
|
||||
@@ -2160,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.
|
||||
|
||||
@@ -2180,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.
|
||||
@@ -2196,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:
|
||||
@@ -2261,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
|
||||
@@ -2313,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",
|
||||
@@ -2435,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():
|
||||
|
||||
@@ -18,7 +18,8 @@ implementers the answer is all N, not none. Each implementer is still subject
|
||||
to the single-owner guard `resolve_pascal_inherited_calls` and
|
||||
`resolve_ruby_member_calls` already use: an implementer that itself declares
|
||||
more than one method of the same name is ambiguous and is skipped on its own,
|
||||
independently of its siblings.
|
||||
independently of its siblings, unless the overloads pair up one-to-one by
|
||||
signature or parameter count (C#, #4584).
|
||||
|
||||
The join is per method rather than per call site, so one edge per implementer
|
||||
reconnects every call that reaches the interface method. Confidence is
|
||||
@@ -125,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
|
||||
@@ -168,28 +172,56 @@ def resolve_interface_dispatch(
|
||||
for impl_nid, impl_node in gated_impls:
|
||||
impl_methods = methods_of.get(impl_nid, {})
|
||||
for name, declared in interface_methods.items():
|
||||
if len(declared) != 1:
|
||||
continue
|
||||
# Ambiguity is per implementer: one implementer overloading a
|
||||
# name does not disqualify its siblings from a clean match.
|
||||
candidates = impl_methods.get(name, set())
|
||||
if len(candidates) != 1:
|
||||
continue
|
||||
source = next(iter(declared))
|
||||
target = next(iter(candidates))
|
||||
if source == target or (source, target) in existing_pairs:
|
||||
continue
|
||||
existing_pairs.add((source, target))
|
||||
new_edges.append({
|
||||
"source": source,
|
||||
"target": target,
|
||||
"relation": DISPATCH_RELATION,
|
||||
"context": "call",
|
||||
"confidence": "INFERRED",
|
||||
"confidence_score": score,
|
||||
"source_file": str(impl_node.get("source_file", "")),
|
||||
"source_location": impl_node.get("source_location"),
|
||||
"weight": 1.0,
|
||||
})
|
||||
for source, target in _overload_pairs(
|
||||
declared, impl_methods.get(name, set()), node_by_id
|
||||
):
|
||||
if source == target or (source, target) in existing_pairs:
|
||||
continue
|
||||
existing_pairs.add((source, target))
|
||||
new_edges.append({
|
||||
"source": source,
|
||||
"target": target,
|
||||
"relation": DISPATCH_RELATION,
|
||||
"context": "call",
|
||||
"confidence": "INFERRED",
|
||||
"confidence_score": score,
|
||||
"source_file": str(impl_node.get("source_file", "")),
|
||||
"source_location": impl_node.get("source_location"),
|
||||
"weight": 1.0,
|
||||
})
|
||||
|
||||
all_edges.extend(new_edges)
|
||||
|
||||
|
||||
def _overload_pairs(
|
||||
declared: set[str], candidates: set[str], node_by_id: dict
|
||||
) -> list[tuple[str, str]]:
|
||||
"""Pair an interface's methods of one name with an implementer's.
|
||||
|
||||
One of each pairs up as always. Otherwise (C# overloads, #4584) each
|
||||
interface method pairs with the one implementer method of the same declared
|
||||
signature, else of the same parameter count among those no signature
|
||||
claimed; no unique match, no edge. An implementer method takes at most one
|
||||
interface method, so an overload implemented on a base class is not pinned
|
||||
on a sibling of the same count.
|
||||
"""
|
||||
if len(declared) == 1 and len(candidates) == 1:
|
||||
return [(next(iter(declared)), next(iter(candidates)))]
|
||||
|
||||
def _meta(nid: str) -> dict:
|
||||
meta = (node_by_id.get(nid) or {}).get("metadata")
|
||||
return meta if isinstance(meta, dict) else {}
|
||||
|
||||
pairs: dict[str, str] = {}
|
||||
for key in ("signature", "arity"):
|
||||
taken = set(pairs.values())
|
||||
for source in sorted(declared):
|
||||
want = _meta(source).get(key)
|
||||
if source in pairs or want is None:
|
||||
continue
|
||||
hits = [c for c in candidates if c not in taken and _meta(c).get(key) == want]
|
||||
if len(hits) == 1:
|
||||
pairs[source] = hits[0]
|
||||
# Two interface methods on one implementer method: neither is certain.
|
||||
targets = list(pairs.values())
|
||||
return [(s, t) for s, t in pairs.items() if targets.count(t) == 1]
|
||||
+193
-28
@@ -22,6 +22,7 @@ from graphify.file_slice import (
|
||||
FileSlice,
|
||||
bisect_slice,
|
||||
expand_oversized_files,
|
||||
make_full_slice,
|
||||
read_slice_text,
|
||||
unit_path,
|
||||
)
|
||||
@@ -61,6 +62,21 @@ def _get_tokenizer():
|
||||
# Cached at import time. None if tiktoken is unavailable; consumers must handle.
|
||||
_TOKENIZER = _get_tokenizer()
|
||||
|
||||
# Anything past Latin Extended (CJK, Devanagari, Cyrillic, Arabic, ...).
|
||||
_NON_LATIN_RE = re.compile(r"[^\u0000-ɏ]")
|
||||
|
||||
|
||||
def _estimate_prompt_tokens(text: str) -> int:
|
||||
"""Rough token count for sizing a local model's context window.
|
||||
|
||||
chars/4 holds for English and code but not other scripts: on qwen2.5 a
|
||||
Chinese doc came out 2.8x larger than chars/4 and a Hindi one 3.7x, so
|
||||
num_ctx was too small and Ollama cut the prompt. Count non-Latin
|
||||
characters as one token each, which errs on the safe side for both.
|
||||
"""
|
||||
non_latin = len(_NON_LATIN_RE.findall(text))
|
||||
return (len(text) - non_latin) // _CHARS_PER_TOKEN + non_latin
|
||||
|
||||
|
||||
def _resolve_ollama_base_url(default: str) -> str:
|
||||
"""Resolve the Ollama base URL. Honors an explicit OLLAMA_BASE_URL first
|
||||
@@ -342,6 +358,41 @@ def _resolve_max_tokens(default: int) -> int:
|
||||
return default
|
||||
|
||||
|
||||
def _openai_max_tokens_kwarg(backend: str, max_tokens: int) -> dict[str, int]:
|
||||
"""Map the output cap to the OpenAI-compatible field accepted by the backend."""
|
||||
# DeepSeek documents max_tokens and ignores max_completion_tokens.
|
||||
key = "max_tokens" if backend == "deepseek" else "max_completion_tokens"
|
||||
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."
|
||||
@@ -525,9 +576,12 @@ source (a markdown or wiki link, a backticked path, a "Source:" or "Related:"
|
||||
line, a module or class a design doc specifies) is a reference, not the source:
|
||||
never use its path as source_file. Model the referenced file or entity as a node
|
||||
attributed to the enclosing file and link to it with a `references` or `cites`
|
||||
edge. Never invent, shorten or rewrite a path, and never omit source_file.
|
||||
edge. Add `"metadata":{"graphify_reference_stub":true}` to every node created
|
||||
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:
|
||||
@@ -792,7 +846,16 @@ def _bind_node_evidence(result: dict, text_units: "list[Path | FileSlice]", root
|
||||
# No evidence. Flag only a node the model itself presented as solid
|
||||
# (EXTRACTED/unset) — one it already hedged (INFERRED/AMBIGUOUS) needs no
|
||||
# second flag. Idempotent: never overwrites an existing verification.
|
||||
if n.get("confidence") in (None, "", "EXTRACTED") and not n.get(_VERIFICATION_FIELD):
|
||||
# Matched case-insensitively, the way build._fold_confidence (#4529)
|
||||
# reads it: a mis-cased enum value IS that enum value there and is
|
||||
# corrected to the canonical spelling, so a node the model wrote as
|
||||
# `"extracted"` reaches graph.json just as solid as `"EXTRACTED"` and
|
||||
# must be evidence-checked the same. A hedged spelling in any case
|
||||
# ("inferred", "ambiguous") still falls through unflagged.
|
||||
_conf = n.get("confidence")
|
||||
if isinstance(_conf, str):
|
||||
_conf = _conf.upper()
|
||||
if _conf in (None, "", "EXTRACTED") and not n.get(_VERIFICATION_FIELD):
|
||||
n[_VERIFICATION_FIELD] = _UNVERIFIED_VALUE
|
||||
downgraded += 1
|
||||
return downgraded
|
||||
@@ -1392,7 +1455,8 @@ def _backend_pkg_hint(pkg: str, extra: str) -> str:
|
||||
)
|
||||
|
||||
|
||||
def _ollama_request_extras(user_message: str, max_completion_tokens: int) -> dict:
|
||||
def _ollama_request_extras(user_message: str, max_completion_tokens: int,
|
||||
system_prompt: str = "") -> dict:
|
||||
"""num_ctx/keep_alive for an Ollama request, sized to the prompt."""
|
||||
# Ollama defaults num_ctx to 2048 and silently truncates prompts larger
|
||||
# than that — the symptom is hollow 200 OK responses after the first few
|
||||
@@ -1400,12 +1464,14 @@ def _ollama_request_extras(user_message: str, max_completion_tokens: int) -> dic
|
||||
# over-allocate KV-cache VRAM. Over-allocation (e.g. 128k slots for an 8k
|
||||
# prompt on a 31B model) exhausts VRAM by chunk 4 and produces the same
|
||||
# hollow-200 symptom — just from a different direction (#798 follow-up).
|
||||
# Formula: actual input tokens + output cap + system prompt headroom.
|
||||
# Formula: input tokens (user message + system prompt) + output cap + margin.
|
||||
# Capped at 131072 (enough for the default 60k token_budget); env var wins.
|
||||
num_ctx_raw = os.environ.get("GRAPHIFY_OLLAMA_NUM_CTX", "").strip()
|
||||
# Auto-derive num_ctx from actual chunk size regardless — used as the
|
||||
# fallback and for the mismatch check below.
|
||||
estimated_input = len(user_message) // _CHARS_PER_TOKEN + 400
|
||||
# The system prompt is measured rather than assumed: a flat 400 was short
|
||||
# of the ~760 tokens the extraction prompt really takes.
|
||||
estimated_input = _estimate_prompt_tokens(user_message) + _estimate_prompt_tokens(system_prompt)
|
||||
auto_num_ctx = min(estimated_input + max_completion_tokens + 2000, 131072)
|
||||
auto_num_ctx = max(auto_num_ctx, 8192)
|
||||
if num_ctx_raw:
|
||||
@@ -1432,8 +1498,6 @@ def _ollama_request_extras(user_message: str, max_completion_tokens: int) -> dic
|
||||
file=sys.stderr,
|
||||
)
|
||||
else:
|
||||
# Estimate input tokens: user_message chars / 4 (standard BPE
|
||||
# heuristic) + 400 for the system prompt, then add output headroom.
|
||||
num_ctx = auto_num_ctx
|
||||
keep_alive = os.environ.get("GRAPHIFY_OLLAMA_KEEP_ALIVE", "30m")
|
||||
return {"options": {"num_ctx": num_ctx}, "keep_alive": keep_alive}
|
||||
@@ -1522,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
|
||||
@@ -1547,14 +1612,15 @@ 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": [
|
||||
{"role": "system", "content": _extraction_system(deep=deep_mode)},
|
||||
{"role": "user", "content": _openai_content(user_message, images or [])},
|
||||
],
|
||||
"max_completion_tokens": max_completion_tokens,
|
||||
**_openai_max_tokens_kwarg(backend, max_completion_tokens),
|
||||
"stream": False,
|
||||
}
|
||||
if temperature is not None:
|
||||
@@ -1583,7 +1649,8 @@ def _call_openai_compat(
|
||||
# above, and replacing it here made the flag silently inert on ollama (#3988).
|
||||
kwargs["extra_body"] = {
|
||||
**kwargs.get("extra_body", {}),
|
||||
**_ollama_request_extras(user_message, max_completion_tokens),
|
||||
**_ollama_request_extras(user_message, max_completion_tokens,
|
||||
kwargs["messages"][0]["content"]),
|
||||
}
|
||||
native = None
|
||||
if backend == "ollama" and extra_body is None:
|
||||
@@ -1629,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:
|
||||
@@ -1636,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"],
|
||||
@@ -1645,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
|
||||
@@ -2178,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
|
||||
@@ -2513,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:
|
||||
@@ -2772,6 +2873,9 @@ def extract_corpus_parallel(
|
||||
"failed_chunks": 0, # count of chunks that raised — loud failure on chunk errors
|
||||
}
|
||||
total = len(chunks)
|
||||
# Files whose chunk raised before returning a response. The #1890
|
||||
# reconciliation below must not describe them as omitted by the model (#3616).
|
||||
failed_files: set[Path] = set()
|
||||
|
||||
def _run_one(idx: int, chunk: list[Path]) -> tuple[int, dict | None, Exception | None]:
|
||||
t0 = time.time()
|
||||
@@ -2799,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
|
||||
@@ -2819,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).
|
||||
@@ -2853,10 +2988,11 @@ def extract_corpus_parallel(
|
||||
if exc is not None:
|
||||
print(f"[graphify] chunk {idx + 1}/{total} failed: {exc}", file=sys.stderr)
|
||||
merged["failed_chunks"] += 1
|
||||
failed_files.update(unit_path(f) for f in chunk)
|
||||
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:
|
||||
@@ -2878,15 +3014,28 @@ def extract_corpus_parallel(
|
||||
file=sys.stderr,
|
||||
)
|
||||
merged["failed_chunks"] += 1
|
||||
failed_files.update(unit_path(f) for f in chunks[idx])
|
||||
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.
|
||||
@@ -2991,11 +3140,25 @@ def extract_corpus_parallel(
|
||||
)
|
||||
merged["uncovered_files"] = [str(p) for p in uncovered]
|
||||
_stamp_semantic_origin(merged)
|
||||
if uncovered:
|
||||
shown = ", ".join(p.name for p in uncovered[:5])
|
||||
more = f" (+{len(uncovered) - 5} more)" if len(uncovered) > 5 else ""
|
||||
# Split the gap by cause (#3616): a file whose chunk raised never got a
|
||||
# response, so only the rest were actually omitted by the model.
|
||||
unanswered = [p for p in uncovered if p in failed_files]
|
||||
omitted = [p for p in uncovered if p not in failed_files]
|
||||
if unanswered:
|
||||
shown = ", ".join(p.name for p in unanswered[:5])
|
||||
more = f" (+{len(unanswered) - 5} more)" if len(unanswered) > 5 else ""
|
||||
print(
|
||||
f"[graphify] WARNING: {len(uncovered)}/{len(dispatched)} dispatched file(s) "
|
||||
f"[graphify] WARNING: {len(unanswered)}/{len(dispatched)} dispatched file(s) "
|
||||
f"produced no nodes and are absent from the graph: {shown}{more}. Their "
|
||||
"chunk failed before returning a response (see errors above); a re-run "
|
||||
"will retry them.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
if omitted:
|
||||
shown = ", ".join(p.name for p in omitted[:5])
|
||||
more = f" (+{len(omitted) - 5} more)" if len(omitted) > 5 else ""
|
||||
print(
|
||||
f"[graphify] WARNING: {len(omitted)}/{len(dispatched)} dispatched file(s) "
|
||||
f"produced no nodes and are absent from the graph: {shown}{more}. The model "
|
||||
"returned a response but omitted them; a re-run will retry them.",
|
||||
file=sys.stderr,
|
||||
@@ -3205,11 +3368,13 @@ 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}],
|
||||
"max_completion_tokens": max_tokens,
|
||||
**_openai_max_tokens_kwarg(backend, max_tokens),
|
||||
# Force a single non-streamed response: some OpenAI-compatible gateways
|
||||
# default to SSE streaming when `stream` is omitted, but the result here
|
||||
# is always read as resp.choices[0]. Same fix as _call_openai_compat
|
||||
|
||||
@@ -320,7 +320,10 @@ def _parse_pom(text: str) -> dict | None:
|
||||
version = _resolve(version)
|
||||
name = f"{gid}:{aid}" if gid else aid
|
||||
deps: list[str] = []
|
||||
for dep in root.findall(".//dependencies/dependency"):
|
||||
# Only the project's own <dependencies> (and those of its profiles) are
|
||||
# dependencies. <dependencyManagement> only pins versions, and a plugin's
|
||||
# <dependencies> belong to the build tool.
|
||||
for dep in root.findall("dependencies/dependency") + root.findall("profiles/profile/dependencies/dependency"):
|
||||
da = _resolve(dep.findtext("artifactId"))
|
||||
dg = _resolve(dep.findtext("groupId"))
|
||||
if da:
|
||||
|
||||
+332
-19
@@ -31,6 +31,15 @@ to the code node that defines it:
|
||||
source path: ``time.sleep`` never lands on a repo's own ``sleep``, and
|
||||
``Widget.render`` picks the ``render`` that ``Widget`` owns. No other
|
||||
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 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
|
||||
@@ -44,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"})
|
||||
|
||||
@@ -62,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", ""))
|
||||
@@ -91,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.
|
||||
@@ -142,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)
|
||||
@@ -190,34 +323,156 @@ def resolve_markdown_mentions(
|
||||
candidates = narrowed
|
||||
return candidates[0] if len(candidates) == 1 else None
|
||||
|
||||
for rc in mentions:
|
||||
caller = str(rc.get("caller_nid", ""))
|
||||
callee = str(rc.get("callee", "")).strip()
|
||||
if not caller or not callee or caller not in node_ids:
|
||||
continue
|
||||
names = list(rc.get("qualifiers") or []) + [callee]
|
||||
def _target(rc: dict) -> tuple[str | None, str, float]:
|
||||
"""The node a mention resolves to, plus the confidence of that match."""
|
||||
names = list(rc.get("qualifiers") or []) + [str(rc.get("callee", "")).strip()]
|
||||
cited = rc.get("path")
|
||||
if cited:
|
||||
source_file = _match_cited_file(
|
||||
str(cited), _posix(str(rc.get("source_file", ""))), source_files
|
||||
)
|
||||
if source_file is None:
|
||||
continue
|
||||
target = _resolve_chain(by_file[source_file], names)
|
||||
confidence, score = "EXTRACTED", 1.0
|
||||
return None, "EXTRACTED", 1.0
|
||||
return _resolve_chain(by_file[source_file], names), "EXTRACTED", 1.0
|
||||
callee = names[-1]
|
||||
# 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_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:
|
||||
"""The class that owns *node_id*, when it is a method and not a function."""
|
||||
for parent in parents.get(node_id, ()):
|
||||
node = nodes_by_id.get(parent)
|
||||
if node is not None and node.get("_callable_class"):
|
||||
return parent
|
||||
return None
|
||||
|
||||
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:
|
||||
if callee in _LANGUAGE_BUILTIN_GLOBALS:
|
||||
continue
|
||||
qualifiers = set(names[:-1])
|
||||
candidates = [
|
||||
c for c in by_label.get(callee, [])
|
||||
if qualifiers <= _evidence(c, nodes_by_id, parents)
|
||||
]
|
||||
target = candidates[0] if len(candidates) == 1 else None
|
||||
confidence, score = "INFERRED", 0.95
|
||||
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
|
||||
if (caller, target) in existing:
|
||||
# Retain target as section-scoped citation evidence (#4609, #4804).
|
||||
cited_targets.setdefault(caller, set()).add(target)
|
||||
return
|
||||
existing.add((caller, target))
|
||||
all_edges.append({
|
||||
"source": caller,
|
||||
"target": target,
|
||||
@@ -229,3 +484,61 @@ def resolve_markdown_mentions(
|
||||
"source_location": rc.get("source_location"),
|
||||
"weight": 1.0,
|
||||
})
|
||||
cited_targets.setdefault(caller, set()).add(target)
|
||||
|
||||
# Pass 1: explicit evidence resolves directly (path, dotted chain, or trailing ()).
|
||||
bare: list[dict] = []
|
||||
for rc in mentions:
|
||||
caller = str(rc.get("caller_nid", ""))
|
||||
callee = str(rc.get("callee", "")).strip()
|
||||
if not caller or not callee or caller not in node_ids:
|
||||
continue
|
||||
names = list(rc.get("qualifiers") or []) + [callee]
|
||||
span = str(rc.get("context") or "")
|
||||
if rc.get("path") or len(names) > 1 or "(" in span:
|
||||
_add(rc, *_target(rc))
|
||||
else:
|
||||
bare.append(rc)
|
||||
|
||||
# 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 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 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)
|
||||
+62
-7
@@ -53,6 +53,34 @@ def _out_from_env() -> str:
|
||||
GRAPHIFY_OUT = _out_from_env()
|
||||
|
||||
|
||||
def os_long_path(path: "str | Path") -> str:
|
||||
r"""Return an OS path string safe for open()/stat() on Windows long paths.
|
||||
|
||||
On win32, paths longer than the legacy MAX_PATH (260 chars) are rejected by
|
||||
the plain file APIs unless prefixed with the extended-length marker ``\\?\``
|
||||
(which also requires a fully-qualified path). Without it, _md5_file /
|
||||
save_manifest / count_words silently fail to hash deeply-nested files, so
|
||||
their manifest entry never stabilizes and detect_incremental re-flags them
|
||||
as changed on every run (#1655), and cache entries under a deep root cannot
|
||||
be written at all. cache._normalize_path strips this prefix for stable
|
||||
KEYS; this adds it for I/O. Non-win32 and already-prefixed paths pass
|
||||
through unchanged.
|
||||
"""
|
||||
if sys.platform != "win32":
|
||||
return str(path)
|
||||
s = str(path)
|
||||
if s.startswith("\\\\?\\"):
|
||||
return s
|
||||
try:
|
||||
s = os.path.abspath(s) # \\?\ requires a fully-qualified path
|
||||
except Exception:
|
||||
return str(path)
|
||||
if s.startswith("\\\\"):
|
||||
# UNC share \\server\share -> \\?\UNC\server\share
|
||||
return "\\\\?\\UNC\\" + s[2:]
|
||||
return "\\\\?\\" + s
|
||||
|
||||
|
||||
def os_replace_with_fallback(src: "str | Path", dst: "str | Path") -> None:
|
||||
"""``os.replace(src, dst)``, falling back to a copy for a known set of
|
||||
Windows quirks (#3508) that raise even when ``src``/``dst`` are the same
|
||||
@@ -543,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.
|
||||
|
||||
@@ -578,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")
|
||||
+9
-1
@@ -186,6 +186,14 @@ def _detect_default_branch(repo: str | None = None) -> str:
|
||||
|
||||
_CI_FAILURE_CONCLUSIONS = frozenset({"FAILURE", "CANCELLED", "TIMED_OUT", "ACTION_REQUIRED", "STARTUP_FAILURE"})
|
||||
|
||||
# CheckStatusState has six values: REQUESTED, QUEUED, IN_PROGRESS, COMPLETED,
|
||||
# WAITING and PENDING. Every one but COMPLETED means the run has not finished,
|
||||
# so it carries no conclusion yet and nothing else in the rollup speaks for it.
|
||||
# Matching only IN_PROGRESS/QUEUED left WAITING (a job held by a deployment
|
||||
# protection rule), REQUESTED and PENDING runs invisible — NONE on their own,
|
||||
# and masked as SUCCESS by any sibling check that had already passed.
|
||||
_CI_PENDING_STATUSES = frozenset({"REQUESTED", "QUEUED", "IN_PROGRESS", "WAITING", "PENDING"})
|
||||
|
||||
|
||||
def _parse_ci(rollup: list) -> str:
|
||||
if not rollup:
|
||||
@@ -198,7 +206,7 @@ def _parse_ci(rollup: list) -> str:
|
||||
if conclusions & (_CI_FAILURE_CONCLUSIONS | {"ERROR"}):
|
||||
return "FAILURE"
|
||||
statuses = {r.get("status") for r in rollup}
|
||||
if "IN_PROGRESS" in statuses or "QUEUED" in statuses or conclusions & {"PENDING", "EXPECTED"}:
|
||||
if statuses & _CI_PENDING_STATUSES or conclusions & {"PENDING", "EXPECTED"}:
|
||||
return "PENDING"
|
||||
if "SUCCESS" in conclusions:
|
||||
return "SUCCESS"
|
||||
|
||||
Loaded 100 of 479 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user