Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d89ec68af9 | ||
|
|
9e7fbcbd6e | ||
|
|
6e97088493 | ||
|
|
1256d65214 | ||
|
|
44c0a5e33c | ||
|
|
b70a6d7126 | ||
|
|
5190a4ede9 | ||
|
|
f4a7994926 | ||
|
|
ad7015262b | ||
|
|
21bcb436b5 | ||
|
|
bb5e5192df | ||
|
|
51f805e953 | ||
|
|
cd3a376030 | ||
|
|
a129ff2cd6 | ||
|
|
67b4525f32 | ||
|
|
784e9c833e | ||
|
|
532a20e775 | ||
|
|
297075c3f3 | ||
|
|
7eb847bcf7 | ||
|
|
984a6a8f0a | ||
|
|
7e24c3b7e4 | ||
|
|
674184d462 | ||
|
|
b8f41c77eb | ||
|
|
f2ea6a6087 | ||
|
|
8127ff9a9c | ||
|
|
e34e27c24c | ||
|
|
b7f88afc30 | ||
|
|
de7d362537 | ||
|
|
6eb7c014f4 | ||
|
|
64a6093376 | ||
|
|
a19b9e90ec | ||
|
|
879c05894d | ||
|
|
5320aa8eb1 | ||
|
|
4a8d6bad97 | ||
|
|
93e8e445dd | ||
|
|
20547c4767 | ||
|
|
1aab291caf | ||
|
|
8fdbf50197 | ||
|
|
4f40967e8d | ||
|
|
69b3997386 | ||
|
|
311e63a7fc | ||
|
|
47033c8b75 | ||
|
|
6dc1cb0dd7 | ||
|
|
8288829613 | ||
|
|
cf747abeaf | ||
|
|
19e7a31343 | ||
|
|
0c551ace36 | ||
|
|
b9d8067d0a | ||
|
|
49252d3cb7 | ||
|
|
3bc3feed54 | ||
|
|
bee3849810 | ||
|
|
bd885cc97d | ||
|
|
c865a3c9b0 | ||
|
|
2cdc212b43 | ||
|
|
00e00a0b5f | ||
|
|
5779767fd3 | ||
|
|
0792b419fc | ||
|
|
1801da0634 | ||
|
|
c8c604d08c | ||
|
|
57469641cd | ||
|
|
544f95efa6 | ||
|
|
1d8d278f9e | ||
|
|
51fc00a30f | ||
|
|
1652dadd60 | ||
|
|
e8dabadeb0 | ||
|
|
7a9cda2452 | ||
|
|
2133539930 | ||
|
|
36b5e5cb29 | ||
|
|
738c9cebcb | ||
|
|
e3e4198038 | ||
|
|
407a7f142d | ||
|
|
4e4935a64a | ||
|
|
86ecb769b6 | ||
|
|
12193a89f1 | ||
|
|
199061207f | ||
|
|
b7e256f779 | ||
|
|
0ca73bd00b | ||
|
|
64c1f21070 | ||
|
|
22a5afb251 | ||
|
|
981e2b93cf | ||
|
|
35fb437365 | ||
|
|
0080d8ac43 | ||
|
|
faa9218907 | ||
|
|
67d8c53ccc | ||
|
|
8b9a99828a | ||
|
|
d177f04270 | ||
|
|
afa4aded2e | ||
|
|
94e5bafc89 | ||
|
|
92e682f1de | ||
|
|
73710d33ce | ||
|
|
3999dbc67e | ||
|
|
388d1b64db | ||
|
|
b46634ef7a | ||
|
|
21a9f1f0b5 | ||
|
|
f7f89d7d84 | ||
|
|
7592244386 | ||
|
|
8e98b916f4 | ||
|
|
8b177cb33d | ||
|
|
0e8d92cf5f | ||
|
|
1f3f1c1ca6 | ||
|
|
940cb53f4d | ||
|
|
1b994965bb | ||
|
|
11dc819c3f | ||
|
|
1225677b8a | ||
|
|
6a45263bc0 | ||
|
|
6509d0ca6f | ||
|
|
76b6eabdb0 | ||
|
|
36b76ce8e0 | ||
|
|
b17e88cc49 | ||
|
|
a16b5bd151 | ||
|
|
652ba42e61 | ||
|
|
7a94f72779 | ||
|
|
ff47316b8a | ||
|
|
9b49bfd9eb | ||
|
|
31b3752902 | ||
|
|
8994b5500c | ||
|
|
905e0a7a2e | ||
|
|
349465b8af | ||
|
|
75a5e6d5ff | ||
|
|
9b583a0dd5 | ||
|
|
1e3270a374 | ||
|
|
7dc5d968a3 | ||
|
|
68dba89a99 | ||
|
|
7278e24d8a | ||
|
|
5d63aad596 | ||
|
|
e4ff54f4e0 | ||
|
|
6d3c9594e3 | ||
|
|
bc362cbb74 | ||
|
|
f9ded63350 | ||
|
|
ec6b397ee8 | ||
|
|
a95a8339ca | ||
|
|
b3ab221762 | ||
|
|
22a58ffc20 | ||
|
|
1a14e94e53 | ||
|
|
d193b6277d | ||
|
|
c06db05351 | ||
|
|
f87011b38e | ||
|
|
6d9617a44f | ||
|
|
89dd00f140 | ||
|
|
533859dc51 | ||
|
|
b448c16cbd | ||
|
|
c390456c6c | ||
|
|
2c7cbb6530 | ||
|
|
ad6cb753c0 | ||
|
|
29fd98fd04 | ||
|
|
87fe887919 | ||
|
|
e7ba16bfa3 | ||
|
|
53edd27e6a | ||
|
|
a4d09aefd8 | ||
|
|
0aeda15c10 | ||
|
|
739230e17a | ||
|
|
30cc4c0670 | ||
|
|
0b96b61609 | ||
|
|
dbce4532f4 | ||
|
|
2323ce1937 | ||
|
|
aa06e10fa5 | ||
|
|
5862bce5ca | ||
|
|
aad3b47098 | ||
|
|
b8dc31f760 | ||
|
|
6954a28da8 | ||
|
|
1f42a2da2b | ||
|
|
d168de999a | ||
|
|
5d053721ab | ||
|
|
dce54a007e | ||
|
|
382b669481 | ||
|
|
30fe8bab61 | ||
|
|
7d07a24708 | ||
|
|
435da06c70 | ||
|
|
8e6ba9d714 | ||
|
|
a78956424d | ||
|
|
e6eaad3d7e | ||
|
|
5038129c7e | ||
|
|
8883991c2e | ||
|
|
ab1e0ec588 | ||
|
|
9e8fa2a28c | ||
|
|
baf2410f08 | ||
|
|
d12eb28c2d | ||
|
|
4f539e729f | ||
|
|
897483fc96 | ||
|
|
895a60f4e3 | ||
|
|
b2a1722903 | ||
|
|
9e0b8766f4 | ||
|
|
c9f2ef5e48 | ||
|
|
5b0c154828 | ||
|
|
e9f8dde7af | ||
|
|
5b988974ca | ||
|
|
8437ef465e | ||
|
|
9c8bd4d47c | ||
|
|
2c662c7917 | ||
|
|
2e01f37c81 | ||
|
|
d8fa70e17b | ||
|
|
fd463deb03 | ||
|
|
f117aaccc6 | ||
|
|
a16b3e1b45 | ||
|
|
9a7dbfbb84 | ||
|
|
d885833112 | ||
|
|
be3dcfca08 | ||
|
|
2100b3d05b | ||
|
|
4fbb33301c | ||
|
|
fd152add64 | ||
|
|
adb52a1ea0 | ||
|
|
09da5294e4 | ||
|
|
61836ce0e8 | ||
|
|
fd470faeee | ||
|
|
a4f3e862b2 | ||
|
|
85de47e121 | ||
|
|
b61c985c12 | ||
|
|
591cc934a7 | ||
|
|
9bed8318c6 | ||
|
|
10655b92eb | ||
|
|
b83086297f | ||
|
|
813db19252 | ||
|
|
dbbf0a45a1 | ||
|
|
0f6d46f822 | ||
|
|
c4689a2f47 | ||
|
|
a7c69808ac | ||
|
|
3929eca450 | ||
|
|
70a1ad7278 | ||
|
|
70380b8ea0 | ||
|
|
3e8cd7da6d | ||
|
|
418fab8e23 | ||
|
|
6c2f273742 | ||
|
|
5a21685bf1 | ||
|
|
fb1908cc55 | ||
|
|
90decbc4ed | ||
|
|
0ff84d8bf3 | ||
|
|
c4d6b412ca | ||
|
|
b304331d24 | ||
|
|
0e74c0401e | ||
|
|
2ab2302112 | ||
|
|
1bb30fcc56 | ||
|
|
b739cf2fda | ||
|
|
3a47091021 | ||
|
|
6dc23db90f | ||
|
|
d276a5aa57 | ||
|
|
60d4b4373f | ||
|
|
e16c1f37bf | ||
|
|
b87329496f | ||
|
|
0be4e81047 | ||
|
|
b7b59ca9ea | ||
|
|
5b60624acd | ||
|
|
3ea6def727 | ||
|
|
b34902b8d7 | ||
|
|
e364f72fd8 | ||
|
|
556cab3c2c | ||
|
|
2117983b87 | ||
|
|
e8ab8f4172 | ||
|
|
b56a415388 | ||
|
|
ec04152a90 | ||
|
|
b525549a24 | ||
|
|
96585badd0 | ||
|
|
58efcebd83 | ||
|
|
cce2673021 | ||
|
|
d26a32a30c | ||
|
|
7b5e625066 | ||
|
|
8401c50178 | ||
|
|
444d73e1c8 | ||
|
|
4f8de1e42b | ||
|
|
7cb5e86fc1 | ||
|
|
edfe5812f7 | ||
|
|
565026d3d1 | ||
|
|
ba1921fe76 | ||
|
|
e6d2dc4d6f | ||
|
|
1513e6271a | ||
|
|
7182b18c35 | ||
|
|
a37672f25f | ||
|
|
5504c84324 | ||
|
|
6695f0aefd | ||
|
|
39afb2d8ef | ||
|
|
524289fb66 | ||
|
|
6f6d74d42d | ||
|
|
137bc2d951 | ||
|
|
e477825a97 | ||
|
|
3602c8031e | ||
|
|
7477b469ee | ||
|
|
418604f32a | ||
|
|
12615226e4 | ||
|
|
bf0ace1759 | ||
|
|
29e57cd295 | ||
|
|
42d1b8d02f | ||
|
|
8a04560bf5 | ||
|
|
6dbcb89f3d | ||
|
|
660d2d32cf | ||
|
|
9e1ad425a9 | ||
|
|
12a9b5e812 | ||
|
|
7aa300709f | ||
|
|
3744e6e220 | ||
|
|
6a549e42d5 | ||
|
|
a8dbbe59cf | ||
|
|
f146be3ea2 | ||
|
|
3e8afc9192 | ||
|
|
1ad47ec05e | ||
|
|
079b34da78 | ||
|
|
7467c1b6a4 | ||
|
|
7b4c8df6e9 | ||
|
|
2a683aac2e | ||
|
|
4b06fd7bf7 | ||
|
|
a380b34739 | ||
|
|
3405c1fb96 | ||
|
|
ec1a3bc9e9 | ||
|
|
23acb41910 | ||
|
|
e3499e069c | ||
|
|
9c2f2f5663 | ||
|
|
f85339bcb1 | ||
|
|
3a4bdf54cc | ||
|
|
6e860e018a | ||
|
|
b368c0eb25 | ||
|
|
78e70ea194 | ||
|
|
30f6f6fb85 | ||
|
|
200edecea5 | ||
|
|
fff1c980ac | ||
|
|
75c4de7759 | ||
|
|
830f0396d8 | ||
|
|
863f0c1e9f | ||
|
|
7a588fb1d2 | ||
|
|
b7a9b8158c | ||
|
|
3a90ac2784 | ||
|
|
25df580061 | ||
|
|
0fdfdedcaa | ||
|
|
2d5a10c0a2 | ||
|
|
88bb1864aa | ||
|
|
1b21368250 | ||
|
|
724f1e3186 | ||
|
|
cb5e701c67 | ||
|
|
631a6d4a67 | ||
|
|
250834a0c4 | ||
|
|
5cc7ec8a23 | ||
|
|
9a298c5a32 | ||
|
|
345e1122d3 | ||
|
|
90286ab735 | ||
|
|
d5d49f3764 | ||
|
|
763b673350 | ||
|
|
46a1d4cabb | ||
|
|
c50ffc2285 | ||
|
|
e3993e4801 | ||
|
|
4a200159af | ||
|
|
e35b0aca2a | ||
|
|
4806c1ee7e | ||
|
|
097b50a5d1 | ||
|
|
adfe8f0794 | ||
|
|
6137cdba43 | ||
|
|
fbe1e9977f | ||
|
|
47042beb05 | ||
|
|
6a3b9e146d | ||
|
|
efda79a3b1 | ||
|
|
f5f3a1cc59 | ||
|
|
1d4e11226f | ||
|
|
ec3cb5eb3e | ||
|
|
a8005c218a | ||
|
|
4b17f199af | ||
|
|
1dc5048b71 | ||
|
|
3922235eba | ||
|
|
c8b329d8f2 | ||
|
|
ad0c8c0a62 | ||
|
|
88a8e3bc91 | ||
|
|
690b4e5d3e | ||
|
|
c898dc62cd | ||
|
|
8db19d6c85 | ||
|
|
0cf596aa8a | ||
|
|
31a608f73e | ||
|
|
55d7dadb63 | ||
|
|
c066511bf2 | ||
|
|
cca13aa8fd | ||
|
|
a9d6be6537 | ||
|
|
006e1594eb | ||
|
|
d4e1d4b553 | ||
|
|
5056c72e67 | ||
|
|
a7a732290c | ||
|
|
998594091b | ||
|
|
9db86942bd | ||
|
|
282afaac7d | ||
|
|
925eb81ec1 | ||
|
|
5642c1b533 | ||
|
|
f0badd9899 | ||
|
|
fd1aca480f | ||
|
|
8a308519f9 | ||
|
|
aae027f7e6 | ||
|
|
0080fbd13c | ||
|
|
66acfd81aa | ||
|
|
c2de9fa72f | ||
|
|
8e179736ce | ||
|
|
379d35e088 | ||
|
|
7c12499783 | ||
|
|
ffbe425c2f | ||
|
|
32aa053e6c | ||
|
|
cddf47d3a0 | ||
|
|
244a266c06 | ||
|
|
a1706ff7fd | ||
|
|
43bf3c2371 | ||
|
|
cfc945a507 | ||
|
|
dacbdb539a | ||
|
|
c09fbef401 | ||
|
|
9f73400cbc | ||
|
|
740382af51 | ||
|
|
80301a06bf | ||
|
|
a54a542b6c | ||
|
|
d1d5751fa4 | ||
|
|
b07f0eb6a7 | ||
|
|
ad3f3b2d9e | ||
|
|
e5313e73b2 | ||
|
|
baaab5f2a9 | ||
|
|
2c01a89b28 | ||
|
|
9abaa77c62 | ||
|
|
3f8efaebc2 | ||
|
|
eef623a54a | ||
|
|
a26f24ef7b | ||
|
|
d9debdf39a | ||
|
|
903fa9c141 | ||
|
|
8bcfffdf62 | ||
|
|
c7a05d67a1 | ||
|
|
68863a72fe | ||
|
|
065a621fa6 | ||
|
|
336652779b | ||
|
|
4e80d8621f | ||
|
|
3efae3827f | ||
|
|
98100f3b35 | ||
|
|
a4a615da97 | ||
|
|
238702b697 | ||
|
|
ab4e5424ca | ||
|
|
32effb10a9 | ||
|
|
d778e2c36b | ||
|
|
6fba4e4594 | ||
|
|
73c3c33ac7 | ||
|
|
4dce16f475 | ||
|
|
71b4e57b67 | ||
|
|
461e346f3a | ||
|
|
990ac706d8 | ||
|
|
b3474924c2 | ||
|
|
3238b32677 | ||
|
|
52d75bd988 | ||
|
|
38cebd321f | ||
|
|
86109e9f27 | ||
|
|
6efd06c54d | ||
|
|
ff14ad5245 | ||
|
|
1494874e25 | ||
|
|
e44e6e986c | ||
|
|
b6127aa5a7 | ||
|
|
020cca2ebf | ||
|
|
406bea47b5 | ||
|
|
06a9b72a38 | ||
|
|
076e6b7c06 | ||
|
|
f4da176851 | ||
|
|
9e6192a6c2 | ||
|
|
6939494b3e | ||
|
|
4c95d02cbb | ||
|
|
d84f07c2e7 | ||
|
|
edb6e3cb98 | ||
|
|
9f8b8b0072 | ||
|
|
a234c5238e | ||
|
|
850c5457da | ||
|
|
47e65658c7 | ||
|
|
2209a9c1e8 | ||
|
|
a5eb15b880 | ||
|
|
a4a475c8b6 | ||
|
|
f0d29a1c6d | ||
|
|
4aa04ddc7d | ||
|
|
44638dd424 | ||
|
|
f5fea13dbc | ||
|
|
596d800aa1 | ||
|
|
2d783e569a | ||
|
|
f7160c81c5 | ||
|
|
96e17adf4d | ||
|
|
46738a1365 | ||
|
|
9b884f7d1a | ||
|
|
ec4c87c86e | ||
|
|
2aaa216825 | ||
|
|
6018831193 | ||
|
|
0ca8d3d9f7 | ||
|
|
b4c0f01bfd | ||
|
|
6d54b25d20 | ||
|
|
cc9e5816a7 | ||
|
|
d717415522 | ||
|
|
b82d5d147f | ||
|
|
500e4a732d | ||
|
|
a316590adc | ||
|
|
b1ade00ece | ||
|
|
0157d5f6ad | ||
|
|
766566f6a8 | ||
|
|
aa541a680a | ||
|
|
8105266800 | ||
|
|
f86b0309e7 | ||
|
|
c74b95c44c | ||
|
|
1ba3e37d27 | ||
|
|
31a9f13cc7 | ||
|
|
d1a2c3f958 | ||
|
|
246f4001d2 | ||
|
|
5e178b9cd4 | ||
|
|
0b54974719 | ||
|
|
d14e8a72d1 | ||
|
|
fa70449d80 | ||
|
|
63926c5e39 | ||
|
|
9ca27aad31 | ||
|
|
aaf66f1cee | ||
|
|
8076687d52 | ||
|
|
6f8e6c59f5 | ||
|
|
299b6baa26 | ||
|
|
1b3296a093 | ||
|
|
5f2c55bc95 | ||
|
|
ac9587bfda | ||
|
|
da4ec1d5e7 | ||
|
|
1ac3b96897 | ||
|
|
df40e4d818 | ||
|
|
d172650065 | ||
|
|
5f5b70ff91 | ||
|
|
daafec20ba | ||
|
|
914a32d000 | ||
|
|
4d6818190d | ||
|
|
03dd794a80 | ||
|
|
40b9b84caa | ||
|
|
7c561e6f82 | ||
|
|
4e7648b4e2 | ||
|
|
972fdc1b87 | ||
|
|
a9b0ddbb86 | ||
|
|
3baedc5bdb | ||
|
|
cfe18ea947 | ||
|
|
fcafec7081 | ||
|
|
6c78a74776 | ||
|
|
a08f0de53b | ||
|
|
2c975ee9fb | ||
|
|
77bb10c682 | ||
|
|
b7e7ae5ad6 | ||
|
|
7c68c84fac | ||
|
|
f7c9a9ad82 | ||
|
|
7d1c1096bc | ||
|
|
1b8b76816e | ||
|
|
ddb98226df | ||
|
|
76833f0281 | ||
|
|
258d2600cd | ||
|
|
c4c2205658 | ||
|
|
53da14333e | ||
|
|
822abd6e69 | ||
|
|
7bb0919c72 | ||
|
|
d0e09aa89d | ||
|
|
c0048d0a61 | ||
|
|
5f9ea2b80e | ||
|
|
ab32098063 | ||
|
|
994b17be46 | ||
|
|
2db5d966f2 | ||
|
|
28fc71eddc | ||
|
|
ef0e6ee681 | ||
|
|
8e4c803f31 | ||
|
|
094d8ba731 | ||
|
|
dd465afd2c | ||
|
|
95e2c5eb32 | ||
|
|
4cec58e072 | ||
|
|
9caaa17f7f | ||
|
|
8c4c67f3ad | ||
|
|
5ead190891 | ||
|
|
db66b8727b | ||
|
|
8c00287e84 | ||
|
|
e926079c0a | ||
|
|
23f598f3a0 | ||
|
|
dc50979a68 | ||
|
|
8e6483511d | ||
|
|
32bf8b4a37 | ||
|
|
adf96da283 | ||
|
|
e5f263ba98 | ||
|
|
f88567b114 | ||
|
|
0c29b2cb88 | ||
|
|
c8dcd03b08 | ||
|
|
480eaea2a8 | ||
|
|
5d0392524a | ||
|
|
ef1050b0e4 | ||
|
|
ca1b774dd9 | ||
|
|
e16ea149aa | ||
|
|
a15cb36dfc | ||
|
|
8489b26d06 | ||
|
|
3e1c257dde | ||
|
|
853f4baad4 | ||
|
|
0656ec62a4 | ||
|
|
cf46be439a | ||
|
|
aa2bd138b7 | ||
|
|
7c6c5242dc | ||
|
|
c8da4a7082 | ||
|
|
13947c3a05 | ||
|
|
96c1d04889 | ||
|
|
3529d46fd2 | ||
|
|
fe76612d90 | ||
|
|
30860b61fb | ||
|
|
62bcf754d3 | ||
|
|
b1ea93586b | ||
|
|
9bc79ef6e3 | ||
|
|
2d44788931 | ||
|
|
027fd7a1c1 | ||
|
|
61e27fb1a5 | ||
|
|
669bc32e0d | ||
|
|
6f15e5b102 | ||
|
|
9bbd14a7dd | ||
|
|
09e69745bc | ||
|
|
c986e28a70 | ||
|
|
78a16c3733 | ||
|
|
935312c227 | ||
|
|
1026695da7 | ||
|
|
68804f7f70 | ||
|
|
81bc2f9298 | ||
|
|
2dd6ee6a9c | ||
|
|
f704972b3e | ||
|
|
c902ae952b | ||
|
|
441ac9fc38 | ||
|
|
25c1ea9212 | ||
|
|
0010d38337 | ||
|
|
06df2066a8 | ||
|
|
12a706b595 | ||
|
|
189cdd92c9 | ||
|
|
519564b742 | ||
|
|
660b605e18 | ||
|
|
e22a189df1 | ||
|
|
6fa2ba2318 | ||
|
|
3457b9cd80 | ||
|
|
48888a7c26 | ||
|
|
69d2cc84e2 | ||
|
|
21e096fd88 | ||
|
|
2415576ab0 | ||
|
|
005a36608a | ||
|
|
cc63a1711b | ||
|
|
64585cf889 | ||
|
|
a9cb692961 | ||
|
|
9a8346d39a | ||
|
|
6aecfcf0fe | ||
|
|
dc69020a47 | ||
|
|
b68ec63494 | ||
|
|
0dfc26e57f | ||
|
|
5f5b59309c | ||
|
|
49c3b50b5f | ||
|
|
0267cd789f | ||
|
|
2b1efe8f08 | ||
|
|
ee85bbfbfd | ||
|
|
5b33e6d2e6 | ||
|
|
579e1cc744 | ||
|
|
eca3277fb9 | ||
|
|
913feca6a6 | ||
|
|
4f08e23807 | ||
|
|
b3c99ec0ed | ||
|
|
682d124618 | ||
|
|
239000d2c9 | ||
|
|
ec413d5233 | ||
|
|
34380434c4 | ||
|
|
b26467a8eb | ||
|
|
b5e7cf3f55 | ||
|
|
5ee4b01406 | ||
|
|
cddf9cf9bf | ||
|
|
09b33b795b | ||
|
|
68081c1c89 | ||
|
|
6c3ccdc77b | ||
|
|
26a5a35200 | ||
|
|
741ac3655b | ||
|
|
c1a7e250b6 | ||
|
|
c121fc4e42 | ||
|
|
6e84b42320 | ||
|
|
d40e27463d | ||
|
|
b6ffdbb8dd | ||
|
|
f81e3bc215 | ||
|
|
8e81720bc8 | ||
|
|
6df69dce6c | ||
|
|
f61bb27d9c | ||
|
|
de268a067c | ||
|
|
b11a8a7813 | ||
|
|
d753413409 | ||
|
|
f065933391 | ||
|
|
f87d0649c5 | ||
|
|
189847eb47 | ||
|
|
893acb19df | ||
|
|
96267ad0a8 | ||
|
|
cf7ce3a450 | ||
|
|
ba41258635 | ||
|
|
e48428296c | ||
|
|
d819827ea2 | ||
|
|
bd92ab67d6 | ||
|
|
0a99a46bfc | ||
|
|
1e848458f9 | ||
|
|
2ca3a5994b | ||
|
|
bfe18f0c83 | ||
|
|
28047b502f | ||
|
|
9881d7ca30 | ||
|
|
24808ef8e6 | ||
|
|
66e61c76b1 | ||
|
|
7237cd3290 | ||
|
|
d04e487877 | ||
|
|
996e82b3d9 | ||
|
|
9ab4f39020 | ||
|
|
58271fb5af | ||
|
|
893219d66f | ||
|
|
763a9359f5 | ||
|
|
5a342e385c | ||
|
|
47ca9228c3 | ||
|
|
36e894aa62 | ||
|
|
d40e1c0cef | ||
|
|
e02c7cc60c | ||
|
|
ca48092413 | ||
|
|
8e01d686f7 | ||
|
|
71423a1efb | ||
|
|
c3ddace690 | ||
|
|
a61b25ce5f | ||
|
|
8c9ee1818b | ||
|
|
a4149dffcd | ||
|
|
028f585356 | ||
|
|
c8969edd3c | ||
|
|
0fc2dc6ad3 | ||
|
|
af15e33f57 | ||
|
|
be83a8cc55 | ||
|
|
3fdae8f334 | ||
|
|
e73b6060b1 | ||
|
|
5dbbcf7dad | ||
|
|
2dc759a951 | ||
|
|
14fd14a284 | ||
|
|
7f336acfd9 | ||
|
|
8a6306f769 | ||
|
|
6b68de140c | ||
|
|
17fb524a91 | ||
|
|
ad1e11a035 | ||
|
|
7d604e8141 | ||
|
|
0999822364 | ||
|
|
47a994ad5b | ||
|
|
5aaa268650 | ||
|
|
2d13a17c3b | ||
|
|
cc5c54574d | ||
|
|
3755fdc885 | ||
|
|
4e871ad36c | ||
|
|
97099edc38 | ||
|
|
abb1450b24 | ||
|
|
4360f9644b | ||
|
|
f755aca58f | ||
|
|
a9946fb7a0 | ||
|
|
28b17d37f1 | ||
|
|
326c03e132 | ||
|
|
44fc32e3e2 | ||
|
|
744827166e | ||
|
|
c750582db4 | ||
|
|
71d1b394e9 | ||
|
|
a4ad901284 | ||
|
|
f9c344b546 | ||
|
|
59cbad3937 | ||
|
|
5904081d7a | ||
|
|
eceaaad61e | ||
|
|
dd86271312 | ||
|
|
7359cdace9 | ||
|
|
ee1df22b25 | ||
|
|
563ee80494 | ||
|
|
88e2b832f7 | ||
|
|
a1dc610079 | ||
|
|
a566bfb566 | ||
|
|
4563b043f2 | ||
|
|
6175e0a8ea | ||
|
|
a52350940a | ||
|
|
c3ba79f5aa | ||
|
|
770d7f54c4 | ||
|
|
3ff7188fbf | ||
|
|
8bed332ff4 | ||
|
|
df9b7ec54f | ||
|
|
2faeed99a2 | ||
|
|
2c49da24f0 | ||
|
|
5843ffc277 | ||
|
|
b326aa83c4 | ||
|
|
e915a877e2 | ||
|
|
64f38acf3e | ||
|
|
e4bdcc2487 | ||
|
|
8981f7c8ef | ||
|
|
4bc20527c3 | ||
|
|
85e713644e | ||
|
|
52ad45bd27 | ||
|
|
86d6d9317f | ||
|
|
d9b2928da1 | ||
|
|
f8fd8f8479 | ||
|
|
f938714df0 | ||
|
|
7cb639ae5d | ||
|
|
39bf0a3f80 | ||
|
|
e241ce96cf | ||
|
|
dbde78ca03 | ||
|
|
9c3d0fa517 | ||
|
|
69d4d7e9c3 | ||
|
|
2a35d7fd38 | ||
|
|
ed4f12ab82 | ||
|
|
de136676ef | ||
|
|
339d9783fb | ||
|
|
4738e88aaf | ||
|
|
81b6e7d7b4 | ||
|
|
f0ebd07fd5 | ||
|
|
2fd15115d9 | ||
|
|
0973af2be0 | ||
|
|
3bf096438f | ||
|
|
45643380d1 | ||
|
|
0f30cfb6ad | ||
|
|
cc53e00bcc | ||
|
|
3f5df2513b | ||
|
|
6892fd9309 | ||
|
|
9c2275ad82 | ||
|
|
d67436c065 | ||
|
|
f8a5328197 | ||
|
|
8171abf583 | ||
|
|
c24cde9d9e | ||
|
|
d0d8d80581 | ||
|
|
8666c6994c | ||
|
|
72d9779aaf | ||
|
|
1805813a56 | ||
|
|
a507c97822 | ||
|
|
826fd0ece1 | ||
|
|
bdfb917935 | ||
|
|
8a474eb1b3 | ||
|
|
022feee5fb | ||
|
|
2a4608cbb0 | ||
|
|
c8a9a6cdbc | ||
|
|
b2523fcdec | ||
|
|
429e46a665 | ||
|
|
7ec92ecc6d | ||
|
|
dc41eceb9e | ||
|
|
01fb51ba78 | ||
|
|
ac265ec495 | ||
|
|
b85184002c | ||
|
|
50afb69859 | ||
|
|
2993cce8b2 | ||
|
|
521487aa2e | ||
|
|
b00813bcb2 | ||
|
|
e737f5bf58 | ||
|
|
1fbcaf840f | ||
|
|
1dd4c41413 | ||
|
|
4210de270f | ||
|
|
f8c91a987f | ||
|
|
6724350665 | ||
|
|
5ab8eb34c5 | ||
|
|
8070909c04 | ||
|
|
d1808bab8c | ||
|
|
b23e5de5a1 | ||
|
|
457e2a1b1b | ||
|
|
8c17230586 | ||
|
|
1cb882a156 | ||
|
|
68abce8a04 | ||
|
|
cede5b6ca6 | ||
|
|
75c08a5b32 | ||
|
|
899bdd09e4 | ||
|
|
74cb9ce197 | ||
|
|
4b87e67ff3 | ||
|
|
1929495a99 | ||
|
|
2a7d2f4fdc | ||
|
|
db07e9f93a | ||
|
|
53d0ceb471 | ||
|
|
de6e341b07 | ||
|
|
cf5d721bee | ||
|
|
e3adc0417a | ||
|
|
4ff85debf1 | ||
|
|
2ea824533c | ||
|
|
6b6d90ac0f | ||
|
|
8b96d05da6 | ||
|
|
6d39432058 | ||
|
|
9c829d7a2e | ||
|
|
32986da448 | ||
|
|
16e36c7337 | ||
|
|
f18ea01530 | ||
|
|
efefd3960a | ||
|
|
244478bcee | ||
|
|
df26f85648 | ||
|
|
38381597d6 | ||
|
|
df77d5f8ce | ||
|
|
c99ac6c2df | ||
|
|
45e407db35 | ||
|
|
95f6c104d4 | ||
|
|
ca842472e5 | ||
|
|
bb2049cec1 | ||
|
|
036d904e31 | ||
|
|
e5760e6b03 | ||
|
|
2a550a3fe6 | ||
|
|
be2058d5d5 | ||
|
|
33482b0827 | ||
|
|
c3817d6144 | ||
|
|
91cbc74bb1 | ||
|
|
9cfaa3339b | ||
|
|
267f8d28c4 | ||
|
|
dbcb1253e8 | ||
|
|
7ff7bd2e8f | ||
|
|
1896379283 | ||
|
|
b4180a50dc | ||
|
|
a25f7629bd | ||
|
|
359ef86dd4 | ||
|
|
2b3accfe66 | ||
|
|
21a081b514 | ||
|
|
76bbb37c74 | ||
|
|
a87be4143a | ||
|
|
f937fc6ce1 | ||
|
|
22f79db72f | ||
|
|
ba7c395ce3 | ||
|
|
2d64c0cd10 | ||
|
|
bd24ddb1d6 | ||
|
|
ffd8906c6c | ||
|
|
92b70ce5f4 | ||
|
|
3d53287ff6 | ||
|
|
96ea51c098 | ||
|
|
fec0f9fca9 | ||
|
|
1383fb0739 | ||
|
|
a78d25d4fc | ||
|
|
3d5da6039a | ||
|
|
f6dd049cb0 | ||
|
|
a06313a0f9 | ||
|
|
db2d297296 | ||
|
|
abd55cca9a | ||
|
|
e5e93c8180 | ||
|
|
1a109afdce | ||
|
|
d7230a24c3 | ||
|
|
9d998cc810 | ||
|
|
f2423bc114 | ||
|
|
b079c6713a | ||
|
|
8c1d5e8114 | ||
|
|
808cd98395 | ||
|
|
e7bd4f38ee | ||
|
|
c529e2217f | ||
|
|
4e844ea907 | ||
|
|
148e247662 | ||
|
|
9eda1558c2 | ||
|
|
79b8d8d9b2 | ||
|
|
477465ae0d | ||
|
|
404674a24a | ||
|
|
934957cbfd | ||
|
|
e11d04f8c2 | ||
|
|
1a54f16b80 | ||
|
|
aed4a981a1 | ||
|
|
3694822040 | ||
|
|
5461feb7e8 | ||
|
|
6570488658 | ||
|
|
38d967fc63 | ||
|
|
07de9d5c22 | ||
|
|
c1bf6c90dc | ||
|
|
4ba8198c7c | ||
|
|
c46a4ebb68 | ||
|
|
0ee77c0b6a | ||
|
|
317d73f8f7 | ||
|
|
3f8169c807 | ||
|
|
3a117c93e8 | ||
|
|
6fa4c7e662 | ||
|
|
dafe6c9f03 | ||
|
|
7e3da961a9 | ||
|
|
63d80200c5 | ||
|
|
66f1f40de8 | ||
|
|
e2fd4f944e | ||
|
|
21e443e201 | ||
|
|
d213c03adf | ||
|
|
92ab83ea38 | ||
|
|
cb4ec5d39d | ||
|
|
010583674e | ||
|
|
d8b1e82079 | ||
|
|
ef8c2fef50 | ||
|
|
0f4de8e47f | ||
|
|
5efcf114ee | ||
|
|
d4b24d8609 | ||
|
|
5db8f7ce39 | ||
|
|
693d2ba991 | ||
|
|
7e82212304 | ||
|
|
64e07abd98 |
No files matched your search
@@ -0,0 +1,25 @@
|
||||
.git
|
||||
.github
|
||||
.venv
|
||||
venv
|
||||
__pycache__
|
||||
*.pyc
|
||||
.pytest_cache
|
||||
.ruff_cache
|
||||
.mypy_cache
|
||||
dist
|
||||
build
|
||||
*.egg-info
|
||||
graphify-out
|
||||
graphify-benchmark
|
||||
graphify_eval
|
||||
graphify_test
|
||||
worked
|
||||
llm-stack-corpus
|
||||
llm-stack-demo
|
||||
product-site
|
||||
ebook
|
||||
tests
|
||||
docs
|
||||
*.md
|
||||
!README.md
|
||||
@@ -0,0 +1,6 @@
|
||||
# Tell GitHub Linguist to ignore generated/example HTML files when calculating
|
||||
# the repo's primary language. Without this, large graph.html artifacts in
|
||||
# worked/ dominate the byte count and the repo shows as HTML instead of Python.
|
||||
worked/**/*.html linguist-vendored=true
|
||||
graphify-out/**/*.html linguist-vendored=true
|
||||
*.html linguist-detectable=false
|
||||
@@ -0,0 +1 @@
|
||||
github: safishamsi
|
||||
@@ -0,0 +1,106 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "main"]
|
||||
pull_request:
|
||||
branches: ["v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "main"]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
skillgen-check:
|
||||
# Fast lint-style guard: the skill files under graphify/ are generated from
|
||||
# the fragments in tools/skillgen/. This fails if someone hand-edited a
|
||||
# generated file or forgot to re-run the generator and bless expected/, and it
|
||||
# runs the build-time validators that guard per-host coverage, the file_type
|
||||
# enum, the monolith round-trips, and the always-on round-trips.
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
# The audit-coverage, monolith-roundtrip, and always-on-roundtrip
|
||||
# validators read blobs from origin/v8. A shallow checkout omits that
|
||||
# ref, so fetch the full history here and the validators run for real
|
||||
# (rather than skipping). The other jobs stay shallow.
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v8.1.0
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
# --frozen keeps uv from re-resolving and rewriting uv.lock as a side
|
||||
# effect of `uv run`; the lock is committed and must not churn in CI.
|
||||
- name: Check generated skill artifacts are up to date
|
||||
run: uv run --frozen python -m tools.skillgen --check
|
||||
|
||||
- name: Audit per-host v8 coverage
|
||||
run: uv run --frozen python -m tools.skillgen --audit-coverage
|
||||
|
||||
- name: Check the file_type enum is a singleton
|
||||
run: uv run --frozen python -m tools.skillgen --schema-singleton
|
||||
|
||||
- name: Round-trip the monoliths against v8
|
||||
run: uv run --frozen python -m tools.skillgen --monolith-roundtrip
|
||||
|
||||
- name: Round-trip the always-on blocks against v8
|
||||
run: uv run --frozen python -m tools.skillgen --always-on-roundtrip
|
||||
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
python-version: ["3.10", "3.12"]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
# test_skillgen.py reads pre-split skill bodies from the immutable
|
||||
# baseline commit via `git show`; a shallow checkout omits that history
|
||||
# and the baseline tests fail. Full history mirrors the skillgen-check job.
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v8.1.0
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
|
||||
# --frozen installs straight from the committed uv.lock without re-resolving
|
||||
# or rewriting it, so CI never churns the lock.
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --frozen
|
||||
|
||||
- name: Run tests
|
||||
run: uv run --frozen pytest tests/ -q --tb=short
|
||||
|
||||
- name: Verify install works end-to-end
|
||||
run: |
|
||||
uv run --frozen graphify --help
|
||||
uv run --frozen graphify install
|
||||
|
||||
security-scan:
|
||||
# The dev deps include bandit and pip-audit. Run them in CI so a new
|
||||
# HIGH-severity finding or vulnerable dependency is caught on the PR that
|
||||
# introduces it, rather than at the next manual audit.
|
||||
# Non-blocking for now (continue-on-error) to avoid breaking CI on
|
||||
# pre-existing findings; remove continue-on-error after the initial
|
||||
# cleanup pass.
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v8.1.0
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Install dependencies
|
||||
run: uv sync --frozen
|
||||
|
||||
- name: bandit (static security analysis)
|
||||
continue-on-error: true
|
||||
run: uv run --frozen bandit -r graphify -ll
|
||||
|
||||
- name: pip-audit (dependency vulnerabilities)
|
||||
continue-on-error: true
|
||||
run: uv run --frozen pip-audit --strict
|
||||
@@ -0,0 +1,64 @@
|
||||
name: Release graph asset
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build-graph:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write # needed to upload release assets
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v8.1.0
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Install graphify
|
||||
run: uv sync --frozen
|
||||
|
||||
- name: Build graph of graphify source (AST-only, no API cost)
|
||||
# graphify/skills/ contains 126+ .md files that trigger the LLM pass.
|
||||
# Temporarily ignore all .md files so extraction stays pure AST (no API key needed).
|
||||
run: |
|
||||
echo "*.md" >> .graphifyignore
|
||||
echo "*.txt" >> .graphifyignore
|
||||
uv run --frozen graphify extract graphify/ --out .
|
||||
git checkout .graphifyignore 2>/dev/null || rm -f .graphifyignore
|
||||
|
||||
- name: Cluster, label communities and generate GRAPH_REPORT.md
|
||||
# cluster-only writes GRAPH_REPORT.md and names communities (no LLM needed
|
||||
# for basic numeric labels; --no-label skips LLM labeling entirely).
|
||||
run: uv run --frozen graphify cluster-only . --no-label
|
||||
|
||||
- name: Generate HTML viewer
|
||||
run: uv run --frozen graphify export html --graph graphify-out/graph.json
|
||||
|
||||
- name: Bundle release asset
|
||||
run: |
|
||||
mkdir -p dist-graph
|
||||
cp graphify-out/graph.json dist-graph/
|
||||
cp graphify-out/graph.html dist-graph/
|
||||
[ -f graphify-out/GRAPH_REPORT.md ] && cp graphify-out/GRAPH_REPORT.md dist-graph/ || true
|
||||
tar -czf graphify-self-graph.tar.gz -C dist-graph .
|
||||
echo "Asset contents:"
|
||||
tar -tzf graphify-self-graph.tar.gz
|
||||
|
||||
- name: Upload to GitHub release
|
||||
if: github.event_name == 'release'
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
files: graphify-self-graph.tar.gz
|
||||
|
||||
- name: Upload as workflow artifact (for workflow_dispatch runs)
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: graphify-self-graph
|
||||
path: graphify-self-graph.tar.gz
|
||||
retention-days: 7
|
||||
+27
@@ -13,3 +13,30 @@ build/
|
||||
*.so
|
||||
*.egg
|
||||
.graphify/
|
||||
graphify-out/
|
||||
.graphify_*.json
|
||||
.graphify_python
|
||||
.claude/
|
||||
skills/
|
||||
# The packaged skill bundles under graphify/skills/ are generated, committed
|
||||
# artifacts (rendered by tools/skillgen). Keep them tracked even though the
|
||||
# broad skills/ rule above ignores install-target skill dirs elsewhere.
|
||||
!graphify/skills/
|
||||
!graphify/skills/**
|
||||
# The skillgen core fragments are the human-edited source of the lean SKILL.md.
|
||||
# A global "core" ignore (for core dumps) would otherwise drop them.
|
||||
!tools/skillgen/fragments/core/
|
||||
!tools/skillgen/fragments/core/**
|
||||
docs/superpowers/
|
||||
.vscode/
|
||||
.kilo
|
||||
openspec/
|
||||
# Local benchmark scripts — never commit
|
||||
scripts/run_k2_*.py
|
||||
scripts/llm.py
|
||||
scripts/benchmark_kimi*.json
|
||||
scripts/benchmark_kimi*.py
|
||||
paper/
|
||||
|
||||
# macOS Finder metadata
|
||||
.DS_Store
|
||||
@@ -0,0 +1,22 @@
|
||||
# Run with: uv run pre-commit install (pre-commit is already a dev dependency)
|
||||
# One-off across the tree: uv run pre-commit run --all-files
|
||||
#
|
||||
# The skillgen hook is the local anti-drift guard. The skill files under
|
||||
# graphify/ are generated from the fragments in tools/skillgen/; a hand-edit to
|
||||
# a generated file fails this check the same way CI does. Run
|
||||
# `python -m tools.skillgen` then `--bless` to regenerate after a fragment edit.
|
||||
repos:
|
||||
- repo: local
|
||||
hooks:
|
||||
- id: skillgen-check
|
||||
name: skillgen --check (generated skill artifacts are up to date)
|
||||
entry: python -m tools.skillgen --check
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
rev: v0.15.14
|
||||
hooks:
|
||||
- id: ruff
|
||||
args: ["--config", "pyproject.toml"]
|
||||
@@ -0,0 +1,8 @@
|
||||
## graphify
|
||||
|
||||
This project has a graphify knowledge graph at graphify-out/.
|
||||
|
||||
Rules:
|
||||
- Before answering architecture or codebase questions, read graphify-out/GRAPH_REPORT.md for god nodes and community structure
|
||||
- If graphify-out/wiki/index.md exists, navigate it instead of reading raw files
|
||||
- After modifying code files in this session, run `graphify update .` to keep the graph current (AST-only, no API cost)
|
||||
@@ -0,0 +1,85 @@
|
||||
# Architecture
|
||||
|
||||
graphify is a Claude Code skill backed by a Python library. The skill orchestrates the library; the library can be used standalone.
|
||||
|
||||
## Pipeline
|
||||
|
||||
```
|
||||
detect() → extract() → build_graph() → cluster() → analyze() → report() → export()
|
||||
```
|
||||
|
||||
Each stage is a single function in its own module. They communicate through plain Python dicts and NetworkX graphs - no shared state, no side effects outside `graphify-out/`.
|
||||
|
||||
## Module responsibilities
|
||||
|
||||
| Module | Function | Input → Output |
|
||||
|--------|----------|----------------|
|
||||
| `detect.py` | `collect_files(root)` | directory → `[Path]` filtered list |
|
||||
| `extract.py` | `extract(path)` | file path → `{nodes, edges}` dict |
|
||||
| `build.py` | `build_graph(extractions)` | list of extraction dicts → `nx.Graph` |
|
||||
| `cluster.py` | `cluster(G)` | graph → graph with `community` attr on each node |
|
||||
| `analyze.py` | `analyze(G)` | graph → analysis dict (god nodes, surprises, questions) |
|
||||
| `report.py` | `render_report(G, analysis)` | graph + analysis → GRAPH_REPORT.md string |
|
||||
| `export.py` | `export(G, out_dir, ...)` | graph → Obsidian vault, graph.json, graph.html, graph.svg |
|
||||
| `callflow_html.py` | `write_callflow_html(...)` | graphify-out files → Mermaid architecture/call-flow HTML |
|
||||
| `ingest.py` | `ingest(url, ...)` | URL → file saved to corpus dir |
|
||||
| `cache.py` | `check_semantic_cache / save_semantic_cache` | files → (cached, uncached) split |
|
||||
| `security.py` | validation helpers | URL / path / label → validated or raises |
|
||||
| `validate.py` | `validate_extraction(data)` | extraction dict → raises on schema errors |
|
||||
| `serve.py` | `start_server(graph_path)` | graph file path → MCP stdio server |
|
||||
| `watch.py` | `watch(root, flag_path)` | directory → writes flag file on change |
|
||||
| `benchmark.py` | `run_benchmark(graph_path)` | graph file → corpus vs subgraph token comparison |
|
||||
|
||||
## Extraction output schema
|
||||
|
||||
Every extractor returns:
|
||||
|
||||
```json
|
||||
{
|
||||
"nodes": [
|
||||
{"id": "unique_string", "label": "human name", "source_file": "path", "source_location": "L42"}
|
||||
],
|
||||
"edges": [
|
||||
{"source": "id_a", "target": "id_b", "relation": "calls|imports|uses|...", "confidence": "EXTRACTED|INFERRED|AMBIGUOUS"}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
`validate.py` enforces this schema before `build_graph()` consumes it.
|
||||
|
||||
## Confidence labels
|
||||
|
||||
| Label | Meaning |
|
||||
|-------|---------|
|
||||
| `EXTRACTED` | Relationship is explicitly stated in the source (e.g., an import statement, a direct call) |
|
||||
| `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 |
|
||||
|
||||
## Adding a new language extractor
|
||||
|
||||
1. Add a `extract_<lang>(path: Path) -> dict` function in `extract.py` following the existing pattern (tree-sitter parse → walk nodes → collect `nodes` and `edges` → call-graph second pass for INFERRED `calls` edges).
|
||||
2. Register the file suffix in `extract()` dispatch and `collect_files()`.
|
||||
3. Add the suffix to `CODE_EXTENSIONS` in `detect.py` and `_WATCHED_EXTENSIONS` in `watch.py`.
|
||||
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`.
|
||||
|
||||
## Security
|
||||
|
||||
All external input passes through `graphify/security.py` before use:
|
||||
|
||||
- URLs → `validate_url()` (http/https only) + `_NoFileRedirectHandler` (blocks file:// redirects)
|
||||
- Fetched content → `safe_fetch()` / `safe_fetch_text()` (size cap, timeout)
|
||||
- Graph file paths → `validate_graph_path()` (must resolve inside `graphify-out/`)
|
||||
- Node labels → `sanitize_label()` (strips control chars, caps 256 chars, HTML-escapes)
|
||||
|
||||
See `SECURITY.md` for the full threat model.
|
||||
|
||||
## Testing
|
||||
|
||||
One test file per module under `tests/`. Run with:
|
||||
|
||||
```bash
|
||||
pytest tests/ -q
|
||||
```
|
||||
|
||||
All tests are pure unit tests - no network calls, no file system side effects outside `tmp_path`.
|
||||
+1291
File diff suppressed because it is too large.
Load diff
+25
@@ -0,0 +1,25 @@
|
||||
# graphify MCP server as a shared HTTP service (issue #1143).
|
||||
#
|
||||
# Build: docker build -t graphify .
|
||||
# Run: docker run -p 8080:8080 -v "$(pwd)/graphify-out:/data" graphify \
|
||||
# /data/graph.json --transport http --host 0.0.0.0 --api-key "$SECRET"
|
||||
#
|
||||
# Builds from source so the image includes the Streamable HTTP transport even
|
||||
# before it lands on PyPI. The graph.json is mounted at runtime (-v), never
|
||||
# baked into the image.
|
||||
FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
COPY . /app
|
||||
|
||||
# The [mcp] extra pulls mcp + starlette + uvicorn, which the HTTP transport needs.
|
||||
RUN pip install --no-cache-dir ".[mcp]"
|
||||
|
||||
# Run as a non-root user — the server is network-exposed.
|
||||
RUN useradd --create-home --uid 10001 graphify
|
||||
USER graphify
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
ENTRYPOINT ["python", "-m", "graphify.serve"]
|
||||
CMD ["/data/graph.json", "--transport", "http", "--host", "0.0.0.0", "--port", "8080"]
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Safi Shamsi
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,216 +1,741 @@
|
||||
# graphify
|
||||
<p align="center">
|
||||
<a href="https://graphifylabs.ai"><img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/></a>
|
||||
</p>
|
||||
|
||||
any folder of files → persistent knowledge graph → Obsidian vault, graph.json, audit report
|
||||
<p align="center">
|
||||
🇺🇸 <a href="README.md">English</a> | 🇨🇳 <a href="docs/translations/README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="docs/translations/README.ja-JP.md">日本語</a> | 🇰🇷 <a href="docs/translations/README.ko-KR.md">한국어</a> | 🇩🇪 <a href="docs/translations/README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="docs/translations/README.fr-FR.md">Français</a> | 🇪🇸 <a href="docs/translations/README.es-ES.md">Español</a> | 🇮🇳 <a href="docs/translations/README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="docs/translations/README.pt-BR.md">Português</a> | 🇷🇺 <a href="docs/translations/README.ru-RU.md">Русский</a> | 🇸🇦 <a href="docs/translations/README.ar-SA.md">العربية</a> | 🇮🇷 <a href="docs/translations/README.fa-IR.md">فارسی</a> | 🇮🇹 <a href="docs/translations/README.it-IT.md">Italiano</a> | 🇵🇱 <a href="docs/translations/README.pl-PL.md">Polski</a> | 🇳🇱 <a href="docs/translations/README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="docs/translations/README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="docs/translations/README.uk-UA.md">Українська</a> | 🇻🇳 <a href="docs/translations/README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="docs/translations/README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="docs/translations/README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="docs/translations/README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="docs/translations/README.ro-RO.md">Română</a> | 🇨🇿 <a href="docs/translations/README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="docs/translations/README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="docs/translations/README.da-DK.md">Dansk</a> | 🇳🇴 <a href="docs/translations/README.no-NO.md">Norsk</a> | 🇭🇺 <a href="docs/translations/README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="docs/translations/README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="docs/translations/README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="docs/translations/README.zh-TW.md">繁體中文</a> | 🇵🇭 <a href="docs/translations/README.fil-PH.md">Filipino</a>
|
||||
</p>
|
||||
|
||||
```
|
||||
/graphify ./raw
|
||||
```
|
||||
<p align="center">
|
||||
<a href="https://www.ycombinator.com/companies/graphify"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
<a href="https://discord.gg/598Ad9zQZ"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://safishamsi.gumroad.com/l/qetvlo"><img src="https://img.shields.io/badge/Book-The%20Memory%20Layer-2ea44f?style=flat&logo=gitbook&logoColor=white" alt="The Memory Layer"/></a>
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<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://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></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://x.com/graphifyy"><img src="https://img.shields.io/badge/X-graphifyy-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
</p>
|
||||
|
||||
```
|
||||
.graphify/
|
||||
├── obsidian/ open as Obsidian vault — visual graph, wikilinks, filter by community
|
||||
├── GRAPH_REPORT.md what the graph found: god nodes, surprising connections, suggested questions
|
||||
├── graph.json persistent graph — query it weeks later without re-reading anything
|
||||
├── cache/ per-file SHA256 cache — re-runs only process changed files
|
||||
└── memory/ Q&A results filed back in — what you ask grows the graph on next --update
|
||||
```
|
||||
<p align="center">
|
||||
<a href="https://star-history.com/#safishamsi/graphify&Date">
|
||||
<img src="https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date" alt="Star History Chart" width="370"/>
|
||||
</a>
|
||||
</p>
|
||||
|
||||
[placeholder: animated GIF showing the full pipeline — detect → extract → cluster → report → Obsidian vault]
|
||||
Type `/graphify` in your AI coding assistant and it maps your entire project — code, docs, PDFs, images, videos — into a knowledge graph you can query instead of grepping through files.
|
||||
|
||||
## Why this exists
|
||||
|
||||
**The problem:** Andrej Karpathy described it well: he keeps a `/raw` folder where he drops papers, tweets, screenshots, and notes. The problem is that folder becomes opaque. You forget what's in it. You can't see what connects. Ask Claude "what links paper A to the code in repo B?" and it will hallucinate — it hasn't read both, and even if it has, it has no memory of that connection next session.
|
||||
|
||||
**What LLMs get wrong:** Naive summarization fills in every gap confidently. You get a summary that sounds complete but you can't tell what was actually in the files vs invented by the model. And next session, it's all gone — no memory of what it extracted.
|
||||
|
||||
**What graphify does differently:**
|
||||
|
||||
- **Persistent graph** — relationships are stored in `.graphify/graph.json` and survive across sessions. Query weeks later without re-reading anything.
|
||||
- **Honest audit trail** — every edge is tagged `EXTRACTED` (explicitly stated), `INFERRED` (call-graph or reasonable deduction), or `AMBIGUOUS` (flagged for review). You always know what was found vs invented.
|
||||
- **Cross-document surprise** — Leiden community detection finds clusters, then surfaces cross-community connections: the things you would never think to ask about directly.
|
||||
- **Feedback loop** — every query answer is saved to `.graphify/memory/`. On next `--update`, that Q&A becomes a node. The graph grows from what you ask, not just what you add.
|
||||
|
||||
The result: a navigable map of your corpus that is honest about what it knows and what it guessed.
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
pip install graphify && graphify install
|
||||
```
|
||||
|
||||
That's it. This copies the skill file into `~/.claude/skills/graphify/` and registers it in `~/.claude/CLAUDE.md` automatically. The Python package and all dependencies install on first `/graphify` run — you never touch pip manually again.
|
||||
|
||||
Then open Claude Code in any directory and type:
|
||||
Works in Claude Code, Codex, OpenCode, Kilo Code, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, Amp, OpenClaw, Factory Droid, Trae, Hermes, Kimi Code, Kiro, Pi, Devin CLI, and Google Antigravity.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Manual install (curl)</summary>
|
||||
That's it. You get three files:
|
||||
|
||||
**Step 1 — copy the skill file**
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html open in any browser — click nodes, filter, search
|
||||
├── GRAPH_REPORT.md the highlights: key concepts, surprising connections, suggested questions
|
||||
└── graph.json the full graph — query it anytime without re-reading your files
|
||||
```
|
||||
|
||||
For a readable architecture page with Mermaid call-flow diagrams, run:
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.claude/skills/graphify
|
||||
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v1/skills/graphify/skill.md \
|
||||
> ~/.claude/skills/graphify/SKILL.md
|
||||
graphify export callflow-html
|
||||
```
|
||||
|
||||
**Step 2 — register it in Claude Code**
|
||||
---
|
||||
|
||||
Add this to `~/.claude/CLAUDE.md` (create the file if it doesn't exist):
|
||||
## Prerequisites
|
||||
|
||||
```
|
||||
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) — any input to knowledge graph. Trigger: `/graphify`
|
||||
When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"` before doing anything else.
|
||||
| Requirement | Minimum | Check | Install |
|
||||
|---|---|---|---|
|
||||
| Python | 3.10+ | `python --version` | [python.org](https://www.python.org/downloads/) |
|
||||
| uv *(recommended)* | any | `uv --version` | `curl -LsSf https://astral.sh/uv/install.sh \| sh` |
|
||||
| pipx *(alternative)* | any | `pipx --version` | `pip install pipx` |
|
||||
|
||||
**macOS quick install (Homebrew):**
|
||||
```bash
|
||||
brew install python@3.12 uv
|
||||
```
|
||||
|
||||
</details>
|
||||
**Windows quick install:**
|
||||
```powershell
|
||||
winget install astral-sh.uv
|
||||
```
|
||||
|
||||
## Usage
|
||||
**Ubuntu/Debian:**
|
||||
```bash
|
||||
sudo apt install python3.12 python3-pip pipx
|
||||
# or install uv:
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Install
|
||||
|
||||
> **Official package:** The PyPI package is `graphifyy` (double-y). Other `graphify*` packages on PyPI are not affiliated. The CLI command is still `graphify`.
|
||||
|
||||
**Step 1 — install the package:**
|
||||
|
||||
```bash
|
||||
# Recommended (isolated env; if 'graphify' isn't found after, run: uv tool update-shell):
|
||||
uv tool install graphifyy
|
||||
|
||||
# Alternatives:
|
||||
pipx install graphifyy
|
||||
pip install graphifyy # may need PATH setup — see note below
|
||||
```
|
||||
|
||||
**Step 2 — register the skill with your AI assistant:**
|
||||
|
||||
```bash
|
||||
graphify install
|
||||
```
|
||||
|
||||
That's it. Open your AI assistant and type `/graphify .`
|
||||
|
||||
To install the assistant skill into the current repository instead of your user
|
||||
profile, add `--project`:
|
||||
|
||||
```bash
|
||||
graphify install --project
|
||||
graphify install --project --platform codex
|
||||
```
|
||||
|
||||
Project-scoped installs write under the current directory, for example
|
||||
`.claude/skills/graphify/SKILL.md` or `.agents/skills/graphify/SKILL.md` (plus a
|
||||
`references/` sidecar the skill loads on demand), and
|
||||
print a `git add` hint for files that can be committed.
|
||||
Per-platform commands that support project-scoped installs accept the same flag,
|
||||
for example `graphify claude install --project` or `graphify codex install --project`.
|
||||
|
||||
> **PowerShell note:** Use `graphify .` not `/graphify .` — the leading slash is a path separator in PowerShell.
|
||||
|
||||
> **`graphify: command not found`?** `uv tool install` / `pipx install` put the `graphify` command in their tool bin dir (`~/.local/bin`). If your shell can't find it right after install — common on a fresh macOS + zsh setup — that dir isn't on your `PATH` yet: run `uv tool update-shell` (or `pipx ensurepath`), then open a new terminal. With plain `pip`, add `~/.local/bin` (Linux) or `~/Library/Python/3.x/bin` (Mac) to your PATH, or run `python -m graphify`.
|
||||
|
||||
> **Running with `uvx` / `uv tool run` instead of installing?** Name the package, not the command: `uvx --from graphifyy graphify install`. Plain `uvx graphify …` fails (`No solution found … no versions of graphify`) because `uv tool run` reads the first word as a *package*, and the package is `graphifyy` — the `graphify` command lives inside it.
|
||||
|
||||
> **Avoid `pip install` on Mac/Windows** if possible. The skill resolves Python at runtime from `graphify-out/.graphify_python`; if that points to a different environment than where `pip` installed the package, you'll get `ModuleNotFoundError: No module named 'graphify'`. `uv tool install` and `pipx install` isolate the package in their own env and avoid this entirely.
|
||||
|
||||
> **Git hooks and uv tool / pipx:** `graphify hook install` embeds the current interpreter path directly into the hook scripts at install time, so the post-commit hook fires correctly even in GUI git clients and CI runners where `~/.local/bin` is not on PATH. If you reinstall or upgrade graphify, re-run `graphify hook install` to refresh the embedded path.
|
||||
|
||||
### Pick your platform
|
||||
|
||||
| Platform | Install command |
|
||||
|----------|----------------|
|
||||
| Claude Code (Linux/Mac) | `graphify install` |
|
||||
| Claude Code (Windows) | `graphify install` (auto-detected) or `graphify install --platform windows` |
|
||||
| CodeBuddy | `graphify install --platform codebuddy` |
|
||||
| Codex | `graphify install --platform codex` |
|
||||
| OpenCode | `graphify install --platform opencode` |
|
||||
| Kilo Code | `graphify install --platform kilo` |
|
||||
| GitHub Copilot CLI | `graphify install --platform copilot` |
|
||||
| VS Code Copilot Chat | `graphify vscode install` |
|
||||
| Aider | `graphify install --platform aider` |
|
||||
| OpenClaw | `graphify install --platform claw` |
|
||||
| Factory Droid | `graphify install --platform droid` |
|
||||
| Trae | `graphify install --platform trae` |
|
||||
| Trae CN | `graphify install --platform trae-cn` |
|
||||
| Gemini CLI | `graphify install --platform gemini` |
|
||||
| Hermes | `graphify install --platform hermes` |
|
||||
| Kimi Code | `graphify install --platform kimi` |
|
||||
| Amp | `graphify amp install` |
|
||||
| Agent Skills (cross-framework) | `graphify install --platform agents` (alias `--platform skills`) |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Pi coding agent | `graphify install --platform pi` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Devin CLI | `graphify devin install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
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 — 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`.
|
||||
|
||||
> Codex uses `$graphify` instead of `/graphify`.
|
||||
|
||||
### Optional extras
|
||||
|
||||
Install only what you need:
|
||||
|
||||
| Extra | What it adds | Install |
|
||||
|---|---|---|
|
||||
| `pdf` | PDF extraction | `uv tool install "graphifyy[pdf]"` |
|
||||
| `office` | `.docx` and `.xlsx` support | `uv tool install "graphifyy[office]"` |
|
||||
| `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]"` |
|
||||
| `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]"` |
|
||||
| `leiden` | Leiden community detection (Python < 3.13 only) | `uv tool install "graphifyy[leiden]"` |
|
||||
| `ollama` | Ollama local inference | `uv tool install "graphifyy[ollama]"` |
|
||||
| `openai` | OpenAI / OpenAI-compatible APIs | `uv tool install "graphifyy[openai]"` |
|
||||
| `gemini` | Google Gemini API | `uv tool install "graphifyy[gemini]"` |
|
||||
| `anthropic` | Anthropic Claude API (`--backend claude`, uses `ANTHROPIC_API_KEY`) | `uv tool install "graphifyy[anthropic]"` |
|
||||
| `bedrock` | AWS Bedrock (uses IAM, no API key) | `uv tool install "graphifyy[bedrock]"` |
|
||||
| `azure` | Azure OpenAI Service (`--backend azure`, uses `AZURE_OPENAI_API_KEY` + `AZURE_OPENAI_ENDPOINT`) | `uv tool install "graphifyy[openai]"` |
|
||||
| `sql` | SQL schema extraction | `uv tool install "graphifyy[sql]"` |
|
||||
| `postgres` | Live PostgreSQL introspection (`--postgres DSN`) | `uv tool install "graphifyy[postgres]"` |
|
||||
| `dm` | BYOND DreamMaker `.dm`/`.dme` AST extraction (may need a C compiler + `python3-dev` if no wheel matches your platform) | `uv tool install "graphifyy[dm]"` |
|
||||
| `terraform` | Terraform / HCL `.tf`/`.tfvars`/`.hcl` AST extraction | `uv tool install "graphifyy[terraform]"` |
|
||||
| `chinese` | Chinese query segmentation (jieba) | `uv tool install "graphifyy[chinese]"` |
|
||||
| `all` | Everything above | `uv tool install "graphifyy[all]"` |
|
||||
|
||||
---
|
||||
|
||||
## Make your assistant always use the graph
|
||||
|
||||
Run this once in your project after building a graph:
|
||||
|
||||
| Platform | Command |
|
||||
|----------|---------|
|
||||
| Claude Code | `graphify claude install` |
|
||||
| CodeBuddy | `graphify codebuddy install` |
|
||||
| Codex | `graphify codex install` |
|
||||
| OpenCode | `graphify opencode install` |
|
||||
| Kilo Code | `graphify kilo install` |
|
||||
| GitHub Copilot CLI | `graphify copilot install` |
|
||||
| VS Code Copilot Chat | `graphify vscode install` |
|
||||
| Aider | `graphify aider install` |
|
||||
| OpenClaw | `graphify claw install` |
|
||||
| Factory Droid | `graphify droid install` |
|
||||
| Trae | `graphify trae install` |
|
||||
| Trae CN | `graphify trae-cn install` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Gemini CLI | `graphify gemini install` |
|
||||
| Hermes | `graphify hermes install` |
|
||||
| Kimi Code | `graphify install --platform kimi` |
|
||||
| Amp | `graphify amp install` |
|
||||
| Agent Skills (cross-framework) | `graphify agents install` (alias `graphify skills install`) |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Pi coding agent | `graphify pi install` |
|
||||
| Devin CLI | `graphify devin install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
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. On platforms that support payload-bearing hooks (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. On the others (Codex, OpenCode, Cursor, etc.), the persistent instruction files (`AGENTS.md`, `.cursor/rules/`, etc.) provide the same query-first guidance. `GRAPH_REPORT.md` is still available for broad architecture review.
|
||||
|
||||
**CodeBuddy** does the same two things as Claude Code: writes a `CODEBUDDY.md` section telling CodeBuddy to read `graphify-out/GRAPH_REPORT.md` before answering architecture questions, and installs **PreToolUse hooks** (`.codebuddy/settings.json`) that fire before Bash search commands and file reads, nudging toward `graphify query` instead.
|
||||
|
||||
**Codex** writes to `AGENTS.md` and also installs a **PreToolUse hook** in `.codex/hooks.json` that fires before every Bash tool call — same always-on mechanism as Claude Code.
|
||||
|
||||
To remove graphify from all platforms at once: `graphify uninstall` (add `--purge` to also delete `graphify-out/`). Or use the per-platform command (e.g. `graphify claude uninstall`).
|
||||
|
||||
---
|
||||
|
||||
**Kilo Code** installs the Graphify skill to `~/.config/kilo/skills/graphify/SKILL.md` and a native `/graphify` command to `~/.config/kilo/command/graphify.md`. `graphify kilo install` also writes `AGENTS.md` plus a native **`tool.execute.before` plugin** (`.kilo/plugins/graphify.js` + `.kilo/kilo.json` or `.kilo/kilo.jsonc` registration) so Kilo gets the same always-on graph reminder behavior through native `.kilo` config.
|
||||
|
||||
**Cursor** writes `.cursor/rules/graphify.mdc` with `alwaysApply: true` — Cursor includes it in every conversation automatically, no hook needed.
|
||||
|
||||
## What's in the report
|
||||
|
||||
- **God nodes** — the most-connected concepts in your project. Everything flows through these.
|
||||
- **Surprising connections** — links between things that live in different files or modules. Ranked by how unexpected they are.
|
||||
- **The "why"** — inline comments (`# NOTE:`, `# WHY:`, `# HACK:`), docstrings, and design rationale from docs are extracted as separate nodes linked to the code they explain.
|
||||
- **Suggested questions** — 4–5 questions the graph is uniquely positioned to answer.
|
||||
- **Confidence tags** — every inferred relationship is marked `EXTRACTED`, `INFERRED`, or `AMBIGUOUS`. You always know what was found vs guessed.
|
||||
|
||||
---
|
||||
|
||||
## What files it handles
|
||||
|
||||
| Type | Extensions |
|
||||
|------|-----------|
|
||||
| Code (36 tree-sitter grammars) | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .h .hpp .cu .cuh .metal .rb .cs .kt .scala .php .swift .lua .luau .zig .ps1 .psm1 .ex .exs .m .mm .jl .vue .svelte .astro .groovy .gradle .dart .v .sv .svh .sql .f .f90 .f95 .f03 .f08 .pas .pp .dpr .dpk .lpr .inc .dfm .lfm .lpk .sh .bash .json .dm .dme .dmi .dmm .dmf .sln .slnx .csproj .fsproj .vbproj .xaml .razor .cshtml` (`.dm`/`.dme` requires `uv tool install graphifyy[dm]`; CUDA `.cu`/`.cuh` and Metal `.metal` reuse the C++ grammar) |
|
||||
| Salesforce Apex | `.cls .trigger` (regex-based; classes, interfaces, enums, methods, triggers, SOQL/DML edges) |
|
||||
| Terraform / HCL | `.tf .tfvars .hcl` (requires `uv tool install graphifyy[terraform]`) |
|
||||
| MCP configs | `.mcp.json` `mcp.json` `mcp_servers.json` `claude_desktop_config.json` — extracts server nodes, package refs, env var requirements |
|
||||
| Package manifests | `apm.yml` `pyproject.toml` `go.mod` `pom.xml` — one canonical package node per package (by name) plus `depends_on` edges, so a package referenced from many manifests is a single hub |
|
||||
| Docs | `.md .mdx .qmd .html .txt .rst .yaml .yml` (markdown `[text](./other.md)` links and `[[wikilinks]]` become `references` edges between docs) |
|
||||
| Office | `.docx .xlsx` (requires `uv tool install graphifyy[office]`) |
|
||||
| Google Workspace | `.gdoc .gsheet .gslides` (opt-in; requires `gws` auth and `--google-workspace`; Sheets need `uv tool install graphifyy[google]`) |
|
||||
| PDFs | `.pdf` |
|
||||
| Images | `.png .jpg .webp .gif` |
|
||||
| Video / Audio | `.mp4 .mov .mp3 .wav` and more (requires `uv tool install graphifyy[video]`) |
|
||||
| YouTube / URLs | any video URL (requires `uv tool install graphifyy[video]`) |
|
||||
|
||||
Code is extracted locally with no API calls (AST via tree-sitter). Everything else goes through your AI assistant's model API.
|
||||
|
||||
Google Drive for desktop `.gdoc`, `.gsheet`, and `.gslides` files are shortcut
|
||||
pointers, not document content. To include native Google Docs, Sheets, and Slides
|
||||
in a headless extraction, install and authenticate the
|
||||
[`gws` CLI](https://github.com/googleworkspace/cli), then run:
|
||||
|
||||
```bash
|
||||
uv tool install "graphifyy[google]" # needed for Google Sheets table rendering
|
||||
gws auth login -s drive
|
||||
graphify extract ./docs --google-workspace
|
||||
```
|
||||
|
||||
You can also set `GRAPHIFY_GOOGLE_WORKSPACE=1`. Graphify exports shortcuts into
|
||||
`graphify-out/converted/` as Markdown sidecars, then extracts those files.
|
||||
|
||||
---
|
||||
|
||||
## Common commands
|
||||
|
||||
```bash
|
||||
/graphify . # build graph for current folder
|
||||
/graphify ./docs --update # re-extract only changed files
|
||||
/graphify . --cluster-only # rerun clustering without re-extracting
|
||||
/graphify . --cluster-only --resolution 1.5 # more granular communities
|
||||
/graphify . --cluster-only --exclude-hubs 99 # suppress utility super-hubs from god-node rankings
|
||||
/graphify . --no-viz # skip the HTML, just the report + JSON
|
||||
/graphify . --wiki # build a markdown wiki from the graph
|
||||
graphify export callflow-html # Mermaid architecture/call-flow HTML (auto-regenerates on every git commit if hook is installed)
|
||||
|
||||
/graphify query "what connects auth to the database?"
|
||||
/graphify path "UserService" "DatabasePool"
|
||||
/graphify explain "RateLimiter"
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # fetch a paper and add it
|
||||
/graphify add <youtube-url> # transcribe and add a video
|
||||
|
||||
graphify hook install # auto-rebuild on git commit
|
||||
graphify merge-graphs a.json b.json # combine two graphs
|
||||
|
||||
graphify prs # PR dashboard: CI state, review status, worktree mapping
|
||||
graphify prs 42 # deep dive on PR #42 with graph impact
|
||||
graphify prs --triage # AI ranks your review queue (uses whatever backend is configured)
|
||||
graphify prs --conflicts # PRs sharing graph communities — merge-order risk
|
||||
```
|
||||
|
||||
See the [full command reference](#full-command-reference) below.
|
||||
|
||||
---
|
||||
|
||||
## Ignoring files
|
||||
|
||||
Create a `.graphifyignore` in your project root — same syntax as `.gitignore`, including `!` negation.
|
||||
|
||||
**`.gitignore` is respected automatically.** graphify reads the `.gitignore` in each directory. If a `.graphifyignore` is also present, the two are **merged** — `.graphifyignore` patterns are evaluated last, so they win on conflicts (including `!` negations). Adding a `.graphifyignore` only ever excludes more; it never re-includes a file your `.gitignore` already excluded. Subdirectory scoping works the same way as git — an ignore file only affects its own subtree.
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
|
||||
# only index src/, ignore everything else
|
||||
*
|
||||
!src/
|
||||
!src/**
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Team setup
|
||||
|
||||
`graphify-out/` is meant to be committed to git so everyone on the team starts with a map.
|
||||
|
||||
**Recommended `.gitignore` additions:**
|
||||
```
|
||||
graphify-out/cost.json # local only
|
||||
# graphify-out/cache/ # optional: commit for speed, skip to keep repo small
|
||||
```
|
||||
|
||||
> `manifest.json` is now portable — keys are stored as relative paths and re-anchored on load, so committing it is safe and avoids a full rebuild on first checkout.
|
||||
|
||||
**Workflow:**
|
||||
1. One person runs `/graphify .` and commits `graphify-out/`.
|
||||
2. Everyone pulls — their assistant reads the graph immediately.
|
||||
3. Run `graphify hook install` to auto-rebuild after each commit (AST only, no API cost). This also sets up a git merge driver so `graph.json` is never left with conflict markers — two devs committing in parallel get their graphs union-merged automatically.
|
||||
4. When docs or papers change, run `/graphify --update` to refresh those nodes.
|
||||
|
||||
---
|
||||
|
||||
## Using the graph directly
|
||||
|
||||
```bash
|
||||
# query the graph from the terminal
|
||||
graphify query "show the auth flow"
|
||||
graphify query "what connects DigestAuth to Response?" --graph graphify-out/graph.json
|
||||
|
||||
# expose the graph as an MCP server (for repeated tool-call access)
|
||||
python -m graphify.serve graphify-out/graph.json
|
||||
python -m graphify.serve --graph graphify-out/graph.json # --graph flag also accepted
|
||||
|
||||
# register with Kimi Code:
|
||||
kimi mcp add --transport stdio graphify -- python -m graphify.serve graphify-out/graph.json
|
||||
|
||||
# or serve over HTTP so a whole team points at one URL (no local graphify needed):
|
||||
python -m graphify.serve graphify-out/graph.json --transport http --port 8080
|
||||
python -m graphify.serve graphify-out/graph.json --transport http --host 0.0.0.0 --api-key "$SECRET"
|
||||
```
|
||||
|
||||
The MCP server gives your assistant structured access: `query_graph`, `get_node`, `get_neighbors`, `shortest_path`, `list_prs`, `get_pr_impact`, `triage_prs`.
|
||||
|
||||
### Shared HTTP server
|
||||
|
||||
`--transport stdio` (the default) spawns one local server per developer. `--transport http` serves the same tools over the MCP Streamable HTTP transport, so a single shared process can serve the graph for the whole team — clients point their IDE MCP config at `http://<host>:8080/mcp` instead of running graphify locally.
|
||||
|
||||
| Flag | Default | Purpose |
|
||||
|---|---|---|
|
||||
| `--transport {stdio,http}` | `stdio` | Transport to serve on |
|
||||
| `--host` | `127.0.0.1` | HTTP bind host (use `0.0.0.0` to expose beyond localhost) |
|
||||
| `--port` | `8080` | HTTP bind port |
|
||||
| `--api-key` | env `GRAPHIFY_API_KEY` | Require `Authorization: Bearer <key>` (or `X-API-Key`) |
|
||||
| `--path` | `/mcp` | HTTP mount path |
|
||||
| `--json-response` | off | Return plain JSON instead of SSE streams |
|
||||
| `--stateless` | off | No per-session state (for load-balanced / CI deployments) |
|
||||
| `--session-timeout` | `3600` | Reap idle stateful sessions after N seconds (`0` disables) |
|
||||
|
||||
The default `127.0.0.1` bind is loopback-only. Set `--host 0.0.0.0` **and** `--api-key` together when exposing on a shared host. Run it in a container:
|
||||
|
||||
```bash
|
||||
docker build -t graphify .
|
||||
docker run -p 8080:8080 -v "$(pwd)/graphify-out:/data" graphify \
|
||||
/data/graph.json --transport http --host 0.0.0.0 --api-key "$SECRET"
|
||||
```
|
||||
|
||||
> **WSL / Linux note:** Ubuntu ships `python3`, not `python`. Use a venv to avoid conflicts:
|
||||
> ```bash
|
||||
> python3 -m venv .venv && .venv/bin/pip install "graphifyy[mcp]"
|
||||
> ```
|
||||
|
||||
---
|
||||
|
||||
## Environment variables
|
||||
|
||||
These are only needed for **headless / CI extraction** (`graphify extract`). When running via the `/graphify` skill inside your IDE, the model API is provided by your IDE session — no extra keys needed.
|
||||
|
||||
| Variable | Used for | When required |
|
||||
|---|---|---|
|
||||
| `ANTHROPIC_API_KEY` | Claude (Anthropic) backend | `--backend claude` |
|
||||
| `ANTHROPIC_BASE_URL` | Anthropic-compatible endpoint URL (LiteLLM proxy, gateways, ...) | `--backend claude` (default: `https://api.anthropic.com`) |
|
||||
| `ANTHROPIC_MODEL` | Model name for the Claude backend — for custom endpoints, use the model name/alias your server exposes | `--backend claude` (default: `claude-sonnet-4-6`) |
|
||||
| `GEMINI_API_KEY` or `GOOGLE_API_KEY` | Google Gemini backend | `--backend gemini` |
|
||||
| `OPENAI_API_KEY` | OpenAI or OpenAI-compatible APIs | `--backend openai` (local servers accept any non-empty value) |
|
||||
| `OPENAI_BASE_URL` | OpenAI-compatible server URL (llama.cpp, vLLM, LM Studio, ...) | `--backend openai` (default: `https://api.openai.com/v1`) |
|
||||
| `OPENAI_MODEL` | Model name for the OpenAI backend — for self-hosted servers, use the model name/alias your server exposes (check its `/v1/models` endpoint), e.g. `LFM2.5-8B-A1B-UD-Q4_K_XL` for llama.cpp | `--backend openai` (default: `gpt-4.1-mini`) |
|
||||
| `DEEPSEEK_API_KEY` | DeepSeek backend | `--backend deepseek` |
|
||||
| `MOONSHOT_API_KEY` | Kimi Code backend | `--backend kimi` |
|
||||
| `OLLAMA_BASE_URL` | Ollama local inference URL | `--backend ollama` (default: `http://localhost:11434`) |
|
||||
| `OLLAMA_MODEL` | Ollama model name | `--backend ollama` (default: auto-detect) |
|
||||
| `GRAPHIFY_OLLAMA_NUM_CTX` | Override Ollama KV-cache window size | optional — auto-sized by default |
|
||||
| `GRAPHIFY_OLLAMA_KEEP_ALIVE` | Minutes to keep Ollama model loaded | optional — set `0` to unload after each chunk |
|
||||
| `AZURE_OPENAI_API_KEY` | Azure OpenAI Service backend | `--backend azure` |
|
||||
| `AZURE_OPENAI_ENDPOINT` | Azure resource endpoint URL | `--backend azure` (required alongside API key) |
|
||||
| `AZURE_OPENAI_API_VERSION` | Azure API version override | optional — default `2024-12-01-preview` |
|
||||
| `AZURE_OPENAI_DEPLOYMENT` or `GRAPHIFY_AZURE_MODEL` | Azure deployment name | optional — default `gpt-4o` |
|
||||
| `AWS_*` / `~/.aws/credentials` | AWS Bedrock — standard credential chain | `--backend bedrock` (no API key, uses IAM) |
|
||||
| `GRAPHIFY_MAX_WORKERS` | AST parallelism thread count | optional — also `--max-workers` flag |
|
||||
| `GRAPHIFY_MAX_OUTPUT_TOKENS` | Raise output cap for dense corpora | optional — e.g. `32768` for large files |
|
||||
| `GRAPHIFY_API_TIMEOUT` | Per-call timeout in seconds for HTTP, claude-cli, and Anthropic SDK backends (default: 600) | optional — also `--api-timeout` flag |
|
||||
| `GRAPHIFY_MAX_RETRIES` | How many times to retry a rate-limited (429) request before giving up (default: 6; honors `Retry-After`) | optional — raise for strict per-org limits (e.g. kimi); `0` disables |
|
||||
| `GRAPHIFY_FORCE` | Force graph rebuild even with fewer nodes | optional — also `--force` flag |
|
||||
| `GRAPHIFY_GOOGLE_WORKSPACE` | Auto-enable Google Workspace export | optional — set to `1` |
|
||||
| `GRAPHIFY_TRIAGE_BACKEND` | Backend for `graphify prs --triage` | optional — auto-detected from available keys |
|
||||
| `GRAPHIFY_TRIAGE_MODEL` | Model override for triage | optional — e.g. `claude-opus-4-7` |
|
||||
| `GRAPHIFY_QUERY_LOG` | Override query log path (default: `~/.cache/graphify-queries.log`) | optional — set to empty or `/dev/null` to silence |
|
||||
| `GRAPHIFY_QUERY_LOG_DISABLE` | Set to `1` to disable query logging entirely | optional |
|
||||
| `GRAPHIFY_QUERY_LOG_RESPONSES` | Set to `1` to also log full subgraph responses (off by default) | optional |
|
||||
| `GRAPHIFY_MAX_GRAPH_BYTES` | Override the 512 MiB graph.json size cap — e.g. `700MB`, `2GB`, or plain bytes | optional — useful for very large corpora |
|
||||
| `GRAPHIFY_LLM_TEMPERATURE` | Override LLM temperature for semantic extraction — e.g. `0.7`, or `none` to omit | optional — auto-omitted for o1/o3/o4/gpt-5 reasoning models |
|
||||
|
||||
---
|
||||
|
||||
## Privacy
|
||||
|
||||
- **Code files** — processed locally via tree-sitter. Nothing leaves your machine. A code-only corpus requires no API key — `graphify extract` runs fully offline.
|
||||
- **Video / audio** — transcribed locally with faster-whisper. Nothing leaves your machine.
|
||||
- **Docs, PDFs, images** — sent to your AI assistant for semantic extraction (via the `/graphify` skill, using whatever model your IDE session runs). Headless `graphify extract` requires `GEMINI_API_KEY` / `GOOGLE_API_KEY` (Gemini), `MOONSHOT_API_KEY` (Kimi), `ANTHROPIC_API_KEY` (Claude), `OPENAI_API_KEY` (OpenAI), `DEEPSEEK_API_KEY` (DeepSeek), a running Ollama instance (`OLLAMA_BASE_URL`), AWS credentials via the standard provider chain (Bedrock - no API key needed, uses IAM), or the `claude` CLI binary (Claude Code - no API key needed, uses your Claude subscription). The `--dedup-llm` flag uses the same key.
|
||||
- **Data residency** — `graphify extract` auto-detects which provider to use based on which API key is set (priority: Gemini → Kimi → Claude → OpenAI → DeepSeek → Azure → Bedrock → Ollama). For code with data-residency requirements, use `--backend ollama` (fully local) or pass an explicit `--backend` flag. Kimi (`MOONSHOT_API_KEY`) routes to Moonshot AI servers in China.
|
||||
- No telemetry, no usage tracking, no analytics.
|
||||
- **Query logging** — every `graphify query`, `graphify path`, `graphify explain`, and MCP `query_graph` call is logged to `~/.cache/graphify-queries.log` in JSON Lines format (timestamp, question, corpus, nodes returned, duration). Full subgraph responses are **not** stored by default. Set `GRAPHIFY_QUERY_LOG_DISABLE=1` to opt out, or `GRAPHIFY_QUERY_LOG=/dev/null` to silence without disabling the code path.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**`graphify: command not found` after installing**
|
||||
The CLI is installed but its bin directory isn't on your shell's `PATH`. Pick the fix for how you installed:
|
||||
- **uv** (`uv tool install graphifyy`): the command lands in uv's tool bin dir (`~/.local/bin`), which a fresh macOS/zsh setup often doesn't have on `PATH`. Run `uv tool update-shell`, then open a new terminal. (Find the dir with `uv tool dir --bin`.)
|
||||
- **pipx** (`pipx install graphifyy`): run `pipx ensurepath`, then open a new terminal.
|
||||
- **pip** (`pip install graphifyy`): pip installs scripts to a user bin dir that may not be on `PATH` — add `~/Library/Python/3.x/bin` (macOS) or `~/.local/bin` (Linux) to your `PATH` in `~/.zshrc`/`~/.bashrc`, or just run `python -m graphify`.
|
||||
|
||||
**`uvx graphify …` or `uv tool run graphify …` fails to resolve `graphify`**
|
||||
The PyPI package is `graphifyy`; `graphify` is only the command it provides. `uv tool run` treats the first word as a *package name*, so it looks for a package called `graphify` and reports `No solution found … no versions of graphify`. Name the package explicitly: `uvx --from graphifyy graphify install` (same as `uv tool run --from graphifyy graphify install`). Or `uv tool install graphifyy` once and then call `graphify` directly.
|
||||
|
||||
**`python -m graphify` works but `graphify` command doesn't**
|
||||
Your shell's `PATH` doesn't include the bin directory the command was installed to. Prefer `uv tool install` / `pipx install` over plain `pip`, then run `uv tool update-shell` / `pipx ensurepath` and open a new terminal (see the install notes above).
|
||||
|
||||
**`/graphify .` causes "path not recognized" in PowerShell**
|
||||
PowerShell treats a leading `/` as a path separator. Use `graphify .` (no slash) on Windows.
|
||||
|
||||
**Graph has fewer nodes after `--update` or rebuild**
|
||||
If a refactor deleted files, the old nodes linger. Pass `--force` (or set `GRAPHIFY_FORCE=1`) to overwrite even when the rebuild has fewer nodes.
|
||||
|
||||
**Graph has duplicate nodes for the same entity (ghost duplicates)**
|
||||
Ghost duplicates (same symbol appearing twice — once from AST extraction with a source location, once from semantic extraction without) are now automatically merged at build time. If you see this in a graph built before v0.8.33, run a full re-extract to clean up:
|
||||
```bash
|
||||
graphify extract . --force
|
||||
```
|
||||
|
||||
**Ollama runs out of VRAM / context window exceeded**
|
||||
The KV-cache window is auto-sized but may be too large for your GPU. Reduce it:
|
||||
```bash
|
||||
GRAPHIFY_OLLAMA_NUM_CTX=8192 graphify extract ./docs --backend ollama --token-budget 4000
|
||||
```
|
||||
|
||||
**`LLM returned invalid JSON` / `Unterminated string` warnings**
|
||||
The model's JSON response hit its output-token limit and was cut off mid-string. graphify auto-recovers (it splits the chunk and re-extracts the halves, and an oversized single document is first sliced at heading/paragraph boundaries so the whole file is still covered), so these warnings are noisy but not data loss. To reduce the churn, raise the output cap or shrink each chunk's output:
|
||||
```bash
|
||||
GRAPHIFY_MAX_OUTPUT_TOKENS=16384 graphify extract . --mode deep # lift the cap
|
||||
graphify extract . --mode deep --token-budget 4000 # smaller input chunks -> smaller output
|
||||
```
|
||||
With a cloud gateway like OpenRouter, prefer `--backend openai` (set `OPENAI_BASE_URL`) over the Ollama shim — it's a cleaner OpenAI-compatible path. If the model has its own max-output ceiling, lowering `--token-budget` is the reliable lever.
|
||||
|
||||
**Graph HTML is too large to open in a browser (>5000 nodes)**
|
||||
Skip HTML generation and use the JSON directly:
|
||||
```bash
|
||||
graphify cluster-only ./my-project --no-viz
|
||||
graphify query "..."
|
||||
```
|
||||
|
||||
**`graph.json` has conflict markers after two devs commit at once**
|
||||
Run `graphify hook install` — it sets up a git merge driver that union-merges `graph.json` automatically so conflicts never happen.
|
||||
|
||||
**Extraction returns empty nodes/edges for docs or PDFs**
|
||||
Docs, PDFs, and images require an LLM call — code-only corpora need no key. Check that your API key is set and the backend is correct:
|
||||
```bash
|
||||
ANTHROPIC_API_KEY=sk-... graphify extract ./docs --backend claude
|
||||
```
|
||||
|
||||
**Skill version mismatch warning in your IDE**
|
||||
Your installed graphify version is different from the skill file. Update:
|
||||
```bash
|
||||
uv tool upgrade graphifyy
|
||||
graphify install # overwrites the skill file
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Full command reference
|
||||
|
||||
```
|
||||
/graphify # run on current directory
|
||||
/graphify ./raw # run on a specific folder
|
||||
/graphify ./raw --mode deep # more aggressive INFERRED edge extraction
|
||||
/graphify ./raw --update # re-extract only changed files, merge into existing graph
|
||||
/graphify ./raw --watch # notify when new files appear
|
||||
/graphify ./raw --mode deep # more aggressive relationship extraction
|
||||
/graphify ./raw --update # re-extract only changed files
|
||||
/graphify ./raw --directed # preserve edge direction
|
||||
/graphify ./raw --cluster-only # rerun clustering on existing graph
|
||||
/graphify ./raw --no-viz # skip HTML visualization
|
||||
/graphify ./raw --obsidian # generate Obsidian vault
|
||||
/graphify ./raw --obsidian --obsidian-dir ~/vault # write into an existing vault (never overwrites your own notes or .obsidian config)
|
||||
/graphify ./raw --wiki # build agent-crawlable markdown wiki
|
||||
/graphify ./raw --svg # export graph.svg
|
||||
/graphify ./raw --graphml # export for Gephi / yEd
|
||||
/graphify ./raw --neo4j # generate cypher.txt for Neo4j
|
||||
/graphify ./raw --neo4j-push bolt://localhost:7687
|
||||
/graphify ./raw --falkordb # generate cypher.txt for FalkorDB
|
||||
/graphify ./raw --falkordb-push falkordb://localhost:6379
|
||||
/graphify ./raw --watch # auto-sync as files change
|
||||
/graphify ./raw --mcp # start MCP stdio server
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # fetch a paper, save, update graph
|
||||
/graphify add https://x.com/karpathy/status/... # fetch a tweet
|
||||
/graphify add <url> --author "Karpathy" --contributor "safi"
|
||||
/graphify add https://arxiv.org/abs/1706.03762
|
||||
/graphify add <video-url>
|
||||
/graphify add https://... --author "Name" --contributor "Name"
|
||||
|
||||
/graphify query "what connects attention to the optimizer?" # BFS — broad context
|
||||
/graphify query "how does the encoder reach the loss?" --dfs # DFS — trace a path
|
||||
/graphify query "..." --budget 1500 # cap at N tokens
|
||||
/graphify query "what connects attention to the optimizer?"
|
||||
/graphify query "..." --dfs --budget 1500
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
/graphify path "DigestAuth" "Response" # shortest path between two concepts
|
||||
/graphify explain "SwinTransformer" # plain-language node explanation
|
||||
graphify save-result --question "Q" --answer "A" --nodes Foo Bar --outcome useful # record how a Q&A turned out (work memory; outcome ∈ useful|dead_end|corrected)
|
||||
graphify reflect # aggregate graphify-out/memory/ outcomes into reflections/LESSONS.md
|
||||
graphify reflect --if-stale # no-op when LESSONS.md is already newer than every input (cheap to run each session)
|
||||
graphify reflect --out docs/LESSONS.md # write the lessons doc somewhere else
|
||||
graphify reflect --graph graphify-out/graph.json # group lessons by community + write the work-memory overlay (.graphify_learning.json)
|
||||
# the overlay tags nodes preferred/tentative/contested (recency-weighted, with provenance);
|
||||
# graphify explain / query then show a "Lesson:" hint, flagged "code changed — re-verify" when the source moved on
|
||||
|
||||
/graphify ./raw --html # also export graph.html (browser, no Obsidian needed)
|
||||
/graphify ./raw --svg # also export graph.svg (embeds in Notion, GitHub)
|
||||
/graphify ./raw --neo4j # generate cypher.txt for Neo4j import
|
||||
/graphify ./raw --mcp # start MCP stdio server for agent access
|
||||
graphify uninstall # remove from all platforms in one shot
|
||||
graphify uninstall --purge # also delete graphify-out/
|
||||
graphify uninstall --project --platform codex # remove project-scoped install files only
|
||||
|
||||
graphify hook install # post-commit + post-checkout hooks
|
||||
graphify hook uninstall
|
||||
graphify hook status
|
||||
|
||||
# always-on assistant instructions - platform-specific
|
||||
graphify claude install # CLAUDE.md + PreToolUse hook (Claude Code)
|
||||
graphify claude uninstall
|
||||
graphify codebuddy install # CODEBUDDY.md + PreToolUse hook (CodeBuddy)
|
||||
graphify codebuddy uninstall
|
||||
graphify codex install # AGENTS.md + PreToolUse hook in .codex/hooks.json (Codex)
|
||||
graphify opencode install # AGENTS.md + tool.execute.before plugin (OpenCode)
|
||||
graphify kilo install # native Kilo skill + /graphify command + AGENTS.md + .kilo plugin
|
||||
graphify kilo uninstall
|
||||
graphify cursor install # .cursor/rules/graphify.mdc (Cursor)
|
||||
graphify cursor uninstall
|
||||
graphify gemini install # GEMINI.md + BeforeTool hook (Gemini CLI)
|
||||
graphify gemini uninstall
|
||||
graphify copilot install # skill file (GitHub Copilot CLI)
|
||||
graphify copilot uninstall
|
||||
graphify aider install # AGENTS.md (Aider)
|
||||
graphify aider uninstall
|
||||
graphify claw install # AGENTS.md (OpenClaw)
|
||||
graphify claw uninstall
|
||||
graphify droid install # AGENTS.md (Factory Droid)
|
||||
graphify droid uninstall
|
||||
graphify trae install # AGENTS.md (Trae)
|
||||
graphify trae uninstall
|
||||
graphify trae-cn install # AGENTS.md (Trae CN)
|
||||
graphify trae-cn uninstall
|
||||
graphify hermes install # AGENTS.md + ~/.hermes/skills/ (Hermes)
|
||||
graphify hermes uninstall
|
||||
graphify amp install # skill file (Amp)
|
||||
graphify amp uninstall
|
||||
graphify agents install # ~/.agents/skills/ + AGENTS.md (cross-framework; alias: graphify skills)
|
||||
graphify agents uninstall
|
||||
graphify kiro install # .kiro/skills/ + .kiro/steering/graphify.md (Kiro IDE/CLI)
|
||||
graphify kiro uninstall
|
||||
graphify pi install # skill file (Pi coding agent)
|
||||
graphify pi uninstall
|
||||
graphify devin install # skill file + .windsurf/rules/graphify.md (Devin CLI)
|
||||
graphify devin uninstall
|
||||
graphify antigravity install # .agents/rules + .agents/workflows (Google Antigravity)
|
||||
graphify antigravity uninstall
|
||||
|
||||
graphify extract ./docs # headless LLM extraction for CI (no IDE needed)
|
||||
graphify extract ./docs --backend gemini # explicit backend: gemini, kimi, claude, openai, deepseek, ollama, bedrock, or claude-cli
|
||||
graphify extract ./docs --backend gemini --model gemini-3.1-pro-preview
|
||||
graphify extract ./docs --backend ollama # local Ollama (set OLLAMA_BASE_URL / OLLAMA_MODEL) - no API key needed for loopback
|
||||
OPENAI_BASE_URL=http://localhost:8080/v1 OPENAI_MODEL=my-model graphify extract ./docs --backend openai # any OpenAI-compatible server (llama.cpp, vLLM, LM Studio)
|
||||
ANTHROPIC_BASE_URL=http://localhost:4000 ANTHROPIC_MODEL=my-model graphify extract ./docs --backend claude # any Anthropic-compatible endpoint (LiteLLM proxy, gateways)
|
||||
GRAPHIFY_OLLAMA_NUM_CTX=32768 graphify extract ./docs --backend ollama # override KV-cache window (auto-sized by default)
|
||||
GRAPHIFY_OLLAMA_KEEP_ALIVE=0 graphify extract ./docs --backend ollama # unload model after each chunk (saves VRAM on small GPUs)
|
||||
graphify extract ./docs --backend bedrock # AWS Bedrock via IAM - no API key, uses AWS credential chain
|
||||
graphify extract ./docs --backend claude-cli # route through Claude Code CLI - no API key, uses your Claude subscription
|
||||
graphify extract ./docs --backend azure # Azure OpenAI (set AZURE_OPENAI_API_KEY + AZURE_OPENAI_ENDPOINT)
|
||||
graphify extract ./docs --max-workers 16 # AST parallelism (also GRAPHIFY_MAX_WORKERS)
|
||||
graphify extract --postgres "postgresql://user:pass@host/db" # introspect live PostgreSQL schema directly
|
||||
graphify extract ./my-workspace --cargo # introspect Rust Cargo workspace dependencies directly
|
||||
graphify extract ./docs --token-budget 30000 # smaller semantic chunks for local/small models
|
||||
graphify extract ./docs --max-concurrency 2 # fewer parallel LLM calls (useful for local inference)
|
||||
graphify extract ./docs --api-timeout 900 # longer HTTP timeout for slow local models (default 600s)
|
||||
graphify extract ./docs --google-workspace # export .gdoc/.gsheet/.gslides via gws before extraction
|
||||
graphify extract ./docs --mode deep # richer semantic extraction via extended system prompt
|
||||
graphify extract ./docs --no-cluster # raw extraction only, skip clustering
|
||||
graphify extract ./docs --timing # print per-stage wall-clock timings to stderr (also works on cluster-only)
|
||||
graphify extract ./docs --force # overwrite graph.json even if new graph has fewer nodes (use after refactors or to clear ghost duplicates)
|
||||
graphify extract ./docs --dedup-llm # LLM tiebreaker for ambiguous entity pairs (uses same API key)
|
||||
graphify extract ./docs --global --as myrepo # extract and register into the cross-project global graph
|
||||
GRAPHIFY_MAX_OUTPUT_TOKENS=32768 graphify extract ./docs --backend claude # raise output cap for dense corpora
|
||||
|
||||
graphify export callflow-html # graphify-out/<project>-callflow.html
|
||||
graphify export callflow-html --max-sections 8 # cap generated architecture sections
|
||||
graphify export callflow-html --output docs/arch.html
|
||||
graphify export callflow-html ./some-repo/graphify-out
|
||||
|
||||
graphify global add graphify-out/graph.json --as myrepo # register a project graph into ~/.graphify/global-graph.json
|
||||
graphify global remove myrepo # remove a project from the global graph
|
||||
graphify global list # show all registered repos + node/edge counts
|
||||
graphify global path # print path to the global graph file
|
||||
|
||||
graphify prs # PR dashboard: CI, review, worktree, graph impact
|
||||
graphify prs 42 # deep dive on PR #42
|
||||
graphify prs --triage # AI triage ranking (auto-detects backend from env)
|
||||
graphify prs --worktrees # worktree → branch → PR mapping
|
||||
graphify prs --conflicts # PRs sharing graph communities (merge-order risk)
|
||||
graphify prs --base main # filter to PRs targeting a specific base branch
|
||||
graphify prs --repo owner/repo # run against a different GitHub repo
|
||||
GRAPHIFY_TRIAGE_BACKEND=kimi graphify prs --triage # use a specific backend for triage
|
||||
|
||||
graphify clone https://github.com/karpathy/nanoGPT
|
||||
graphify merge-graphs a.json b.json --out merged.json
|
||||
graphify --version # print installed version
|
||||
graphify watch ./src
|
||||
graphify check-update ./src
|
||||
graphify update ./src
|
||||
graphify update ./src --no-cluster # skip reclustering, write raw AST graph only
|
||||
graphify update ./src --force # overwrite even if new graph has fewer nodes
|
||||
graphify cluster-only ./my-project
|
||||
graphify cluster-only ./my-project --graph path/to/graph.json # custom graph location
|
||||
graphify cluster-only ./my-project --max-concurrency 16 --batch-size 200 # parallel community labeling (large graphs)
|
||||
graphify cluster-only ./my-project --resolution 1.5 # more, smaller communities
|
||||
graphify cluster-only ./my-project --exclude-hubs 99 # exclude p99 degree nodes from partitioning
|
||||
graphify cluster-only ./my-project --no-label # keep "Community N" placeholders
|
||||
graphify cluster-only ./my-project --backend=gemini # backend for community naming
|
||||
graphify cluster-only ./my-project --backend=gemini --model gemini-2.5-pro # specific model
|
||||
graphify label ./my-project # (re)name communities with the configured backend
|
||||
graphify label ./my-project --backend=openai --model gpt-4o # force a specific backend and model
|
||||
```
|
||||
|
||||
Works with any mix of file types in the same folder:
|
||||
> **Community names:** inside an agent (Claude Code, Gemini CLI) the agent names communities itself. When you run the bare CLI, `cluster-only` auto-names them with the configured backend (built-in or custom OpenAI-compatible provider) — pass `--no-label` to keep `Community N`, or run `graphify label` to (re)generate names on demand.
|
||||
|
||||
| Type | Extensions | How it's extracted |
|
||||
|------|-----------|-------------------|
|
||||
| Code | `.py .ts .tsx .js .go .rs` | AST (deterministic) + call-graph pass (INFERRED) |
|
||||
| Code | `.java .cpp .c .rb .swift .kt` | Claude semantic extraction |
|
||||
| Documents | `.md .txt .rst` | Concepts + relationships via Claude |
|
||||
| Papers | `.pdf` | Citation mining + concept extraction |
|
||||
| Images | `.png .jpg .webp .gif .svg` | Claude vision — screenshots, charts, whiteboards, any language |
|
||||
---
|
||||
|
||||
## What you get
|
||||
## Learn more
|
||||
|
||||
After running, Claude outputs three things directly in chat:
|
||||
- [How it works](docs/how-it-works.md) — the extraction pipeline, community detection, confidence scoring, benchmarks
|
||||
- [ARCHITECTURE.md](ARCHITECTURE.md) — module breakdown, how to add a language
|
||||
- [Optional integrations](docs/docker-mcp-sqlite.md) — Docker MCP Toolkit + SQLite
|
||||
|
||||
**God nodes** — highest-degree concepts (what everything connects through)
|
||||
---
|
||||
|
||||
**Surprising connections** — cross-community edges; relationships between concepts in different clusters that you didn't know to look for
|
||||
## Built on graphify — Penpax
|
||||
|
||||
**Suggested questions** — 4-5 questions the graph is uniquely positioned to answer, with the reason why (which bridge node makes it interesting, which community boundary it crosses)
|
||||
[**Penpax**](https://graphifylabs.ai) is the always-on layer built on top of graphify — it applies the same graph approach to your entire working life: meetings, browser history, emails, files, and code, updating continuously in the background.
|
||||
|
||||
The full GRAPH_REPORT.md adds community summaries with cohesion scores and a list of ambiguous edges for review.
|
||||
Built for people whose work lives across hundreds of conversations and documents they can never fully reconstruct. No cloud, fully on-device.
|
||||
|
||||
## Key files explained
|
||||
**Free trial launching soon.** [Join the waitlist →](https://graphifylabs.ai)
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `GRAPH_REPORT.md` | The audit report. God nodes, surprising connections, community cohesion scores, ambiguous edge list, suggested questions. |
|
||||
| `graph.json` | Persistent graph in node-link format. Load it with NetworkX or push to Neo4j. Survives sessions. |
|
||||
| `obsidian/` | Wikilink vault. Open in Obsidian → enable graph view → see communities as clusters. Filter by tag, search across everything. |
|
||||
| `.graphify/cache/` | SHA256-based per-file cache. A re-run on an unchanged corpus takes seconds. |
|
||||
| `.graphify/memory/` | Q&A feedback loop. Every `/graphify query` answer is saved here. Next `--update` extracts it into the graph. |
|
||||
---
|
||||
|
||||
## What this skill will NOT do
|
||||
<details>
|
||||
<summary>Contributing</summary>
|
||||
|
||||
- **Won't invent edges** — `AMBIGUOUS` exists so uncertain relationships are flagged, not hidden. If the connection isn't clear, it's tagged, not fabricated.
|
||||
- **Won't claim the graph is useful when it isn't** — a corpus over 2M words or 200 files gets a cost warning before proceeding.
|
||||
- **Won't re-extract unchanged files** — SHA256 cache ensures warm re-runs skip everything that hasn't changed.
|
||||
- **Won't visualize graphs over 5,000 nodes** — use `--no-viz` or query instead.
|
||||
- **Won't download datasets or set up infrastructure** — graphify reads your files. What you put in the folder is what it works with.
|
||||
- **Won't implement baselines or run experiments** — it reads and maps. Analysis is yours.
|
||||
### Development setup
|
||||
|
||||
## Design principles
|
||||
The project uses [uv](https://docs.astral.sh/uv/) for dev workflow. Install it once, then:
|
||||
|
||||
1. **Extraction quality is everything** — clustering is downstream of it. A bad graph clusters into bad communities. The AST + call-graph pass exists because deterministic beats probabilistic for code.
|
||||
2. **Show the numbers** — cohesion is `0.91`, not "good". Token cost is always printed. You know what you spent.
|
||||
3. **The best output is what you didn't know** — Surprising Connections is not optional. God nodes you probably already suspected. Cross-community edges are what you came for.
|
||||
4. **The graph earns its complexity** — below a certain density, just use Claude directly. The graph adds value when you have more than you can hold in context across sessions.
|
||||
5. **What you ask grows the graph** — query results are filed back in automatically. The corpus is not static.
|
||||
6. **Honest uncertainty** — `EXTRACTED`, `INFERRED`, `AMBIGUOUS` are not cosmetic labels. They are the difference between trusting the graph and being misled by it.
|
||||
|
||||
## Contributing
|
||||
|
||||
**Adding worked examples**
|
||||
|
||||
Worked examples are the most trust-building part of this project. To add one:
|
||||
|
||||
1. Pick a real corpus (people should be able to verify the output)
|
||||
2. Run the skill: `/graphify <path>`
|
||||
3. Save the full output to `worked/{corpus_slug}/`
|
||||
4. Write a `review.md` that honestly evaluates:
|
||||
- What the graph got right
|
||||
- What edges it correctly flagged AMBIGUOUS
|
||||
- Any mistakes or missed connections
|
||||
- Any surprising connections that were genuinely surprising
|
||||
5. Submit a PR with all of the above
|
||||
|
||||
**Improving extraction**
|
||||
|
||||
If you find a file type or language where extraction is poor, open an issue with a minimal reproduction case. The best bug reports include: the input file, the extraction output (`.graphify/cache/` entry), and what was missed or invented.
|
||||
|
||||
**Adding domain knowledge**
|
||||
|
||||
If corpora in your domain consistently contain structures graphify doesn't extract well (e.g., legal documents, lab notebooks, musical scores), open a discussion with examples.
|
||||
|
||||
## Worked examples
|
||||
|
||||
| Corpus | Type | Eval report |
|
||||
|--------|------|-------------|
|
||||
| httpx (Python HTTP client) | Codebase | `tests/EVAL_httpx.md` + `tests/GRAPH_REPORT_httpx.md` |
|
||||
| Mixed corpus (code + paper + Arabic image) | Multi-type | `tests/EVAL_mixed_corpus.md` |
|
||||
|
||||
Each includes the full graph output and an honest evaluation of what the skill got right and wrong.
|
||||
|
||||
## Tech stack
|
||||
|
||||
| Layer | Library | Why |
|
||||
|-------|---------|-----|
|
||||
| Graph | NetworkX | Pure Python, same internals as MS GraphRAG |
|
||||
| Community detection | Leiden via graspologic | Better than K-means for sparse graphs |
|
||||
| Code parsing | tree-sitter | Multi-language AST, deterministic, zero hallucination |
|
||||
| Extraction | Claude (parallel subagents) | Reads anything, outputs structured graph data |
|
||||
| Visualization | Obsidian vault | Native graph view, wikilinks, no server needed |
|
||||
|
||||
No Neo4j required. No dashboards. No server. Runs entirely locally.
|
||||
|
||||
## Files
|
||||
```bash
|
||||
git clone https://github.com/safishamsi/graphify.git
|
||||
cd graphify
|
||||
git checkout v8 # active development branch
|
||||
|
||||
# Create the project venv and install graphify + all extras + the dev group
|
||||
# (pytest). uv installs the dev dependency group by default; pass --no-dev to
|
||||
# skip it.
|
||||
uv sync --all-extras
|
||||
```
|
||||
graphify/
|
||||
├── detect.py detect file types, auto-exclude venvs/caches/node_modules; scan .graphify/memory/
|
||||
├── extract.py AST extraction (Python, TypeScript, JavaScript, Go, Rust) + call-graph pass
|
||||
├── build.py assemble NetworkX graph from extraction JSON; schema-validates before assembly
|
||||
├── cluster.py Leiden community detection, cohesion scoring
|
||||
├── analyze.py god nodes, bridge nodes, surprising connections, suggested questions, graph diff
|
||||
├── report.py render GRAPH_REPORT.md
|
||||
├── export.py Obsidian vault, graph.json, graph.html, graph.svg, Neo4j Cypher, Canvas
|
||||
├── ingest.py fetch URLs (arXiv, Twitter/X, PDF, any webpage); save Q&A to .graphify/memory/
|
||||
├── cache.py SHA256-based per-file extraction cache; check_semantic_cache / save_semantic_cache
|
||||
├── security.py URL validation (http/https only), safe fetch with size cap, path guards, label sanitisation
|
||||
├── validate.py JSON schema checks on extraction output
|
||||
├── serve.py MCP stdio server — query_graph, get_node, get_neighbors, shortest_path, god_nodes
|
||||
└── watch.py fs watcher, writes flag file when new files appear
|
||||
|
||||
skills/graphify/
|
||||
└── skill.md the Claude Code skill — the full pipeline the agent runs step by step
|
||||
|
||||
SECURITY.md threat model, mitigations, vulnerability reporting
|
||||
tests/ 163 tests, one file per module
|
||||
pyproject.toml pip install graphify | pip install graphify[mcp,neo4j,pdf,watch]
|
||||
Verify the editable install:
|
||||
```bash
|
||||
uv run graphify --version
|
||||
uv run python -c "import graphify; print(graphify.__file__)"
|
||||
```
|
||||
|
||||
### Running tests
|
||||
|
||||
```bash
|
||||
uv run pytest tests/ -q # run the full suite
|
||||
uv run pytest tests/test_extract.py -q # one module
|
||||
uv run pytest tests/ -q -k "python" # filter by name
|
||||
```
|
||||
|
||||
> macOS note: the test suite includes both `sample.f90` and `sample.F90` fixtures. These collide on case-insensitive HFS+ / APFS file systems. Run on Linux or in a Docker container if you need to test both Fortran variants simultaneously.
|
||||
|
||||
### Git workflow
|
||||
|
||||
- Active development happens on the `v8` branch.
|
||||
- Commit style: `fix: <description>` / `feat: <description>` / `docs: <description>`
|
||||
- Before opening a PR, run `uv run pytest tests/ -q` and confirm it passes.
|
||||
- Add a fixture file to `tests/fixtures/` and tests to `tests/test_languages.py` for any new language extractor.
|
||||
|
||||
### What to contribute
|
||||
|
||||
**Worked examples** are the most useful contribution. Run `/graphify` on a real corpus, save the output to `worked/{slug}/`, write an honest `review.md` covering what the graph got right and wrong, and open a PR.
|
||||
|
||||
**Extraction bugs** — open an issue with the input file, the cache entry (`graphify-out/cache/`), and what was missed or wrong.
|
||||
|
||||
See [ARCHITECTURE.md](ARCHITECTURE.md) for module responsibilities and how to add a language.
|
||||
|
||||
</details>
|
||||
+11
-10
@@ -4,8 +4,8 @@
|
||||
|
||||
| Version | Supported |
|
||||
|---------|-----------|
|
||||
| 0.1.x | Yes |
|
||||
| < 0.1 | No |
|
||||
| 0.3.x | Yes |
|
||||
| < 0.3 | No |
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
@@ -22,27 +22,28 @@ We will acknowledge receipt within 48 hours and aim to release a fix within 7 da
|
||||
|
||||
## Security Model
|
||||
|
||||
graphify is a **local development tool**. It runs as a Claude Code skill and optionally as a local MCP stdio server. It makes no network calls during graph analysis — only during `ingest` (explicit URL fetch by the user).
|
||||
graphify is a **local development tool**. It runs as a Claude Code skill and optionally as a local MCP stdio server. It makes no network calls during graph analysis - only during `ingest` (explicit URL fetch by the user).
|
||||
|
||||
### Threat Surface
|
||||
|
||||
| Vector | Mitigation |
|
||||
|--------|-----------|
|
||||
| SSRF via URL fetch | `security.validate_url()` allows only `http` and `https` schemes. Redirect targets are re-validated by `_NoFileRedirectHandler` — a redirect to `file://` is blocked. |
|
||||
| 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()`. |
|
||||
| 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/`. Also requires the `.graphify/` directory to exist. |
|
||||
| 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. |
|
||||
| XSS in graph HTML output | `security.sanitize_label()` strips control characters, caps at 256 chars, and HTML-escapes all node labels and edge titles before pyvis embeds them. |
|
||||
| Prompt injection via node labels | `sanitize_label()` also applied to MCP text output — node labels from user-controlled source files cannot break the text format returned to agents. |
|
||||
| YAML frontmatter injection | Newlines stripped from user-provided strings before embedding in YAML frontmatter (e.g. in `save_query_result()`). |
|
||||
| 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. |
|
||||
| Prompt injection via node labels | `sanitize_label()` also applied to MCP text output - node labels from user-controlled source files cannot break the text format returned to agents. |
|
||||
| Prompt injection via source file content | During the semantic pass, source files are attacker-controlled text mixed into the LLM context. `_read_files()` in `llm.py` wraps every file in a hash-stamped `<untrusted_source path=... sha256=...>` delimiter block, the extraction system prompt instructs the model to treat that block as inert data and never as instructions, and `_neutralise_injection_sentinels()` defangs known chat-template/jailbreak tokens (`<\|im_start\|>`, `[INST]`, `<<SYS>>`, forged `</untrusted_source>`, etc.) before insertion. This is the table-stakes defense (issue #1210): it does not make injection impossible, but changes it from "works on first try" to "requires evasion." |
|
||||
| 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 explicit throughout `detect.py`. |
|
||||
| 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
|
||||
|
||||
- Does not run a network listener (MCP server communicates over stdio only)
|
||||
- Does not execute code from source files (tree-sitter parses ASTs — no eval/exec)
|
||||
- Does not execute code from source files (tree-sitter parses ASTs - no eval/exec)
|
||||
- Does not use `shell=True` in any subprocess call
|
||||
- Does not store credentials or API keys
|
||||
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
# Docker MCP Toolkit + SQLite MCP server
|
||||
|
||||
A reproducible runbook for installing the **SQLite MCP server** into the
|
||||
[Docker MCP Toolkit](https://docs.docker.com/desktop/features/mcp/) so any
|
||||
connected MCP client (Claude Code, Claude Desktop, Cursor, VS Code, etc.) gains
|
||||
six SQLite tools: `read_query`, `write_query`, `create_table`, `list_tables`,
|
||||
`describe_table`, and `append_insight`.
|
||||
|
||||
This document is *not* required to use graphify — it lives here as a known-good
|
||||
recipe for users who want a lightweight, persistent SQL workspace exposed to
|
||||
their AI clients alongside graphify's knowledge-graph tools.
|
||||
|
||||
## Why SQLite (and not `sqlite-mcp-server`)
|
||||
At time of writing the catalog ships two SQLite MCP images:
|
||||
|
||||
| Catalog name | Image | Status |
|
||||
| ------------------- | ---------------------- | ------ |
|
||||
| `SQLite` | `mcp/sqlite` | Marked "Archived" in catalog metadata, but **boots and serves correctly** |
|
||||
| `sqlite-mcp-server` | `mcp/sqlite-mcp-server`| **Broken**: entrypoint `/app/.venv/bin/mcp-server-sqlite` does not exist in the published layer |
|
||||
|
||||
Use `SQLite` (`mcp/sqlite`) until the newer image is fixed upstream.
|
||||
|
||||
## Prerequisites
|
||||
- Docker Desktop running and healthy
|
||||
- `docker info` returns a `Server Version`
|
||||
- Public socket present at `/var/run/docker.sock` (or its symlink to
|
||||
`~/.docker/run/docker.sock`)
|
||||
- Docker MCP Toolkit CLI plugin (`docker mcp`)
|
||||
- Bundled with recent Docker Desktop releases; `docker mcp --version` should
|
||||
print a version string
|
||||
|
||||
## Install
|
||||
```bash
|
||||
# Add the working SQLite server to the default MCP profile
|
||||
docker mcp profile server add default \
|
||||
--server catalog://mcp/docker-mcp-catalog/SQLite
|
||||
|
||||
# Pre-pull the image so the first tool call is fast
|
||||
docker pull mcp/sqlite:latest
|
||||
```
|
||||
|
||||
Verify the profile now contains both `fetch` (built-in) and `SQLite`:
|
||||
```bash
|
||||
docker mcp profile show default | grep -E '^[[:space:]]+name:'
|
||||
```
|
||||
|
||||
Expected output:
|
||||
```
|
||||
name: fetch
|
||||
name: SQLite
|
||||
```
|
||||
|
||||
The Docker MCP gateway should now expose 6 additional tools:
|
||||
```bash
|
||||
docker mcp tools count
|
||||
# → 15 tools (was 9 before adding SQLite)
|
||||
```
|
||||
|
||||
## Smoke test
|
||||
The CLI can call MCP tools directly (each call boots a fresh gateway, ~5s
|
||||
overhead per call):
|
||||
```bash
|
||||
docker mcp tools call list_tables
|
||||
docker mcp tools call create_table \
|
||||
query='CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY AUTOINCREMENT, body TEXT NOT NULL, created_at TEXT DEFAULT CURRENT_TIMESTAMP)'
|
||||
docker mcp tools call write_query \
|
||||
query="INSERT INTO notes(body) VALUES ('first row'), ('second row')"
|
||||
docker mcp tools call read_query \
|
||||
query='SELECT * FROM notes ORDER BY id'
|
||||
docker mcp tools call describe_table table_name=notes
|
||||
docker mcp tools call append_insight insight='3 rows inserted; aggregates work.'
|
||||
```
|
||||
|
||||
`read_query` should return the inserted rows with timestamps.
|
||||
|
||||
## Storage layout
|
||||
Database file lives in a Docker named volume `mcp-sqlite`, mounted at `/mcp`
|
||||
inside containers:
|
||||
```
|
||||
mcp-sqlite (named volume) → /mcp/db.sqlite
|
||||
```
|
||||
|
||||
Inspect from the host:
|
||||
```bash
|
||||
docker volume inspect mcp-sqlite
|
||||
docker run --rm -v mcp-sqlite:/mcp:ro alpine ls -la /mcp
|
||||
docker run --rm -v mcp-sqlite:/mcp:ro keinos/sqlite3 \
|
||||
sqlite3 /mcp/db.sqlite '.schema'
|
||||
```
|
||||
|
||||
The volume persists across `docker run --rm` invocations of the SQLite MCP
|
||||
container, so writes from one MCP tool call are visible to the next.
|
||||
|
||||
## Wiring into MCP clients
|
||||
Connect once per client; the gateway exposes every server in the active profile:
|
||||
```bash
|
||||
docker mcp client connect claude-code # already connected for many users
|
||||
docker mcp client connect cursor
|
||||
docker mcp client connect vscode
|
||||
docker mcp client connect claude-desktop
|
||||
# Supported: claude-code, claude-desktop, cline, codex, continue, crush,
|
||||
# cursor, gemini, goose, gordon, kiro, lmstudio, opencode, sema4,
|
||||
# vscode, zed
|
||||
```
|
||||
|
||||
Verify wiring:
|
||||
```bash
|
||||
docker mcp client ls
|
||||
```
|
||||
|
||||
## Uninstall / reset
|
||||
```bash
|
||||
# Remove server from the profile
|
||||
docker mcp profile server remove default SQLite
|
||||
|
||||
# Drop the database volume (irreversible)
|
||||
docker volume rm mcp-sqlite
|
||||
|
||||
# Remove the image
|
||||
docker rmi mcp/sqlite:latest
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
- **`starting client: calling "initialize": EOF`** — the requested server
|
||||
failed its MCP handshake. Run the image directly to see the error:
|
||||
```bash
|
||||
printf '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"smoke","version":"0.0"}}}\n' \
|
||||
| docker run --rm -i -v mcp-sqlite:/mcp <image-ref> --db-path /mcp/db.sqlite
|
||||
```
|
||||
Common causes: missing entrypoint binary in the image (the
|
||||
`sqlite-mcp-server` failure mode) or missing required env/secrets.
|
||||
- **`cannot use --enable-all-servers with --servers flag`** — these gateway
|
||||
args are mutually exclusive; pick one.
|
||||
- **No new tools appear in `docker mcp tools count` after install** — the
|
||||
gateway may be running with `dynamic-tools` enabled, exposing only meta-tools
|
||||
(`mcp-add`, `mcp-find`, …) until a profile is activated mid-session. Either
|
||||
invoke `docker mcp tools` (which spins up an ephemeral gateway against the
|
||||
default profile) or call `mcp-activate-profile` from inside an MCP session.
|
||||
@@ -0,0 +1,101 @@
|
||||
# How graphify works
|
||||
|
||||
## The three passes
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
Before Pass 3, optional converters turn supported pointer/binary formats into
|
||||
Markdown sidecars under `graphify-out/converted/`. Office files (`.docx`,
|
||||
`.xlsx`) use the `[office]` extra. Google Workspace shortcuts (`.gdoc`,
|
||||
`.gsheet`, `.gslides`) are opt-in with `--google-workspace` or
|
||||
`GRAPHIFY_GOOGLE_WORKSPACE=1` and require an authenticated `gws` CLI.
|
||||
|
||||
---
|
||||
|
||||
## How community detection works
|
||||
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
## Confidence tagging
|
||||
|
||||
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) |
|
||||
| `AMBIGUOUS` | Uncertain — flagged in the report for manual review |
|
||||
|
||||
EXTRACTED edges always have confidence 1.0. INFERRED edges use a discrete rubric:
|
||||
- **0.95** — near-certain (explicit cross-file reference, one plausible target)
|
||||
- **0.85** — strong evidence (naming + context align)
|
||||
- **0.75** — reasonable (contextual but not explicit)
|
||||
- **0.65** — weak (naming similarity only)
|
||||
- **0.55** — speculative
|
||||
|
||||
---
|
||||
|
||||
## Token benchmark
|
||||
|
||||
The first run extracts and builds the graph — this costs tokens. Every subsequent query reads the compact graph instead of raw files. That's where the savings compound.
|
||||
|
||||
On a mixed corpus (Karpathy repos + 5 papers + 4 images, 52 files): **71.5x fewer tokens per query** vs reading the raw files directly.
|
||||
|
||||
| Corpus | Files | Reduction |
|
||||
|--------|-------|-----------|
|
||||
| Karpathy repos + papers + images | 52 | **71.5x** |
|
||||
| graphify source + Transformer paper | 4 | **5.4x** |
|
||||
| httpx (synthetic Python library) | 6 | ~1x |
|
||||
|
||||
Token reduction scales with corpus size. Six files already fits in a context window — the graph value there is structural clarity, not compression. At 52 files the savings compound quickly.
|
||||
|
||||
Each `worked/` folder in the repo has the raw input files and actual output (`GRAPH_REPORT.md`, `graph.json`) so you can run it yourself and verify.
|
||||
|
||||
---
|
||||
|
||||
## 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.
|
||||
|
||||
---
|
||||
|
||||
## SHA256 cache
|
||||
|
||||
Every extracted file is fingerprinted by content hash. Re-runs skip unchanged files entirely — only new or modified files go through extraction again. The cache lives in `graphify-out/cache/`.
|
||||
|
||||
---
|
||||
|
||||
## The graph format
|
||||
|
||||
The output `graph.json` uses NetworkX's node-link format. Each node has:
|
||||
- `id` — stable identifier
|
||||
- `label` — human-readable name
|
||||
- `file_type` — `code`, `document`, `paper`, `image`, `rationale`
|
||||
- `source_file` — where it came from
|
||||
|
||||
See [RFC: file-level node summaries](node-summaries-rfc.md) for two proposed
|
||||
ways to add compact optional summaries for AI navigation.
|
||||
|
||||
Each edge has:
|
||||
- `source`, `target` — node IDs
|
||||
- `relation` — verb phrase (e.g. `calls`, `imports`, `implements`, `semantically_similar_to`)
|
||||
- `confidence` — `EXTRACTED`, `INFERRED`, or `AMBIGUOUS`
|
||||
- `confidence_score` — float (INFERRED only)
|
||||
- `source_file` — where the relationship was found
|
||||
|
||||
Hyperedges (group relationships connecting 3+ nodes) live in `G.graph["hyperedges"]`.
|
||||
@@ -0,0 +1,47 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" role="img" aria-label="Graphify">
|
||||
<defs>
|
||||
<style>
|
||||
.edge { stroke: #22c55e; stroke-width: 1.1; stroke-linecap: round; opacity: 0.55; fill: none; }
|
||||
.edge-hot { stroke: #4ade80; stroke-width: 1.2; stroke-linecap: round; opacity: 0.9; fill: none; }
|
||||
.node { fill: #040806; stroke: #22c55e; stroke-width: 1.3; }
|
||||
.node-hub { fill: #0a1410; stroke: #4ade80; stroke-width: 1.6; }
|
||||
.node-amber { fill: #040806; stroke: #f59e0b; stroke-width: 1.3; }
|
||||
.node-amber-core { fill: #f59e0b; }
|
||||
.node-core { fill: #22c55e; }
|
||||
.node-hub-core { fill: #4ade80; }
|
||||
</style>
|
||||
</defs>
|
||||
|
||||
<!-- subtle halo around hub -->
|
||||
<circle cx="24" cy="24" r="11" fill="none" stroke="#22c55e" stroke-width="0.4" opacity="0.18"/>
|
||||
|
||||
<!-- edges: hub to satellites -->
|
||||
<line class="edge-hot" x1="24" y1="24" x2="10" y2="11"/>
|
||||
<line class="edge-hot" x1="24" y1="24" x2="39" y2="14"/>
|
||||
<line class="edge-hot" x1="24" y1="24" x2="38" y2="36"/>
|
||||
<line class="edge-hot" x1="24" y1="24" x2="11" y2="37"/>
|
||||
|
||||
<!-- perimeter edges -->
|
||||
<line class="edge" x1="10" y1="11" x2="39" y2="14"/>
|
||||
<line class="edge" x1="39" y1="14" x2="38" y2="36"/>
|
||||
<line class="edge" x1="38" y1="36" x2="11" y2="37"/>
|
||||
<line class="edge" x1="11" y1="37" x2="10" y2="11"/>
|
||||
|
||||
<!-- satellite nodes -->
|
||||
<circle class="node" cx="10" cy="11" r="2.6"/>
|
||||
<circle class="node-core" cx="10" cy="11" r="1.1"/>
|
||||
|
||||
<circle class="node" cx="39" cy="14" r="2.6"/>
|
||||
<circle class="node-core" cx="39" cy="14" r="1.1"/>
|
||||
|
||||
<!-- amber accent node -->
|
||||
<circle class="node-amber" cx="38" cy="36" r="2.8"/>
|
||||
<circle class="node-amber-core" cx="38" cy="36" r="1.25"/>
|
||||
|
||||
<circle class="node" cx="11" cy="37" r="2.6"/>
|
||||
<circle class="node-core" cx="11" cy="37" r="1.1"/>
|
||||
|
||||
<!-- central hub / god-node -->
|
||||
<circle class="node-hub" cx="24" cy="24" r="4.4"/>
|
||||
<circle class="node-hub-core" cx="24" cy="24" r="1.8"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.0 KiB |
@@ -0,0 +1,33 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 260 64" role="img" aria-label="Graphify">
|
||||
<rect width="260" height="64" rx="8" fill="#040806"/>
|
||||
<defs>
|
||||
<style>
|
||||
.logo-text { font-family: 'Segoe UI', 'Helvetica Neue', Arial, sans-serif; font-size: 42px; font-weight: 700; letter-spacing: -1.6px; }
|
||||
</style>
|
||||
</defs>
|
||||
<!-- icon mark -->
|
||||
<circle cx="24" cy="32" r="11" fill="none" stroke="#22c55e" stroke-width="0.4" opacity="0.18"/>
|
||||
<line x1="24" y1="32" x2="10" y2="19" stroke="#4ade80" stroke-width="1.2" stroke-linecap="round" opacity="0.9"/>
|
||||
<line x1="24" y1="32" x2="39" y2="22" stroke="#4ade80" stroke-width="1.2" stroke-linecap="round" opacity="0.9"/>
|
||||
<line x1="24" y1="32" x2="38" y2="44" stroke="#4ade80" stroke-width="1.2" stroke-linecap="round" opacity="0.9"/>
|
||||
<line x1="24" y1="32" x2="11" y2="45" stroke="#4ade80" stroke-width="1.2" stroke-linecap="round" opacity="0.9"/>
|
||||
<line x1="10" y1="19" x2="39" y2="22" stroke="#22c55e" stroke-width="1.1" stroke-linecap="round" opacity="0.55"/>
|
||||
<line x1="39" y1="22" x2="38" y2="44" stroke="#22c55e" stroke-width="1.1" stroke-linecap="round" opacity="0.55"/>
|
||||
<line x1="38" y1="44" x2="11" y2="45" stroke="#22c55e" stroke-width="1.1" stroke-linecap="round" opacity="0.55"/>
|
||||
<line x1="11" y1="45" x2="10" y2="19" stroke="#22c55e" stroke-width="1.1" stroke-linecap="round" opacity="0.55"/>
|
||||
<circle cx="10" cy="19" r="2.6" fill="#040806" stroke="#22c55e" stroke-width="1.3"/>
|
||||
<circle cx="10" cy="19" r="1.1" fill="#22c55e"/>
|
||||
<circle cx="39" cy="22" r="2.6" fill="#040806" stroke="#22c55e" stroke-width="1.3"/>
|
||||
<circle cx="39" cy="22" r="1.1" fill="#22c55e"/>
|
||||
<circle cx="38" cy="44" r="2.8" fill="#040806" stroke="#f59e0b" stroke-width="1.3"/>
|
||||
<circle cx="38" cy="44" r="1.25" fill="#f59e0b"/>
|
||||
<circle cx="11" cy="45" r="2.6" fill="#040806" stroke="#22c55e" stroke-width="1.3"/>
|
||||
<circle cx="11" cy="45" r="1.1" fill="#22c55e"/>
|
||||
<circle cx="24" cy="32" r="4.4" fill="#0a1410" stroke="#4ade80" stroke-width="1.6"/>
|
||||
<circle cx="24" cy="32" r="1.8" fill="#4ade80"/>
|
||||
<!-- divider -->
|
||||
<line x1="56" y1="18" x2="56" y2="46" stroke="#22c55e" stroke-width="1" opacity="0.2"/>
|
||||
<!-- text: Graph in near-white, ify in green -->
|
||||
<text x="68" y="47" class="logo-text" fill="#e6f5ec">Graph</text>
|
||||
<text x="178" y="47" class="logo-text" fill="#22c55e">ify</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.3 KiB |
@@ -0,0 +1,186 @@
|
||||
# RFC: file-level node summaries
|
||||
|
||||
This RFC proposes an optional way for graphify to expose compact file-level
|
||||
summaries for AI coding agents.
|
||||
|
||||
## Problem
|
||||
|
||||
`graph.json` gives agents graph structure, source files, node labels, and
|
||||
relationships. That helps avoid reading an entire repository, but agents still
|
||||
often need to inspect raw files just to answer a basic navigation question:
|
||||
|
||||
> What is this file or node responsible for?
|
||||
|
||||
A short summary near the graph node could reduce repeated file reads during
|
||||
`graphify query`, `graphify explain`, MCP node lookup, and graph navigation.
|
||||
|
||||
## Goals
|
||||
|
||||
- Help agents choose relevant files with less context.
|
||||
- Preserve graphify's offline, deterministic behavior by default.
|
||||
- Keep the first implementation small and reviewable.
|
||||
- Avoid adding long prose to `GRAPH_REPORT.md`.
|
||||
- Leave room for a future opt-in LLM-generated summary backend.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Summarizing every function, method, or local symbol in the first version.
|
||||
- Calling an LLM or remote API by default.
|
||||
- Replacing `graphify explain`; summaries should make `explain` more useful.
|
||||
- Turning `GRAPH_REPORT.md` into a full per-file index.
|
||||
|
||||
## Shared constraints for either option
|
||||
|
||||
- Start with file-level nodes only.
|
||||
- Keep each summary bounded, for example one sentence or roughly 200-300
|
||||
characters.
|
||||
- Generate deterministic summaries first from existing local signal:
|
||||
module docstrings, top comments, exported symbols, imports, relation counts,
|
||||
and community/context data.
|
||||
- Do not emit summaries by default until the storage model is agreed on.
|
||||
- Display a summary in `graphify explain <node>` when one exists.
|
||||
- Include summaries in `graphify serve` / MCP node lookup when one exists.
|
||||
|
||||
## Proposed summary contents
|
||||
|
||||
Each file-level summary should give an agent enough signal to decide whether to
|
||||
inspect the file, without replacing the file or bloating graph output.
|
||||
|
||||
Recommended fields:
|
||||
|
||||
| Field | Why it helps agents |
|
||||
| --- | --- |
|
||||
| `summary` | One bounded sentence describing the file's responsibility. This is the main token-saving field. |
|
||||
| `source_file` | Lets the agent jump to the right file without resolving a node ID manually. |
|
||||
| `label` | Keeps the summary readable in CLI, MCP, and UI contexts. |
|
||||
| `generated_by` | Distinguishes deterministic summaries from future LLM-generated summaries. |
|
||||
| `summary_version` | Allows the format to evolve without guessing how an older summary was produced. |
|
||||
|
||||
Recommended signal inside the `summary` sentence:
|
||||
|
||||
| Signal | Why it belongs in the sentence |
|
||||
| --- | --- |
|
||||
| Module docstring or top comment | Usually the highest-quality human-authored purpose statement. |
|
||||
| Exported classes/functions/symbols | Tells the agent what API surface the file provides. |
|
||||
| Important imports or dependencies | Reveals whether the file belongs to auth, database, UI, CLI, test, etc. |
|
||||
| Dominant graph relations | Shows whether the file mainly calls, imports, defines, contains, or references other nodes. |
|
||||
| Community or nearby hub label | Gives architectural context without reading the whole community report. |
|
||||
| Source location coverage when available | Helps distinguish a file-level summary from a symbol-level explanation. |
|
||||
|
||||
Example:
|
||||
|
||||
```json
|
||||
{
|
||||
"label": "extract.py",
|
||||
"source_file": "graphify/extract.py",
|
||||
"summary": "Extracts source files into graph nodes and relationships; defines language parsers and import/call extraction helpers.",
|
||||
"generated_by": "deterministic",
|
||||
"summary_version": 1
|
||||
}
|
||||
```
|
||||
|
||||
The summary should not include long call chains, full dependency lists, raw code,
|
||||
or every symbol in the file. Those details already belong in the graph and can
|
||||
be fetched through `graphify explain`, `graphify query`, or direct file reads
|
||||
when needed.
|
||||
|
||||
## Option A: `summary` attribute in `graph.json`
|
||||
|
||||
Add an optional `summary` field to file-level nodes:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "graphify_extract",
|
||||
"label": "extract.py",
|
||||
"file_type": "code",
|
||||
"source_file": "graphify/extract.py",
|
||||
"summary": "Extracts source files into graph nodes and relationships using language-specific parsers."
|
||||
}
|
||||
```
|
||||
|
||||
Possible user flow:
|
||||
|
||||
```bash
|
||||
graphify . --summarize-nodes
|
||||
graphify explain "extract.py"
|
||||
```
|
||||
|
||||
Pros:
|
||||
|
||||
- Single artifact for graph consumers.
|
||||
- Matches NetworkX node attributes and existing node metadata.
|
||||
- Easy for `explain`, `serve`, visualizers, and MCP tools to consume.
|
||||
- No sidecar freshness or node-ID join logic.
|
||||
|
||||
Cons:
|
||||
|
||||
- Adds text to the core graph artifact.
|
||||
- Expands the graph schema surface.
|
||||
- Consumers that dump all of `graph.json` into an LLM context would pay for all
|
||||
summaries at once.
|
||||
|
||||
## Option B: sidecar `node-summaries.json`
|
||||
|
||||
Write summaries to a separate artifact keyed by node ID:
|
||||
|
||||
```json
|
||||
{
|
||||
"version": 1,
|
||||
"generator": "deterministic",
|
||||
"nodes": {
|
||||
"graphify_extract": {
|
||||
"label": "extract.py",
|
||||
"source_file": "graphify/extract.py",
|
||||
"summary": "Extracts source files into graph nodes and relationships using language-specific parsers."
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Possible user flow:
|
||||
|
||||
```bash
|
||||
graphify summarize
|
||||
graphify explain "extract.py"
|
||||
```
|
||||
|
||||
Pros:
|
||||
|
||||
- Keeps `graph.json` lean and topology-focused.
|
||||
- Makes summaries clearly optional.
|
||||
- Can be regenerated independently.
|
||||
- Provides a natural place for future generator metadata.
|
||||
|
||||
Cons:
|
||||
|
||||
- Adds a second artifact that consumers must discover and load.
|
||||
- Introduces freshness and synchronization questions.
|
||||
- Every consumer that wants summaries must join by node ID.
|
||||
|
||||
## Suggested first implementation once storage is chosen
|
||||
|
||||
1. Add deterministic file-level summary generation.
|
||||
2. Store summaries using the selected option.
|
||||
3. Surface summaries in `graphify explain`.
|
||||
4. Surface summaries in `graphify serve` / MCP node lookup.
|
||||
5. Add tests for default behavior, generated summaries, missing summaries, and
|
||||
bounded summary length.
|
||||
|
||||
## Follow-up ideas
|
||||
|
||||
- Add opt-in LLM-generated summaries with explicit provider/backend selection.
|
||||
- Extend summaries to class or module-level nodes if file-level summaries prove
|
||||
useful.
|
||||
- Allow `graphify query` to include summaries for returned nodes under a budget.
|
||||
- Add cache/freshness metadata if summaries are generated separately from the
|
||||
main graph.
|
||||
|
||||
## Questions for maintainers and users
|
||||
|
||||
1. Should graphify prefer one artifact (`graph.json`) or keep generated text in a
|
||||
sidecar?
|
||||
2. Should deterministic file-level summaries be generated during graph creation,
|
||||
or only through an explicit command such as `graphify summarize`?
|
||||
3. Is `summary` the right term, or would `synopsis` better communicate a short,
|
||||
bounded description?
|
||||
4. What summary length budget would be acceptable for large repositories?
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,133 @@
|
||||
# Design: Incremental Updates + Entity Deduplication
|
||||
|
||||
**Date:** 2026-05-04
|
||||
**Issues:** #698 (incremental updates), entity deduplication (no issue, proactive)
|
||||
**Branch:** v7
|
||||
|
||||
---
|
||||
|
||||
## Problem
|
||||
|
||||
1. `graphify extract` rebuilds the full graph from scratch every run — re-sends all files to the LLM regardless of what changed. For a 1000-file Markdown corpus updated daily this is expensive.
|
||||
|
||||
2. LLM extraction is chunk-by-chunk — the same real-world concept can get different labels across chunks (`AuthManager`, `AuthenticationManager`, `auth_mgr`). No semantic dedup exists beyond exact string normalization.
|
||||
|
||||
---
|
||||
|
||||
## Pipeline (every `graphify extract` run)
|
||||
|
||||
```
|
||||
detect (full or incremental, auto-detected)
|
||||
↓
|
||||
AST extract (code files, AST cache-aware)
|
||||
↓
|
||||
Semantic LLM extract (doc/paper/image files, semantic cache-aware)
|
||||
↓
|
||||
build_merge (merge into existing graph, prune deleted nodes)
|
||||
↓
|
||||
deduplicate_entities (normalize → entropy gate → MinHash/LSH → Jaro-Winkler → community boost → optional LLM)
|
||||
↓
|
||||
cluster (full graph, always re-run)
|
||||
↓
|
||||
score_all + god_nodes + surprising_connections
|
||||
↓
|
||||
write graph.json + .graphify_analysis.json + manifest.json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Feature 1: Incremental Updates
|
||||
|
||||
### Auto-detection
|
||||
If `graphify-out/manifest.json` + `graphify-out/graph.json` both exist → incremental mode. No flag needed. First run is always full.
|
||||
|
||||
### Incremental mode changes
|
||||
- `detect_incremental(target)` instead of `detect(target)` — returns `new_files`, `unchanged_files`, `deleted_files`
|
||||
- Only `new_files` go through AST + LLM extraction
|
||||
- `build_merge(new_chunks, prune_sources=deleted_files)` instead of `build_from_json` — merges into existing graph, prunes nodes from deleted files
|
||||
- `manifest.json` written only on successful completion (crash mid-run does not corrupt next run's diff)
|
||||
|
||||
### Semantic cache (both full and incremental mode)
|
||||
- Before LLM call: `check_semantic_cache(files)` splits into `(cached_results, uncached_files)`
|
||||
- Only `uncached_files` sent to `extract_corpus_parallel`
|
||||
- After LLM call: `save_semantic_cache(fresh_results)` — keyed by content hash
|
||||
- On file rename: `source_file` updated to new path in cached result (same pattern as existing AST cache)
|
||||
|
||||
### Output summary
|
||||
```
|
||||
[graphify extract] incremental: 20 changed, 980 cached, 2 deleted
|
||||
[graphify extract] graph: 4,821 nodes, 12,304 edges, 43 communities
|
||||
[graphify extract] tokens: 18,432 in / 6,201 out, est. cost: $0.08
|
||||
```
|
||||
|
||||
### Files changed
|
||||
- `graphify/__main__.py` — `elif cmd == "extract":` block only (~5 targeted changes)
|
||||
|
||||
---
|
||||
|
||||
## Feature 2: Entity Deduplication
|
||||
|
||||
### New module: `graphify/dedup.py`
|
||||
Single responsibility. Called from `build.py` after graph construction. Returns deduplicated `(nodes, edges)`.
|
||||
|
||||
### Pipeline
|
||||
|
||||
**Step 1 — Exact normalization**
|
||||
Wire up the dormant `deduplicate_by_label` in `build.py`. Catches case/punctuation variants across files. Free win, already written.
|
||||
|
||||
**Step 2 — Entropy gate**
|
||||
Skip fuzzy matching on labels with < 2.5 bits/char entropy. Short ambiguous names (`"AI"`, `"DB"`, `"x"`) are too risky to auto-merge. Only high-entropy labels proceed to steps 3-4.
|
||||
|
||||
**Step 3 — MinHash + LSH blocking** (`datasketch`)
|
||||
3-gram shingles, 128 permutations, threshold 0.7. Generates candidate pairs in O(n) instead of O(n²). Sub-second at 10k nodes.
|
||||
|
||||
**Step 4 — Jaro-Winkler verification** (`rapidfuzz`)
|
||||
Each candidate pair verified at ≥ 0.92. Catches typos, plurals, spacing variants. Pairs below threshold discarded.
|
||||
|
||||
**Step 5 — Same-community boost**
|
||||
Pairs where both nodes share a Leiden community ID get +0.05 score bonus. Graphify-specific advantage — community structure is a strong signal that GraphRAG/LightRAG don't exploit.
|
||||
|
||||
**Step 6 — Union-find merge**
|
||||
Confirmed pairs fed into union-find → connected components → each component merged into one node. Edges rewired to survivor. Self-loops dropped. Prefer shorter non-chunk-suffixed IDs as survivor.
|
||||
|
||||
**Step 7 — Optional LLM tiebreaker** (`--dedup-llm` flag)
|
||||
Ambiguous pairs (score 0.75–0.85) batched in groups of 30, one LLM call per batch. ~$0.01 total for 10k nodes. Off by default.
|
||||
|
||||
### Integration point
|
||||
Dedup runs after `build_merge` / `build_from_json`, before `cluster`. Order matters: cleaner graph → better community detection.
|
||||
|
||||
```python
|
||||
# in build.py
|
||||
G = build_merge(...) # or build_from_json
|
||||
G = deduplicate_entities(G) # new step
|
||||
communities = cluster(G) # unchanged
|
||||
```
|
||||
|
||||
### New dependencies
|
||||
- `datasketch` — always required (added to `[project.dependencies]`)
|
||||
- `rapidfuzz` — always required (added to `[project.dependencies]`)
|
||||
- No `sentence-transformers` / PyTorch dependency
|
||||
|
||||
### Files changed
|
||||
- `graphify/dedup.py` — new module, full pipeline
|
||||
- `graphify/build.py` — call `deduplicate_entities` after graph construction; wire dormant `deduplicate_by_label`
|
||||
- `graphify/__main__.py` — add `--dedup-llm` flag parsing in extract block
|
||||
- `pyproject.toml` — add `datasketch`, `rapidfuzz` to base dependencies
|
||||
|
||||
---
|
||||
|
||||
## Testing
|
||||
|
||||
- Unit tests for each dedup step in isolation (`tests/test_dedup.py`)
|
||||
- Integration test: two chunks with overlapping entity labels → single merged node in output graph
|
||||
- Incremental test: run extract twice, assert second run makes zero LLM calls for unchanged files
|
||||
- Rename test: rename a file, assert cache hit and `source_file` updated correctly
|
||||
- Delete test: delete a file, assert its nodes are pruned from graph
|
||||
|
||||
---
|
||||
|
||||
## Non-goals
|
||||
|
||||
- `--dedup embed` (MiniLM cosine) — explicitly excluded, no PyTorch dependency
|
||||
- Incremental support for `graphify update` (AST-only) — already handled by existing AST cache
|
||||
- Dedup across different graph.json files (merge two graphs) — separate feature
|
||||
@@ -0,0 +1,177 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></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>
|
||||
</p>
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
**مهارة لمساعد برمجة الذكاء الاصطناعي.** اكتب `/graphify` في Claude Code أو Codex أو OpenCode أو Cursor أو Gemini CLI أو GitHub Copilot CLI أو VS Code Copilot Chat أو Aider أو OpenClaw أو Factory Droid أو Trae أو Hermes أو Kiro أو Google Antigravity — يقرأ ملفاتك ويبني رسماً بيانياً للمعرفة ويعيد إليك البنية التي لم تكن تعلم بوجودها. افهم قاعدة الكود بشكل أسرع. اكتشف "السبب" وراء القرارات المعمارية.
|
||||
|
||||
متعدد الوسائط بالكامل. أضف كوداً أو ملفات PDF أو markdown أو لقطات شاشة أو رسوماً بيانية أو صور سبورة أو صوراً بلغات أخرى أو ملفات فيديو وصوت — يستخرج graphify المفاهيم والعلاقات من كل ذلك ويربطها في رسم بياني واحد. يتم نسخ مقاطع الفيديو محلياً باستخدام Whisper. يدعم 25 لغة برمجة عبر tree-sitter AST (Python, JS, TS, Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Lua, Zig, PowerShell, Elixir, Objective-C, Julia, Verilog, SystemVerilog, Vue, Svelte, Dart).
|
||||
|
||||
> يحتفظ Andrej Karpathy بمجلد `/raw` يضع فيه الأوراق البحثية والتغريدات ولقطات الشاشة والملاحظات. graphify هو الإجابة على تلك المشكلة — **71.5 مرة** أقل في الرموز لكل استعلام مقارنةً بقراءة الملفات الخام، مستمر عبر الجلسات، صادق حول ما تم العثور عليه مقابل ما تم استنتاجه.
|
||||
|
||||
</div>
|
||||
|
||||
```
|
||||
/graphify . # يعمل مع أي مجلد — الكود، الملاحظات، الأوراق البحثية، كل شيء
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html رسم بياني تفاعلي — افتحه في أي متصفح، انقر على العقد، ابحث، صفّ
|
||||
├── GRAPH_REPORT.md عقد الإله، الاتصالات المفاجئة، الأسئلة المقترحة
|
||||
├── graph.json رسم بياني دائم — استعلم بعد أسابيع دون إعادة القراءة
|
||||
└── cache/ ذاكرة تخزين مؤقت SHA256 — إعادة التشغيل تعالج الملفات المتغيرة فقط
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
أضف ملف `.graphifyignore` لاستبعاد المجلدات:
|
||||
|
||||
</div>
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
vendor/
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
نفس صيغة `.gitignore`.
|
||||
|
||||
## كيف يعمل
|
||||
|
||||
يعمل graphify في ثلاث مراحل. أولاً، تمريرة AST حتمية تستخرج البنية من ملفات الكود (الفئات، الدوال، الاستيرادات، رسوم بيانية الاستدعاء، docstrings، تعليقات المبرر) — دون الحاجة إلى LLM. ثانياً، يتم نسخ ملفات الفيديو والصوت محلياً باستخدام faster-whisper. ثالثاً، تعمل عوامل Claude الفرعية بالتوازي على المستندات والأوراق البحثية والصور والنصوص المكتوبة لاستخراج المفاهيم والعلاقات ومبررات التصميم. يتم دمج النتائج في رسم بياني NetworkX وتجميعها باستخدام Leiden وتصديرها كـ HTML تفاعلي وJSON قابل للاستعلام وتقرير تدقيق بلغة طبيعية.
|
||||
|
||||
**التجميع مبني على طوبولوجيا الرسم البياني — بدون embeddings.** يجد Leiden المجتمعات بواسطة كثافة الحواف. حواف التشابه الدلالي التي يستخرجها Claude (`semantically_similar_to`، مصنفة INFERRED) موجودة بالفعل في الرسم البياني. بنية الرسم البياني هي إشارة التشابه — لا حاجة لخطوة embedding منفصلة أو قاعدة بيانات متجهية.
|
||||
|
||||
كل علاقة مصنفة كـ `EXTRACTED` (وجدت مباشرة في المصدر) أو `INFERRED` (استنتاج معقول مع درجة ثقة) أو `AMBIGUOUS` (مُعلَّمة للمراجعة).
|
||||
|
||||
## التثبيت
|
||||
|
||||
**المتطلبات:** Python 3.10+ وواحد من: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com), [Gemini CLI](https://github.com/google-gemini/gemini-cli), [GitHub Copilot CLI](https://docs.github.com/en/copilot/how-tos/copilot-cli), [VS Code Copilot Chat](https://code.visualstudio.com/docs/copilot/overview), [Aider](https://aider.chat), [OpenClaw](https://openclaw.ai), [Factory Droid](https://factory.ai), [Trae](https://trae.ai), [Kiro](https://kiro.dev), Hermes, أو [Google Antigravity](https://antigravity.google)
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
# موصى به — يعمل على Mac وLinux دون إعداد PATH
|
||||
uv tool install graphifyy && graphify install
|
||||
# أو مع pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# أو pip العادي
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
> **الحزمة الرسمية:** اسم حزمة PyPI هو `graphifyy` (تثبيت بـ `pip install graphifyy`). الحزم الأخرى المسماة `graphify*` على PyPI ليست تابعة لهذا المشروع. المستودع الرسمي الوحيد هو [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
### دعم المنصات
|
||||
|
||||
| المنصة | أمر التثبيت |
|
||||
|--------|-------------|
|
||||
| Claude Code (Linux/Mac) | `graphify install` |
|
||||
| Claude Code (Windows) | `graphify install` (كشف تلقائي) أو `graphify install --platform windows` |
|
||||
| Codex | `graphify install --platform codex` |
|
||||
| OpenCode | `graphify install --platform opencode` |
|
||||
| GitHub Copilot CLI | `graphify install --platform copilot` |
|
||||
| VS Code Copilot Chat | `graphify vscode install` |
|
||||
| Aider | `graphify install --platform aider` |
|
||||
| OpenClaw | `graphify install --platform claw` |
|
||||
| Factory Droid | `graphify install --platform droid` |
|
||||
| Trae | `graphify install --platform trae` |
|
||||
| Gemini CLI | `graphify install --platform gemini` |
|
||||
| Hermes | `graphify install --platform hermes` |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
افتح مساعد الكود الذكاء الاصطناعي واكتب:
|
||||
|
||||
</div>
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
ملاحظة: يستخدم Codex `$` بدلاً من `/` للمهارات، لذا اكتب `$graphify .`.
|
||||
|
||||
## الاستخدام
|
||||
|
||||
</div>
|
||||
|
||||
```
|
||||
/graphify # المجلد الحالي
|
||||
/graphify ./raw # مجلد محدد
|
||||
/graphify ./raw --update # إعادة استخراج الملفات المتغيرة فقط
|
||||
/graphify ./raw --directed # رسم بياني موجّه
|
||||
/graphify ./raw --no-viz # تقرير + JSON فقط، بدون HTML
|
||||
/graphify ./raw --obsidian # إنشاء Obsidian vault
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # جلب ورقة بحثية
|
||||
/graphify add <video-url> # تحميل صوت، نسخ، إضافة
|
||||
/graphify query "ما الذي يربط Attention بالمحسِّن؟"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
graphify hook install # تثبيت Git hooks
|
||||
graphify update ./src # إعادة استخراج ملفات الكود، بدون LLM
|
||||
graphify watch ./src # تحديث تلقائي للرسم البياني
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
## ما ستحصل عليه
|
||||
|
||||
**عقد الإله** — المفاهيم ذات أعلى درجة (كل شيء يمر بها)
|
||||
|
||||
**الاتصالات المفاجئة** — مرتبة حسب الدرجة المركبة. حواف الكود-الورقة البحثية تحصل على تصنيف أعلى. كل نتيجة تتضمن سبباً بلغة طبيعية.
|
||||
|
||||
**الأسئلة المقترحة** — 4-5 أسئلة الرسم البياني في وضع فريد للإجابة عليها
|
||||
|
||||
**"السبب"** — يتم استخراج docstrings والتعليقات المضمنة (`# NOTE:`, `# IMPORTANT:`, `# HACK:`, `# WHY:`) ومبررات التصميم كعقد `rationale_for`.
|
||||
|
||||
**درجات الثقة** — كل حافة INFERRED لها `confidence_score` (0.0-1.0).
|
||||
|
||||
**معيار الرموز** — يُطبع تلقائياً بعد كل تشغيل. على مجموعة بيانات مختلطة: **71.5 مرة** أقل في الرموز لكل استعلام مقارنةً بالملفات الخام.
|
||||
|
||||
**المزامنة التلقائية** (`--watch`) — يحدّث الرسم البياني تلقائياً عند تغيير الكود.
|
||||
|
||||
**Git hooks** (`graphify hook install`) — يثبّت خطافات post-commit وpost-checkout.
|
||||
|
||||
## الخصوصية
|
||||
|
||||
يرسل graphify محتوى الملفات إلى API نموذج مساعد الذكاء الاصطناعي الخاص بك للاستخراج الدلالي من المستندات والأوراق البحثية والصور. تتم معالجة ملفات الكود محلياً عبر tree-sitter AST. يتم نسخ ملفات الفيديو والصوت محلياً باستخدام faster-whisper. لا قياس عن بُعد، لا تتبع للاستخدام.
|
||||
|
||||
## المكدس التقني
|
||||
|
||||
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. استخراج دلالي عبر Claude أو GPT-4 أو نموذج منصتك. نسخ الفيديو عبر faster-whisper + yt-dlp (اختياري).
|
||||
|
||||
## مبني على graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) هو الطبقة المؤسسية فوق graphify. حيث يحوّل graphify مجلداً من الملفات إلى رسم بياني للمعرفة، يطبّق Penpax نفس الرسم البياني على حياتك المهنية بأكملها — باستمرار.
|
||||
|
||||
**نسخة تجريبية مجانية قريباً.** [انضم إلى قائمة الانتظار →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
## سجل النجوم
|
||||
|
||||
</div>
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**Dovednost pro asistenty kódování AI.** Napište `/graphify` v Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro nebo Google Antigravity — přečte vaše soubory, vytvoří znalostní graf a vrátí vám strukturu, o které jste nevěděli, že existuje. Pochopte kódovou základnu rychleji. Najděte „proč" za architektonickými rozhodnutími.
|
||||
|
||||
Plně multimodální. Přidejte kód, PDF, markdown, snímky obrazovky, diagramy, fotografie tabule, obrázky v jiných jazycích nebo video a zvukové soubory — graphify extrahuje koncepty a vztahy ze všeho a spojuje je do jediného grafu. Videa jsou přepisována lokálně pomocí Whisper. Podporuje 25 programovacích jazyků prostřednictvím tree-sitter AST.
|
||||
|
||||
> Andrej Karpathy udržuje složku `/raw`, kde ukládá články, tweety, snímky obrazovky a poznámky. graphify je odpovědí na tento problém — **71,5x** méně tokenů na dotaz ve srovnání se čtením surových souborů, přetrvávající mezi sezeními.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html interaktivní graf — otevřete v libovolném prohlížeči
|
||||
├── GRAPH_REPORT.md boží uzly, překvapivá propojení, navrhované otázky
|
||||
├── graph.json trvalý graf — dotazovatelný týdny poté
|
||||
└── cache/ SHA256 cache — opakovaná spuštění zpracovávají pouze změněné soubory
|
||||
```
|
||||
|
||||
## Jak to funguje
|
||||
|
||||
graphify pracuje ve třech průchodech. Nejprve deterministický průchod AST extrahuje strukturu z kódových souborů bez LLM. Poté jsou video a zvukové soubory přepisovány lokálně pomocí faster-whisper. Nakonec sub-agenti Claude běží paralelně na dokumentech, článcích, obrázcích a přepisech. Výsledky jsou sloučeny do grafu NetworkX, clusterovány pomocí Leiden a exportovány jako interaktivní HTML, dotazovatelný JSON a auditní zpráva.
|
||||
|
||||
Každý vztah je označen `EXTRACTED`, `INFERRED` (se skóre spolehlivosti) nebo `AMBIGUOUS`.
|
||||
|
||||
## Instalace
|
||||
|
||||
**Požadavky:** Python 3.10+ a jedno z: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) a další.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# nebo s pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# nebo pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Oficiální balíček:** Balíček PyPI se jmenuje `graphifyy`. Jediné oficiální úložiště je [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Použití
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "co spojuje Attention s optimizerem?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Co získáte
|
||||
|
||||
**Boží uzly** — koncepty s nejvyšším stupněm · **Překvapivá propojení** — seřazená podle skóre · **Navrhované otázky** · **„Proč"** — docstringy a návrhové odůvodnění extrahované jako uzly · **Benchmark tokenů** — **71,5x** méně tokenů na smíšeném korpusu.
|
||||
|
||||
## Soukromí
|
||||
|
||||
Kódové soubory jsou zpracovávány lokálně prostřednictvím tree-sitter AST. Videa jsou přepisována lokálně pomocí faster-whisper. Žádná telemetrie.
|
||||
|
||||
## Postaveno na graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) je enterprise vrstva nad graphify. **Bezplatná zkušební verze brzy.** [Přidejte se na čekací listinu →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**En færdighed til AI-kodeassistenter.** Skriv `/graphify` i Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro eller Google Antigravity — den læser dine filer, bygger en vidensgraf og giver dig den struktur tilbage, du ikke vidste eksisterede. Forstå en kodebase hurtigere. Find "hvorfor" bag arkitektoniske beslutninger.
|
||||
|
||||
Fuldt multimodal. Tilføj kode, PDF'er, markdown, skærmbilleder, diagrammer, whiteboardfotos, billeder på andre sprog eller video- og lydfiler — graphify udtrækker begreber og relationer fra alt og forbinder dem i én graf. Videoer transskriberes lokalt med Whisper. Understøtter 25 programmeringssprog via tree-sitter AST.
|
||||
|
||||
> Andrej Karpathy opretholder en `/raw`-mappe, hvor han lægger artikler, tweets, skærmbilleder og noter. graphify er svaret på det problem — **71,5x** færre tokens pr. forespørgsel sammenlignet med at læse rå filer, vedvarende mellem sessioner.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html interaktiv graf — åbn i enhver browser
|
||||
├── GRAPH_REPORT.md gudknuder, overraskende forbindelser, foreslåede spørgsmål
|
||||
├── graph.json vedvarende graf — forespørgselsbar uger senere
|
||||
└── cache/ SHA256-cache — gentagne kørsler behandler kun ændrede filer
|
||||
```
|
||||
|
||||
## Sådan fungerer det
|
||||
|
||||
graphify arbejder i tre gennemløb. Først udtrækker et deterministisk AST-gennemløb struktur fra kodefiler uden LLM. Derefter transskriberes video- og lydfiler lokalt med faster-whisper. Endelig kører Claude-underagenter parallelt på dokumenter, artikler, billeder og transskriptioner. Resultaterne flettes ind i en NetworkX-graf, klynges med Leiden og eksporteres som interaktiv HTML, forespørgselsbar JSON og revisionsrapport.
|
||||
|
||||
Hver relation er mærket `EXTRACTED`, `INFERRED` (med konfidensscore) eller `AMBIGUOUS`.
|
||||
|
||||
## Installation
|
||||
|
||||
**Krav:** Python 3.10+ og én af: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) og andre.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# eller med pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# eller pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Officiel pakke:** PyPI-pakken hedder `graphifyy`. Det eneste officielle lager er [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Brug
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "hvad forbinder Attention med optimizeren?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Hvad du får
|
||||
|
||||
**Gudknuder** — begreber med den højeste grad · **Overraskende forbindelser** — rangeret efter score · **Foreslåede spørgsmål** · **"Hvorfor"** — docstrings og designbegrundelse udtrukket som knuder · **Token-benchmark** — **71,5x** færre tokens på blandet korpus.
|
||||
|
||||
## Privatliv
|
||||
|
||||
Kodefiler behandles lokalt via tree-sitter AST. Videoer transskriberes lokalt med faster-whisper. Ingen telemetri.
|
||||
|
||||
## Bygget på graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) er enterprise-laget oven på graphify. **Gratis prøveperiode kommer snart.** [Tilmeld dig ventelisten →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,180 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></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>
|
||||
</p>
|
||||
|
||||
**Eine KI-Coding-Assistent-Skill.** Tippe `/graphify` in Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro oder Google Antigravity — es liest deine Dateien, baut einen Wissensgraphen und gibt dir Struktur zurück, die du vorher nicht sehen konntest. Verstehe eine Codebasis schneller. Finde das „Warum" hinter Architekturentscheidungen.
|
||||
|
||||
Vollständig multimodal. Leg Code, PDFs, Markdown, Screenshots, Diagramme, Whiteboard-Fotos, Bilder in anderen Sprachen oder Video- und Audiodateien ab — graphify extrahiert Konzepte und Beziehungen aus allem und verbindet sie in einem einzigen Graphen. Videos werden lokal mit Whisper transkribiert, angetrieben durch einen domänenspezifischen Prompt aus deinem Korpus. 25 Programmiersprachen werden über tree-sitter AST unterstützt (Python, JS, TS, Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Lua, Zig, PowerShell, Elixir, Objective-C, Julia, Verilog, SystemVerilog, Vue, Svelte, Dart).
|
||||
|
||||
> Andrej Karpathy führt einen `/raw`-Ordner, in dem er Papers, Tweets, Screenshots und Notizen ablegt. graphify ist die Antwort auf dieses Problem — 71,5-fach weniger Tokens pro Abfrage gegenüber dem Lesen der Rohdateien, persistent über Sitzungen hinweg, ehrlich darüber, was gefunden vs. erschlossen wurde.
|
||||
|
||||
```
|
||||
/graphify . # funktioniert mit jedem Ordner — Codebase, Notizen, Papers, alles
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html interaktiver Graph — im Browser öffnen, Knoten anklicken, suchen, filtern
|
||||
├── GRAPH_REPORT.md Gott-Knoten, überraschende Verbindungen, vorgeschlagene Fragen
|
||||
├── graph.json persistenter Graph — Wochen später abfragen, ohne neu zu lesen
|
||||
└── cache/ SHA256-Cache — erneute Ausführungen verarbeiten nur geänderte Dateien
|
||||
```
|
||||
|
||||
Füge eine `.graphifyignore`-Datei hinzu, um Ordner auszuschließen:
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
vendor/
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
```
|
||||
|
||||
Gleiche Syntax wie `.gitignore`. Du kannst eine einzelne `.graphifyignore` im Repo-Stammverzeichnis behalten — Muster funktionieren korrekt, auch wenn graphify auf einem Unterordner ausgeführt wird.
|
||||
|
||||
## So funktioniert es
|
||||
|
||||
graphify läuft in drei Durchgängen. Zuerst extrahiert ein deterministischer AST-Durchgang Strukturen aus Code-Dateien (Klassen, Funktionen, Importe, Aufrufgraphen, Docstrings, Begründungskommentare) — ohne LLM. Zweitens werden Video- und Audiodateien lokal mit faster-whisper transkribiert, angetrieben durch einen domänenspezifischen Prompt aus Korpus-Gott-Knoten — Transkripte werden gecacht, sodass erneute Ausführungen sofort sind. Drittens laufen Claude-Subagenten parallel über Dokumente, Papers, Bilder und Transkripte, um Konzepte, Beziehungen und Designbegründungen zu extrahieren. Die Ergebnisse werden in einem NetworkX-Graphen zusammengeführt, mit Leiden-Community-Erkennung geclustert und als interaktives HTML, abfragbares JSON und ein Klartext-Audit-Report exportiert.
|
||||
|
||||
**Clustering basiert auf Graph-Topologie — keine Embeddings.** Leiden findet Communities durch Kantendichte. Die semantischen Ähnlichkeitskanten, die Claude extrahiert (`semantically_similar_to`, markiert als INFERRED), sind bereits im Graphen, sodass sie die Community-Erkennung direkt beeinflussen. Die Graphstruktur ist das Ähnlichkeitssignal — kein separater Embedding-Schritt oder Vektordatenbank nötig.
|
||||
|
||||
Jede Beziehung ist markiert als `EXTRACTED` (direkt in der Quelle gefunden), `INFERRED` (begründete Schlussfolgerung mit Konfidenzwert) oder `AMBIGUOUS` (zur Überprüfung markiert). Du weißt immer, was gefunden vs. erschlossen wurde.
|
||||
|
||||
## Installation
|
||||
|
||||
**Voraussetzungen:** Python 3.10+ und eines von: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com), [Gemini CLI](https://github.com/google-gemini/gemini-cli), [GitHub Copilot CLI](https://docs.github.com/en/copilot/how-tos/copilot-cli), [VS Code Copilot Chat](https://code.visualstudio.com/docs/copilot/overview), [Aider](https://aider.chat), [OpenClaw](https://openclaw.ai), [Factory Droid](https://factory.ai), [Trae](https://trae.ai), [Kiro](https://kiro.dev), Hermes oder [Google Antigravity](https://antigravity.google)
|
||||
|
||||
```bash
|
||||
# Empfohlen — funktioniert auf Mac und Linux ohne PATH-Einrichtung
|
||||
uv tool install graphifyy && graphify install
|
||||
# oder mit pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# oder einfaches pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Offizielles Paket:** Das PyPI-Paket heißt `graphifyy` (installieren mit `pip install graphifyy`). Andere Pakete mit Namen `graphify*` auf PyPI sind nicht mit diesem Projekt verbunden. Das einzige offizielle Repository ist [safishamsi/graphify](https://github.com/safishamsi/graphify). CLI und Skill-Befehl heißen weiterhin `graphify`.
|
||||
|
||||
> **`graphify: command not found`?** Verwende `uv tool install graphifyy` (empfohlen) oder `pipx install graphifyy` — beide platzieren die CLI an einem verwalteten Ort, der automatisch im PATH ist. Mit einfachem `pip` musst du möglicherweise `~/.local/bin` (Linux) oder `~/Library/Python/3.x/bin` (Mac) zum PATH hinzufügen, oder `python -m graphify` verwenden.
|
||||
|
||||
### Plattformunterstützung
|
||||
|
||||
| Plattform | Installationsbefehl |
|
||||
|-----------|---------------------|
|
||||
| Claude Code (Linux/Mac) | `graphify install` |
|
||||
| Claude Code (Windows) | `graphify install` (automatisch erkannt) oder `graphify install --platform windows` |
|
||||
| Codex | `graphify install --platform codex` |
|
||||
| OpenCode | `graphify install --platform opencode` |
|
||||
| GitHub Copilot CLI | `graphify install --platform copilot` |
|
||||
| VS Code Copilot Chat | `graphify vscode install` |
|
||||
| Aider | `graphify install --platform aider` |
|
||||
| OpenClaw | `graphify install --platform claw` |
|
||||
| Factory Droid | `graphify install --platform droid` |
|
||||
| Trae | `graphify install --platform trae` |
|
||||
| Trae CN | `graphify install --platform trae-cn` |
|
||||
| Gemini CLI | `graphify install --platform gemini` |
|
||||
| Hermes | `graphify install --platform hermes` |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
Dann öffne deinen KI-Coding-Assistenten und tippe:
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
Hinweis: Codex verwendet `$` statt `/` für Skill-Aufrufe, also tippe `$graphify .`.
|
||||
|
||||
### Assistenten immer den Graphen nutzen lassen (empfohlen)
|
||||
|
||||
Nach dem Erstellen eines Graphen, führe dies einmal in deinem Projekt aus:
|
||||
|
||||
| Plattform | Befehl |
|
||||
|-----------|--------|
|
||||
| Claude Code | `graphify claude install` |
|
||||
| Codex | `graphify codex install` |
|
||||
| OpenCode | `graphify opencode install` |
|
||||
| GitHub Copilot CLI | `graphify copilot install` |
|
||||
| VS Code Copilot Chat | `graphify vscode install` |
|
||||
| Aider | `graphify aider install` |
|
||||
| OpenClaw | `graphify claw install` |
|
||||
| Factory Droid | `graphify droid install` |
|
||||
| Trae | `graphify trae install` |
|
||||
| Trae CN | `graphify trae-cn install` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Gemini CLI | `graphify gemini install` |
|
||||
| Hermes | `graphify hermes install` |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
## Verwendung
|
||||
|
||||
```
|
||||
/graphify # aktuelles Verzeichnis verarbeiten
|
||||
/graphify ./raw # spezifischen Ordner verarbeiten
|
||||
/graphify ./raw --mode deep # aggressivere INFERRED-Kanten-Extraktion
|
||||
/graphify ./raw --update # nur geänderte Dateien neu extrahieren
|
||||
/graphify ./raw --directed # gerichteten Graphen erstellen
|
||||
/graphify ./raw --cluster-only # Clustering auf bestehendem Graphen neu ausführen
|
||||
/graphify ./raw --no-viz # kein HTML, nur Report + JSON
|
||||
/graphify ./raw --obsidian # Obsidian-Vault generieren (opt-in)
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # Paper abrufen, speichern, Graphen aktualisieren
|
||||
/graphify add <video-url> # Audio herunterladen, transkribieren, hinzufügen
|
||||
/graphify query "was verbindet Attention mit dem Optimizer?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
graphify hook install # Git-Hooks installieren
|
||||
graphify update ./src # Code-Dateien neu extrahieren, kein LLM benötigt
|
||||
graphify watch ./src # Graphen bei Änderungen automatisch aktualisieren
|
||||
```
|
||||
|
||||
## Was du bekommst
|
||||
|
||||
**Gott-Knoten** — Konzepte mit dem höchsten Grad (durch die alles fließt)
|
||||
|
||||
**Überraschende Verbindungen** — nach Composite-Score eingestuft. Code-Paper-Kanten werden höher bewertet. Jedes Ergebnis enthält ein Klartext-Warum.
|
||||
|
||||
**Vorgeschlagene Fragen** — 4-5 Fragen, die der Graph einzigartig gut beantworten kann
|
||||
|
||||
**Das „Warum"** — Docstrings, Inline-Kommentare (`# NOTE:`, `# IMPORTANT:`, `# HACK:`, `# WHY:`), und Designbegründungen aus Dokumenten werden als `rationale_for`-Knoten extrahiert.
|
||||
|
||||
**Konfidenzwerte** — jede INFERRED-Kante hat einen `confidence_score` (0,0-1,0).
|
||||
|
||||
**Token-Benchmark** — wird automatisch nach jeder Ausführung gedruckt. Auf einem gemischten Korpus: **71,5-fach** weniger Tokens pro Abfrage gegenüber Rohdateien.
|
||||
|
||||
**Auto-Sync** (`--watch`) — läuft im Hintergrund und aktualisiert den Graphen bei Codeänderungen automatisch.
|
||||
|
||||
**Git-Hooks** (`graphify hook install`) — installiert Post-Commit- und Post-Checkout-Hooks.
|
||||
|
||||
## Datenschutz
|
||||
|
||||
graphify sendet Dateiinhalte an die Modell-API deines KI-Assistenten für semantische Extraktion von Dokumenten, Papers und Bildern. Code-Dateien werden lokal via tree-sitter AST verarbeitet — kein Dateiinhalt verlässt dein Gerät für Code. Video- und Audiodateien werden lokal mit faster-whisper transkribiert. Keine Telemetrie, keine Nutzungsverfolgung.
|
||||
|
||||
## Tech-Stack
|
||||
|
||||
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Semantische Extraktion via Claude, GPT-4 oder welches Modell deine Plattform verwendet. Video-Transkription via faster-whisper + yt-dlp (optional).
|
||||
|
||||
## Auf graphify aufgebaut — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) ist die Enterprise-Schicht über graphify. Wo graphify einen Ordner mit Dateien in einen Wissensgraphen verwandelt, wendet Penpax denselben Graphen auf dein gesamtes Arbeitsleben an — kontinuierlich.
|
||||
|
||||
**Kostenlose Testversion startet bald.** [Auf die Warteliste setzen →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
## Star-Verlauf
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**Μια δεξιότητα για βοηθούς κώδικα AI.** Πληκτρολογήστε `/graphify` στο Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro ή Google Antigravity — διαβάζει τα αρχεία σας, δημιουργεί ένα γράφο γνώσης και σας επιστρέφει δομή που δεν ξέρατε ότι υπήρχε. Κατανοήστε μια βάση κώδικα γρηγορότερα. Βρείτε το «γιατί» πίσω από αρχιτεκτονικές αποφάσεις.
|
||||
|
||||
Πλήρως πολυτροπικό. Προσθέστε κώδικα, PDF, markdown, στιγμιότυπα οθόνης, διαγράμματα, φωτογραφίες πίνακα, εικόνες σε άλλες γλώσσες ή αρχεία βίντεο και ήχου — το graphify εξάγει έννοιες και σχέσεις από όλα και τα συνδέει σε ένα ενιαίο γράφο. Τα βίντεο μεταγράφονται τοπικά με το Whisper. Υποστηρίζει 25 γλώσσες προγραμματισμού μέσω tree-sitter AST.
|
||||
|
||||
> Ο Andrej Karpathy διατηρεί ένα φάκελο `/raw` όπου αποθηκεύει εργασίες, tweets, στιγμιότυπα και σημειώσεις. Το graphify είναι η απάντηση σε αυτό το πρόβλημα — **71,5x** λιγότερα token ανά ερώτημα σε σύγκριση με την ανάγνωση αρχείων, επίμονο μεταξύ συνεδριών.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html διαδραστικός γράφος — ανοίξτε σε οποιοδήποτε πρόγραμμα περιήγησης
|
||||
├── GRAPH_REPORT.md κόμβοι-θεοί, εκπληκτικές συνδέσεις, προτεινόμενες ερωτήσεις
|
||||
├── graph.json επίμονος γράφος — μπορεί να υποβληθεί σε ερωτήματα εβδομάδες αργότερα
|
||||
└── cache/ κρυφή μνήμη SHA256 — επαναλαμβανόμενες εκτελέσεις επεξεργάζονται μόνο τα αλλαγμένα αρχεία
|
||||
```
|
||||
|
||||
## Πώς λειτουργεί
|
||||
|
||||
Το graphify λειτουργεί σε τρεις διελεύσεις. Πρώτα, μια ντετερμινιστική διέλευση AST εξάγει δομή από αρχεία κώδικα χωρίς LLM. Στη συνέχεια, τα αρχεία βίντεο και ήχου μεταγράφονται τοπικά με faster-whisper. Τέλος, οι υπο-πράκτορες Claude εκτελούνται παράλληλα σε έγγραφα, εργασίες, εικόνες και μεταγραφές. Τα αποτελέσματα συγχωνεύονται σε ένα γράφο NetworkX, ομαδοποιούνται με Leiden και εξάγονται ως διαδραστική HTML, JSON για ερωτήματα και αναφορά ελέγχου.
|
||||
|
||||
Κάθε σχέση επισημαίνεται ως `EXTRACTED`, `INFERRED` (με βαθμολογία εμπιστοσύνης) ή `AMBIGUOUS`.
|
||||
|
||||
## Εγκατάσταση
|
||||
|
||||
**Απαιτήσεις:** Python 3.10+ και ένα από: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) και άλλα.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# ή με pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# ή pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Επίσημο πακέτο:** Το πακέτο PyPI ονομάζεται `graphifyy`. Το μοναδικό επίσημο αποθετήριο είναι το [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Χρήση
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "τι συνδέει το Attention με τον optimizer;"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Τι λαμβάνετε
|
||||
|
||||
**Κόμβοι-θεοί** — έννοιες με τον υψηλότερο βαθμό · **Εκπληκτικές συνδέσεις** — ταξινομημένες κατά βαθμολογία · **Προτεινόμενες ερωτήσεις** · **Το «γιατί»** — docstrings και αιτιολόγηση σχεδιασμού εξαγόμενα ως κόμβοι · **Σημείο αναφοράς token** — **71,5x** λιγότερα token σε μικτό σώμα κειμένου.
|
||||
|
||||
## Απόρρητο
|
||||
|
||||
Τα αρχεία κώδικα επεξεργάζονται τοπικά μέσω tree-sitter AST. Τα βίντεο μεταγράφονται τοπικά με faster-whisper. Χωρίς τηλεμετρία.
|
||||
|
||||
## Δημιουργήθηκε στο graphify — Penpax
|
||||
|
||||
Το [**Penpax**](https://safishamsi.github.io/penpax.ai) είναι το εταιρικό επίπεδο πάνω από το graphify. **Δωρεάν δοκιμή σύντομα.** [Εγγραφείτε στη λίστα αναμονής →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,170 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></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>
|
||||
</p>
|
||||
|
||||
**Una habilidad para asistentes de código IA.** Escribe `/graphify` en Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro o Google Antigravity — lee tus archivos, construye un grafo de conocimiento y te devuelve estructura que no sabías que existía. Entiende una base de código más rápido. Encuentra el «por qué» detrás de las decisiones arquitectónicas.
|
||||
|
||||
Totalmente multimodal. Deposita código, PDFs, markdown, capturas de pantalla, diagramas, fotos de pizarras, imágenes en otros idiomas, o archivos de video y audio — graphify extrae conceptos y relaciones de todo ello y los conecta en un solo grafo. Los videos se transcriben localmente con Whisper usando un prompt adaptado al dominio derivado de tu corpus. 25 lenguajes de programación soportados mediante tree-sitter AST (Python, JS, TS, Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Lua, Zig, PowerShell, Elixir, Objective-C, Julia, Verilog, SystemVerilog, Vue, Svelte, Dart).
|
||||
|
||||
> Andrej Karpathy mantiene una carpeta `/raw` donde deposita papers, tweets, capturas de pantalla y notas. graphify es la respuesta a ese problema — 71,5 veces menos tokens por consulta versus leer los archivos sin procesar, persistente entre sesiones, honesto sobre lo que encontró versus lo que infirió.
|
||||
|
||||
```
|
||||
/graphify . # funciona con cualquier carpeta — tu código, notas, papers, todo
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html grafo interactivo — abrir en cualquier navegador, hacer clic en nodos, buscar
|
||||
├── GRAPH_REPORT.md nodos dios, conexiones sorprendentes, preguntas sugeridas
|
||||
├── graph.json grafo persistente — consultar semanas después sin releer
|
||||
└── cache/ caché SHA256 — las re-ejecuciones solo procesan archivos modificados
|
||||
```
|
||||
|
||||
Añade un archivo `.graphifyignore` para excluir carpetas:
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
vendor/
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
```
|
||||
|
||||
Misma sintaxis que `.gitignore`. Puedes mantener un único `.graphifyignore` en la raíz del repositorio.
|
||||
|
||||
## Cómo funciona
|
||||
|
||||
graphify se ejecuta en tres pasadas. Primero, una pasada AST determinista extrae estructura de los archivos de código (clases, funciones, importaciones, grafos de llamadas, docstrings, comentarios de justificación) sin necesidad de LLM. Segundo, los archivos de video y audio se transcriben localmente con faster-whisper usando un prompt adaptado al dominio derivado de los nodos dios del corpus. Tercero, subagentes de Claude se ejecutan en paralelo sobre documentos, papers, imágenes y transcripciones para extraer conceptos, relaciones y justificaciones de diseño. Los resultados se fusionan en un grafo NetworkX, se agrupan con detección de comunidades Leiden, y se exportan como HTML interactivo, JSON consultable y un informe de auditoría en lenguaje natural.
|
||||
|
||||
**El clustering se basa en la topología del grafo — sin embeddings.** Leiden encuentra comunidades por densidad de aristas. Las aristas de similitud semántica que Claude extrae (`semantically_similar_to`, marcadas como INFERRED) ya están en el grafo. La estructura del grafo es la señal de similitud — no se necesita paso de embedding separado ni base de datos vectorial.
|
||||
|
||||
Cada relación está etiquetada como `EXTRACTED` (encontrada directamente en la fuente), `INFERRED` (inferencia razonable con puntuación de confianza) o `AMBIGUOUS` (marcada para revisión).
|
||||
|
||||
## Instalación
|
||||
|
||||
**Requisitos:** Python 3.10+ y uno de: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com), [Gemini CLI](https://github.com/google-gemini/gemini-cli), [GitHub Copilot CLI](https://docs.github.com/en/copilot/how-tos/copilot-cli), [VS Code Copilot Chat](https://code.visualstudio.com/docs/copilot/overview), [Aider](https://aider.chat), [OpenClaw](https://openclaw.ai), [Factory Droid](https://factory.ai), [Trae](https://trae.ai), [Kiro](https://kiro.dev), Hermes o [Google Antigravity](https://antigravity.google)
|
||||
|
||||
```bash
|
||||
# Recomendado — funciona en Mac y Linux sin configurar el PATH
|
||||
uv tool install graphifyy && graphify install
|
||||
# o con pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# o pip simple
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Paquete oficial:** El paquete PyPI se llama `graphifyy` (instalar con `pip install graphifyy`). Otros paquetes llamados `graphify*` en PyPI no están afiliados con este proyecto. El único repositorio oficial es [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
### Soporte de plataformas
|
||||
|
||||
| Plataforma | Comando de instalación |
|
||||
|------------|------------------------|
|
||||
| Claude Code (Linux/Mac) | `graphify install` |
|
||||
| Claude Code (Windows) | `graphify install` (detección automática) o `graphify install --platform windows` |
|
||||
| Codex | `graphify install --platform codex` |
|
||||
| OpenCode | `graphify install --platform opencode` |
|
||||
| GitHub Copilot CLI | `graphify install --platform copilot` |
|
||||
| VS Code Copilot Chat | `graphify vscode install` |
|
||||
| Aider | `graphify install --platform aider` |
|
||||
| OpenClaw | `graphify install --platform claw` |
|
||||
| Factory Droid | `graphify install --platform droid` |
|
||||
| Trae | `graphify install --platform trae` |
|
||||
| Trae CN | `graphify install --platform trae-cn` |
|
||||
| Gemini CLI | `graphify install --platform gemini` |
|
||||
| Hermes | `graphify install --platform hermes` |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
Luego abre tu asistente de código IA y escribe:
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
Nota: Codex usa `$` en lugar de `/` para habilidades, así que escribe `$graphify .`.
|
||||
|
||||
### Hacer que el asistente siempre use el grafo (recomendado)
|
||||
|
||||
Después de construir un grafo, ejecuta esto una vez en tu proyecto:
|
||||
|
||||
| Plataforma | Comando |
|
||||
|------------|---------|
|
||||
| Claude Code | `graphify claude install` |
|
||||
| Codex | `graphify codex install` |
|
||||
| OpenCode | `graphify opencode install` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Gemini CLI | `graphify gemini install` |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
## Uso
|
||||
|
||||
```
|
||||
/graphify # directorio actual
|
||||
/graphify ./raw # carpeta específica
|
||||
/graphify ./raw --mode deep # extracción de aristas INFERRED más agresiva
|
||||
/graphify ./raw --update # re-extraer solo archivos modificados
|
||||
/graphify ./raw --directed # grafo dirigido
|
||||
/graphify ./raw --cluster-only # re-ejecutar clustering en grafo existente
|
||||
/graphify ./raw --no-viz # sin HTML, solo informe + JSON
|
||||
/graphify ./raw --obsidian # generar vault de Obsidian (opt-in)
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # obtener un paper
|
||||
/graphify add <video-url> # descargar audio, transcribir, añadir
|
||||
/graphify query "¿qué conecta Attention con el optimizador?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
graphify hook install # instalar hooks de Git
|
||||
graphify update ./src # re-extraer archivos de código, sin LLM
|
||||
graphify watch ./src # actualización automática del grafo
|
||||
```
|
||||
|
||||
## Qué obtienes
|
||||
|
||||
**Nodos dios** — conceptos con mayor grado (por donde todo pasa)
|
||||
|
||||
**Conexiones sorprendentes** — clasificadas por puntuación compuesta. Las aristas código-paper puntúan más alto. Cada resultado incluye un por qué en lenguaje natural.
|
||||
|
||||
**Preguntas sugeridas** — 4-5 preguntas que el grafo está en posición única de responder
|
||||
|
||||
**El «por qué»** — docstrings, comentarios inline (`# NOTE:`, `# IMPORTANT:`, `# HACK:`, `# WHY:`), y justificaciones de diseño extraídas como nodos `rationale_for`.
|
||||
|
||||
**Puntuaciones de confianza** — cada arista INFERRED tiene un `confidence_score` (0,0-1,0).
|
||||
|
||||
**Benchmark de tokens** — impreso automáticamente tras cada ejecución. En un corpus mixto: **71,5 veces** menos tokens por consulta vs archivos sin procesar.
|
||||
|
||||
**Sincronización automática** (`--watch`) — actualiza el grafo automáticamente cuando cambia el código.
|
||||
|
||||
**Hooks de Git** (`graphify hook install`) — instala hooks post-commit y post-checkout.
|
||||
|
||||
## Privacidad
|
||||
|
||||
graphify envía contenido de archivos a la API del modelo de tu asistente IA para extracción semántica de documentos, papers e imágenes. Los archivos de código se procesan localmente mediante tree-sitter AST. Los archivos de video y audio se transcriben localmente con faster-whisper. Sin telemetría, sin seguimiento de uso.
|
||||
|
||||
## Stack técnico
|
||||
|
||||
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Extracción semántica via Claude, GPT-4 o el modelo de tu plataforma. Transcripción de video via faster-whisper + yt-dlp (opcional).
|
||||
|
||||
## Construido sobre graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) es la capa enterprise sobre graphify. Donde graphify convierte una carpeta de archivos en un grafo de conocimiento, Penpax aplica el mismo grafo a toda tu vida laboral — continuamente.
|
||||
|
||||
**Prueba gratuita próximamente.** [Unirse a la lista de espera →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
## Historial de estrellas
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,572 @@
|
||||
<p align="center">
|
||||
<a href="https://graphifylabs.ai"><img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇷 <a href="README.fa-IR.md">فارسی</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a> | 🇵🇭 <a href="README.fil-PH.md">Filipino</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://www.ycombinator.com/companies/graphify"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<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://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></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://x.com/graphifyy"><img src="https://img.shields.io/badge/X-graphifyy-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
</p>
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
**یک مهارت برای دستیار کدنویسی هوش مصنوعی.** `/graphify` را در Claude Code، Codex، OpenCode، Kilo Code، Cursor، Gemini CLI، GitHub Copilot CLI، VS Code Copilot Chat، Aider، Amp، OpenClaw، Factory Droid، Trae، Hermes، Kimi Code، Kiro، Pi، Devin CLI یا Google Antigravity تایپ کنید — تمام پروژهتان را میخواند، یک گراف دانش میسازد، و ساختاری که نمیدانستید وجود دارد را به شما بازمیگرداند. کدبیس را سریعتر درک کنید. «چرا»ی پشت تصمیمات معماری را کشف کنید.
|
||||
|
||||
کاملاً چندوجهی. کد، PDF، مارکداون، اسکرینشات، نمودار، عکس وایتبورد، تصاویر به زبانهای دیگر، یا فایلهای ویدئو و صوتی بریزید — graphify مفاهیم و روابط را از همه آنها استخراج کرده و در یک گراف به هم متصل میکند. ویدئوها بهصورت محلی با Whisper رونویسی میشوند. ۳۶ زبان برنامهنویسی از طریق tree-sitter AST پشتیبانی میشوند.
|
||||
|
||||
> Andrej Karpathy یک پوشه `/raw` نگه میدارد که در آن مقالات، توییتها، اسکرینشاتها و یادداشتها میریزد. graphify پاسخ آن مشکل است — **۷۱.۵ برابر** کمتر توکن در هر پرسوجو در مقایسه با خواندن فایلهای خام، در طول جلسات پایدار، و صادق در مورد آنچه پیدا شده در برابر آنچه استنباط شده است.
|
||||
|
||||
</div>
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
همین. سه فایل دریافت میکنید:
|
||||
|
||||
</div>
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html در هر مرورگری باز کنید — روی گرهها کلیک کنید، فیلتر کنید، جستجو کنید
|
||||
├── GRAPH_REPORT.md نکات کلیدی: مفاهیم محوری، اتصالات شگفتانگیز، سؤالات پیشنهادی
|
||||
└── graph.json گراف کامل — هر زمان بدون نیاز به بازخوانی فایلها پرسوجو کنید
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
برای یک صفحه معماری خوانا با نمودارهای جریان فراخوانی Mermaid، اجرا کنید:
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
graphify export callflow-html
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
## پیشنیازها
|
||||
|
||||
</div>
|
||||
|
||||
| پیشنیاز | حداقل | بررسی | نصب |
|
||||
|---|---|---|---|
|
||||
| Python | ۳.۱۰+ | `python --version` | [python.org](https://www.python.org/downloads/) |
|
||||
| uv *(پیشنهادی)* | هر نسخه | `uv --version` | `curl -LsSf https://astral.sh/uv/install.sh \| sh` |
|
||||
| pipx *(جایگزین)* | هر نسخه | `pipx --version` | `pip install pipx` |
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
**نصب سریع macOS (Homebrew):**
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
brew install python@3.12 uv
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
**نصب سریع Windows:**
|
||||
|
||||
</div>
|
||||
|
||||
```powershell
|
||||
winget install astral-sh.uv
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
**Ubuntu/Debian:**
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
sudo apt install python3.12 python3-pip pipx
|
||||
# یا نصب uv:
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
## نصب
|
||||
|
||||
> **بسته رسمی:** بسته PyPI به نام `graphifyy` است (با دو y). سایر بستههای `graphify*` در PyPI وابسته به این پروژه نیستند. دستور CLI همچنان `graphify` است.
|
||||
|
||||
**مرحله ۱ — نصب بسته:**
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
# پیشنهادی (uv بهطور خودکار graphify را در PATH قرار میدهد):
|
||||
uv tool install graphifyy
|
||||
|
||||
# جایگزینها:
|
||||
pipx install graphifyy
|
||||
pip install graphifyy # ممکن است نیاز به تنظیم PATH داشته باشد — یادداشت زیر را ببینید
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
**مرحله ۲ — ثبت مهارت در دستیار هوش مصنوعی:**
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
graphify install
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
همین. دستیار هوش مصنوعیتان را باز کنید و `/graphify .` تایپ کنید.
|
||||
|
||||
برای نصب مهارت دستیار در مخزن جاری بهجای پروفایل کاربری، `--project` اضافه کنید:
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
graphify install --project
|
||||
graphify install --project --platform codex
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
> **یادداشت PowerShell:** از `graphify .` استفاده کنید نه `/graphify .` — اسلش ابتدایی در PowerShell جداکننده مسیر است.
|
||||
|
||||
> **`graphify: command not found`؟** از `uv tool install graphifyy` یا `pipx install graphifyy` استفاده کنید — هر دو CLI را بهطور خودکار در PATH قرار میدهند.
|
||||
|
||||
### انتخاب پلتفرم
|
||||
|
||||
</div>
|
||||
|
||||
| پلتفرم | دستور نصب |
|
||||
|----------|----------------|
|
||||
| Claude Code (Linux/Mac) | `graphify install` |
|
||||
| Claude Code (Windows) | `graphify install` (تشخیص خودکار) یا `graphify install --platform windows` |
|
||||
| CodeBuddy | `graphify install --platform codebuddy` |
|
||||
| Codex | `graphify install --platform codex` |
|
||||
| OpenCode | `graphify install --platform opencode` |
|
||||
| Kilo Code | `graphify install --platform kilo` |
|
||||
| GitHub Copilot CLI | `graphify install --platform copilot` |
|
||||
| VS Code Copilot Chat | `graphify vscode install` |
|
||||
| Aider | `graphify install --platform aider` |
|
||||
| OpenClaw | `graphify install --platform claw` |
|
||||
| Factory Droid | `graphify install --platform droid` |
|
||||
| Trae | `graphify install --platform trae` |
|
||||
| Trae CN | `graphify install --platform trae-cn` |
|
||||
| Gemini CLI | `graphify install --platform gemini` |
|
||||
| Hermes | `graphify install --platform hermes` |
|
||||
| Kimi Code | `graphify install --platform kimi` |
|
||||
| Amp | `graphify amp install` |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Pi coding agent | `graphify install --platform pi` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Devin CLI | `graphify devin install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
### افزونههای اختیاری
|
||||
|
||||
فقط آنچه نیاز دارید نصب کنید:
|
||||
|
||||
</div>
|
||||
|
||||
| افزونه | چه چیزی اضافه میکند | نصب |
|
||||
|---|---|---|
|
||||
| `pdf` | استخراج PDF | `uv tool install "graphifyy[pdf]"` |
|
||||
| `office` | پشتیبانی از `.docx` و `.xlsx` | `uv tool install "graphifyy[office]"` |
|
||||
| `google` | رندرینگ Google Sheets | `uv tool install "graphifyy[google]"` |
|
||||
| `video` | رونویسی ویدئو/صوت | `uv tool install "graphifyy[video]"` |
|
||||
| `mcp` | سرور MCP stdio | `uv tool install "graphifyy[mcp]"` |
|
||||
| `neo4j` | پشتیبانی از Neo4j | `uv tool install "graphifyy[neo4j]"` |
|
||||
| `ollama` | استنتاج محلی Ollama | `uv tool install "graphifyy[ollama]"` |
|
||||
| `openai` | OpenAI / APIهای سازگار با OpenAI | `uv tool install "graphifyy[openai]"` |
|
||||
| `gemini` | Google Gemini API | `uv tool install "graphifyy[gemini]"` |
|
||||
| `anthropic` | Anthropic Claude API | `uv tool install "graphifyy[anthropic]"` |
|
||||
| `bedrock` | AWS Bedrock (از IAM استفاده میکند) | `uv tool install "graphifyy[bedrock]"` |
|
||||
| `sql` | استخراج طرح SQL | `uv tool install "graphifyy[sql]"` |
|
||||
| `all` | همه موارد بالا | `uv tool install "graphifyy[all]"` |
|
||||
|
||||
---
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
## دستیار را همیشه از گراف استفاده کنید
|
||||
|
||||
پس از ساخت گراف، یک بار در پروژهتان اجرا کنید:
|
||||
|
||||
</div>
|
||||
|
||||
| پلتفرم | دستور |
|
||||
|----------|---------|
|
||||
| Claude Code | `graphify claude install` |
|
||||
| CodeBuddy | `graphify codebuddy install` |
|
||||
| Codex | `graphify codex install` |
|
||||
| OpenCode | `graphify opencode install` |
|
||||
| Kilo Code | `graphify kilo install` |
|
||||
| GitHub Copilot CLI | `graphify copilot install` |
|
||||
| VS Code Copilot Chat | `graphify vscode install` |
|
||||
| Aider | `graphify aider install` |
|
||||
| OpenClaw | `graphify claw install` |
|
||||
| Factory Droid | `graphify droid install` |
|
||||
| Trae | `graphify trae install` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Gemini CLI | `graphify gemini install` |
|
||||
| Amp | `graphify amp install` |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Devin CLI | `graphify devin install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
این یک فایل پیکربندی کوچک مینویسد که به دستیارتان میگوید برای سؤالات مربوط به کدبیس، گراف دانش را مشورت بگیرد. برای حذف graphify از همه پلتفرمها به یکباره: `graphify uninstall` (با `--purge` برای حذف `graphify-out/` نیز).
|
||||
|
||||
---
|
||||
|
||||
## محتوای گزارش
|
||||
|
||||
- **گرههای اصلی** — پرارتباطترین مفاهیم پروژه. همه چیز از اینها عبور میکند.
|
||||
- **اتصالات شگفتانگیز** — پیوندهایی بین چیزهایی که در فایلها یا ماژولهای مختلف زندگی میکنند. بر اساس میزان غیرمنتظره بودن رتبهبندی شده.
|
||||
- **«چرا»** — نظرات درونخطی (`# NOTE:`، `# WHY:`، `# HACK:`)، داکاسترینگها و منطق طراحی از اسناد بهعنوان گرههای جداگانه مرتبط با کدی که توضیح میدهند استخراج میشوند.
|
||||
- **سؤالات پیشنهادی** — ۴ تا ۵ سؤال که گراف بهطور منحصربهفرد میتواند پاسخ دهد.
|
||||
- **برچسبهای اطمینان** — هر رابطه استنباطشده با `EXTRACTED`، `INFERRED` یا `AMBIGUOUS` علامتگذاری میشود. همیشه میدانید چه چیزی پیدا شده در برابر چه چیزی حدس زده شده.
|
||||
|
||||
---
|
||||
|
||||
## فایلهای پشتیبانیشده
|
||||
|
||||
</div>
|
||||
|
||||
| نوع | پسوندها |
|
||||
|------|-----------|
|
||||
| کد (۳۶ دستور زبان tree-sitter) | `.py .ts .js .jsx .tsx .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1 .ex .exs .vue .svelte .dart` و بیشتر |
|
||||
| اسناد | `.md .mdx .html .txt .rst .yaml .yml` |
|
||||
| Office | `.docx .xlsx` (نیاز به `graphifyy[office]`) |
|
||||
| PDF | `.pdf` |
|
||||
| تصاویر | `.png .jpg .webp .gif` |
|
||||
| ویدئو / صوت | `.mp4 .mov .mp3 .wav` و بیشتر (نیاز به `graphifyy[video]`) |
|
||||
| YouTube / URLها | هر URL ویدئویی (نیاز به `graphifyy[video]`) |
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
کد بهصورت محلی با tree-sitter بدون هیچ فراخوانی API استخراج میشود. بقیه از طریق API مدل دستیار هوش مصنوعی شما پردازش میشوند.
|
||||
|
||||
---
|
||||
|
||||
## دستورات رایج
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
/graphify . # ساخت گراف برای پوشه جاری
|
||||
/graphify ./docs --update # فقط فایلهای تغییریافته را مجدداً استخراج کن
|
||||
/graphify . --cluster-only # خوشهبندی مجدد بدون استخراج مجدد
|
||||
/graphify . --no-viz # فقط گزارش + JSON، بدون HTML
|
||||
/graphify . --wiki # ساخت ویکی مارکداون از گراف
|
||||
graphify export callflow-html # HTML معماری/جریان فراخوانی Mermaid
|
||||
|
||||
/graphify query "چه چیزی auth را به پایگاه داده متصل میکند؟"
|
||||
/graphify path "UserService" "DatabasePool"
|
||||
/graphify explain "RateLimiter"
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # یک مقاله را واکشی و اضافه کن
|
||||
/graphify add <youtube-url> # رونویسی و اضافه کردن ویدئو
|
||||
|
||||
graphify hook install # بازسازی خودکار پس از هر commit
|
||||
graphify merge-graphs a.json b.json # ترکیب دو گراف
|
||||
|
||||
graphify prs # داشبورد PR: وضعیت CI، بررسی، تأثیر گراف
|
||||
graphify prs 42 # بررسی عمیق PR شماره ۴۲
|
||||
graphify prs --triage # رتبهبندی صف بررسی با هوش مصنوعی
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
[مرجع کامل دستورات](#full-command-reference) را ببینید.
|
||||
|
||||
---
|
||||
|
||||
## نادیده گرفتن فایلها
|
||||
|
||||
یک `.graphifyignore` در ریشه پروژه بسازید — همان سینتکس `.gitignore`، از جمله نفی با `!`.
|
||||
|
||||
**`.gitignore` بهطور خودکار رعایت میشود.** اگر `.graphifyignore` در یک دایرکتوری وجود نداشته باشد، graphify به `.gitignore` آن دایرکتوری بازمیگردد.
|
||||
|
||||
</div>
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
|
||||
# فقط src/ را ایندکس کن، بقیه را نادیده بگیر
|
||||
*
|
||||
!src/
|
||||
!src/**
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
## تنظیمات تیمی
|
||||
|
||||
`graphify-out/` برای commit شدن در git طراحی شده تا همه در تیم با یک نقشه شروع کنند.
|
||||
|
||||
**افزودنهای پیشنهادی به `.gitignore`:**
|
||||
|
||||
</div>
|
||||
|
||||
```
|
||||
graphify-out/cost.json # فقط محلی
|
||||
# graphify-out/cache/ # اختیاری: برای سرعت commit کنید، برای کوچک نگه داشتن repo حذف کنید
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
**جریان کار:**
|
||||
۱. یک نفر `/graphify .` اجرا میکند و `graphify-out/` را commit میکند.
|
||||
۲. همه pull میکنند — دستیارشان فوراً گراف را میخواند.
|
||||
۳. `graphify hook install` را اجرا کنید تا پس از هر commit بهطور خودکار بازسازی شود.
|
||||
۴. وقتی اسناد یا مقالات تغییر کردند، `/graphify --update` اجرا کنید.
|
||||
|
||||
---
|
||||
|
||||
## استفاده مستقیم از گراف
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
# پرسوجو از گراف در ترمینال
|
||||
graphify query "جریان احراز هویت را نشان بده"
|
||||
graphify query "چه چیزی DigestAuth را به Response متصل میکند؟" --graph graphify-out/graph.json
|
||||
|
||||
# نمایش گراف بهعنوان سرور MCP
|
||||
python -m graphify.serve graphify-out/graph.json
|
||||
|
||||
# یا سرویسدهی از طریق HTTP برای دسترسی تیمی:
|
||||
python -m graphify.serve graphify-out/graph.json --transport http --port 8080
|
||||
python -m graphify.serve graphify-out/graph.json --transport http --host 0.0.0.0 --api-key "$SECRET"
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
سرور MCP دسترسی ساختاریافته میدهد: `query_graph`، `get_node`، `get_neighbors`، `shortest_path`، `list_prs`، `get_pr_impact`، `triage_prs`.
|
||||
|
||||
---
|
||||
|
||||
## متغیرهای محیطی
|
||||
|
||||
اینها فقط برای **استخراج بدون نمایشگر / CI** (`graphify extract`) لازم هستند. هنگام اجرا از طریق مهارت `/graphify` داخل IDE، API مدل توسط جلسه IDE شما تأمین میشود.
|
||||
|
||||
</div>
|
||||
|
||||
| متغیر | استفاده | شرط لزوم |
|
||||
|---|---|---|
|
||||
| `ANTHROPIC_API_KEY` | بکاند Claude (Anthropic) | `--backend claude` |
|
||||
| `GEMINI_API_KEY` یا `GOOGLE_API_KEY` | بکاند Google Gemini | `--backend gemini` |
|
||||
| `OPENAI_API_KEY` | OpenAI یا APIهای سازگار | `--backend openai` |
|
||||
| `DEEPSEEK_API_KEY` | بکاند DeepSeek | `--backend deepseek` |
|
||||
| `MOONSHOT_API_KEY` | بکاند Kimi Code | `--backend kimi` |
|
||||
| `OLLAMA_BASE_URL` | URL استنتاج محلی Ollama | `--backend ollama` |
|
||||
| `AZURE_OPENAI_API_KEY` | بکاند Azure OpenAI | `--backend azure` |
|
||||
| `GRAPHIFY_MAX_WORKERS` | تعداد thread های موازی AST | اختیاری |
|
||||
| `GRAPHIFY_FORCE` | بازسازی اجباری گراف | اختیاری |
|
||||
| `GRAPHIFY_QUERY_LOG_DISABLE` | برای غیرفعال کردن ثبت پرسوجو `1` تنظیم کنید | اختیاری |
|
||||
|
||||
---
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
## حریم خصوصی
|
||||
|
||||
- **فایلهای کد** — بهصورت محلی از طریق tree-sitter پردازش میشوند. هیچ چیزی دستگاه شما را ترک نمیکند.
|
||||
- **ویدئو / صوت** — بهصورت محلی با faster-whisper رونویسی میشوند. هیچ چیزی دستگاه شما را ترک نمیکند.
|
||||
- **اسناد، PDFها، تصاویر** — برای استخراج معنایی به API مدل دستیار هوش مصنوعی شما ارسال میشوند.
|
||||
- بدون تلهمتری، بدون ردیابی استفاده، بدون آنالیتیکس.
|
||||
|
||||
---
|
||||
|
||||
## عیبیابی
|
||||
|
||||
**`graphify: command not found` پس از `pip install graphifyy`**
|
||||
pip اسکریپتها را در دایرکتوری bin کاربر نصب میکند که ممکن است در PATH نباشد:
|
||||
- macOS: `~/Library/Python/3.x/bin` را به PATH در `~/.zshrc` اضافه کنید
|
||||
- Linux: `~/.local/bin` را به PATH در `~/.bashrc` اضافه کنید
|
||||
- یا از `uv tool install graphifyy` / `pipx install graphifyy` استفاده کنید.
|
||||
|
||||
**`/graphify .` در PowerShell "path not recognized" نشان میدهد**
|
||||
PowerShell `/` ابتدایی را بهعنوان جداکننده مسیر در نظر میگیرد. از `graphify .` (بدون اسلش) در Windows استفاده کنید.
|
||||
|
||||
**گراف پس از `--update` یا بازسازی گره کمتری دارد**
|
||||
اگر یک refactor فایلها را حذف کرده، گرههای قدیمی باقی میمانند. `--force` (یا `GRAPHIFY_FORCE=1`) را پاس دهید:
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
graphify extract . --force
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
**استخراج برای اسناد یا PDFها گره/یال خالی برمیگرداند**
|
||||
اسناد، PDFها و تصاویر به یک فراخوانی LLM نیاز دارند. بررسی کنید API key تنظیم شده و بکاند صحیح است:
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
ANTHROPIC_API_KEY=sk-... graphify extract ./docs --backend claude
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
## مرجع کامل دستورات
|
||||
|
||||
</div>
|
||||
|
||||
```
|
||||
/graphify # اجرا روی دایرکتوری جاری
|
||||
/graphify ./raw # اجرا روی پوشه مشخص
|
||||
/graphify ./raw --mode deep # استخراج رابطههای عمیقتر
|
||||
/graphify ./raw --update # فقط فایلهای تغییریافته را مجدداً استخراج کن
|
||||
/graphify ./raw --directed # حفظ جهت یالها
|
||||
/graphify ./raw --cluster-only # خوشهبندی مجدد روی گراف موجود
|
||||
/graphify ./raw --no-viz # بدون HTML بصریسازی
|
||||
/graphify ./raw --obsidian # تولید Obsidian vault
|
||||
/graphify ./raw --wiki # ساخت ویکی مارکداون قابل خزیدن برای agent
|
||||
/graphify ./raw --svg # خروجی graph.svg
|
||||
/graphify ./raw --graphml # خروجی برای Gephi / yEd
|
||||
/graphify ./raw --neo4j # تولید cypher.txt برای Neo4j
|
||||
/graphify ./raw --watch # همگامسازی خودکار با تغییر فایلها
|
||||
/graphify ./raw --mcp # شروع سرور MCP stdio
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762
|
||||
/graphify add <video-url>
|
||||
|
||||
/graphify query "چه چیزی attention را به optimizer متصل میکند؟"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
graphify uninstall # حذف از همه پلتفرمها
|
||||
graphify uninstall --purge # همچنین graphify-out/ را حذف کن
|
||||
|
||||
graphify hook install # hook های post-commit + post-checkout
|
||||
graphify hook uninstall
|
||||
graphify hook status
|
||||
|
||||
graphify claude install # CLAUDE.md + PreToolUse hook (Claude Code)
|
||||
graphify codex install # AGENTS.md + PreToolUse hook (Codex)
|
||||
graphify cursor install # .cursor/rules/graphify.mdc (Cursor)
|
||||
graphify gemini install # GEMINI.md + BeforeTool hook (Gemini CLI)
|
||||
graphify amp install # فایل مهارت (Amp)
|
||||
graphify kiro install # .kiro/skills/ + .kiro/steering/ (Kiro)
|
||||
graphify devin install # فایل مهارت + .windsurf/rules/ (Devin CLI)
|
||||
graphify antigravity install # .agents/rules + .agents/workflows (Google Antigravity)
|
||||
|
||||
graphify extract ./docs # استخراج بدون نمایشگر برای CI
|
||||
graphify extract ./docs --backend gemini # بکاند صریح
|
||||
graphify extract ./docs --backend ollama # Ollama محلی - بدون نیاز به API key
|
||||
graphify extract ./docs --backend bedrock # AWS Bedrock از طریق IAM
|
||||
graphify extract --postgres "postgresql://user:pass@host/db" # طرح PostgreSQL زنده
|
||||
|
||||
graphify prs # داشبورد PR
|
||||
graphify prs 42 # بررسی عمیق PR شماره ۴۲
|
||||
graphify prs --triage # رتبهبندی هوش مصنوعی
|
||||
graphify prs --conflicts # PR هایی که جوامع گراف را به اشتراک میگذارند
|
||||
|
||||
graphify export callflow-html # HTML معماری/جریان فراخوانی
|
||||
graphify merge-graphs a.json b.json --out merged.json
|
||||
graphify --version
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
## بیشتر بدانید
|
||||
|
||||
- [نحوه عملکرد](../../docs/how-it-works.md) — پایپلاین استخراج، تشخیص جامعه، امتیازدهی اطمینان، معیارها
|
||||
- [ARCHITECTURE.md](../../ARCHITECTURE.md) — تقسیمبندی ماژولها، نحوه اضافه کردن زبان جدید
|
||||
- [یکپارچهسازیهای اختیاری](../../docs/docker-mcp-sqlite.md) — Docker MCP Toolkit + SQLite
|
||||
|
||||
---
|
||||
|
||||
## ساختهشده روی graphify — Penpax
|
||||
|
||||
[**Penpax**](https://graphifylabs.ai) لایه همیشهروشن ساختهشده روی graphify است — همان رویکرد گراف را بر کل زندگی کاری شما اعمال میکند: جلسات، تاریخچه مرورگر، ایمیلها، فایلها و کد، بهصورت مداوم در پسزمینه بهروزرسانی میشود.
|
||||
|
||||
ساختهشده برای کسانی که کارشان در صدها مکالمه و سند پراکنده است. بدون ابر، کاملاً روی دستگاه.
|
||||
|
||||
**آزمایش رایگان بهزودی راهاندازی میشود.** [به لیست انتظار بپیوندید ←](https://graphifylabs.ai)
|
||||
|
||||
---
|
||||
|
||||
</div>
|
||||
|
||||
<details>
|
||||
<summary>مشارکت در پروژه</summary>
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
### راهاندازی محیط توسعه
|
||||
|
||||
این پروژه از [uv](https://docs.astral.sh/uv/) برای جریان کار توسعه استفاده میکند. یک بار آن را نصب کنید، سپس:
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
git clone https://github.com/safishamsi/graphify.git
|
||||
cd graphify
|
||||
git checkout v8 # شاخه توسعه فعال
|
||||
|
||||
uv sync --all-extras
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
### اجرای تستها
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
uv run pytest tests/ -q # اجرای کل مجموعه
|
||||
uv run pytest tests/test_extract.py -q # یک ماژول
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
### جریان کار Git
|
||||
|
||||
- توسعه فعال روی شاخه `v8` انجام میشود.
|
||||
- سبک commit: `fix: <توضیح>` / `feat: <توضیح>` / `docs: <توضیح>`
|
||||
- قبل از باز کردن PR، `uv run pytest tests/ -q` اجرا کنید و از موفقیت آن مطمئن شوید.
|
||||
|
||||
### چه چیزی مشارکت کنیم
|
||||
|
||||
**نمونههای کاری** مفیدترین نوع مشارکت هستند. `/graphify` را روی یک corpus واقعی اجرا کنید، خروجی را در `worked/{slug}/` ذخیره کنید، یک `review.md` صادقانه بنویسید که چه چیزهایی درست و نادرست بوده، و یک PR باز کنید.
|
||||
|
||||
**باگهای استخراج** — یک issue با فایل ورودی، آیتم کش (`graphify-out/cache/`) و آنچه اشتباه یا حذف شده باز کنید.
|
||||
|
||||
برای مسئولیتهای ماژول و نحوه اضافه کردن زبان جدید [ARCHITECTURE.md](../../ARCHITECTURE.md) را ببینید.
|
||||
|
||||
</div>
|
||||
|
||||
</details>
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**Taito tekoälykoodiavustajille.** Kirjoita `/graphify` Claude Codessa, Codexissa, OpenCodessa, Cursorissa, Gemini CLI:ssä, GitHub Copilot CLI:ssä, VS Code Copilot Chatissa, Aiderissa, OpenClawissa, Factory Droidissa, Traessa, Hermeksessä, Kirossa tai Google Antigravityssa — se lukee tiedostosi, rakentaa tietograafin ja palauttaa sinulle rakenteen, jota et tiennyt olevan. Ymmärrä koodikanta nopeammin. Löydä arkkitehtuuripäätösten taustalla oleva "miksi".
|
||||
|
||||
Täysin multimodaalinen. Lisää koodia, PDF:iä, markdownia, kuvakaappauksia, kaavioita, liitutaulun valokuvia, muilla kielillä olevia kuvia tai video- ja äänitiedostoja — graphify poimii käsitteitä ja suhteita kaikesta ja yhdistää ne yhdeksi graafaksi. Videot litteroidaan paikallisesti Whisperillä. Tukee 25 ohjelmointikieltä tree-sitter AST:n kautta.
|
||||
|
||||
> Andrej Karpathy ylläpitää `/raw`-kansiota, johon hän tallentaa papereita, tviittejä, kuvakaappauksia ja muistiinpanoja. graphify on vastaus tähän ongelmaan — **71,5x** vähemmän tokeneita kyselyä kohden verrattuna raakatiedostojen lukemiseen, pysyvä istuntojen välillä.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html interaktiivinen graafi — avaa missä tahansa selaimessa
|
||||
├── GRAPH_REPORT.md jumalsolmut, yllättävät yhteydet, ehdotetut kysymykset
|
||||
├── graph.json pysyvä graafi — kyselytavissa viikkojen kuluttua
|
||||
└── cache/ SHA256-välimuisti — toistuvat ajot käsittelevät vain muuttuneet tiedostot
|
||||
```
|
||||
|
||||
## Miten se toimii
|
||||
|
||||
graphify toimii kolmessa läpiajossa. Ensin deterministinen AST-läpiajo poimii rakenteen kooditiedostoista ilman LLM:ää. Sitten video- ja äänitiedostot litteroidaan paikallisesti faster-whisperillä. Lopuksi Clauden ala-agentit suoritetaan rinnakkain asiakirjoissa, papereissa, kuvissa ja litteroinneissa. Tulokset yhdistetään NetworkX-graafiin, klusteroidaan Leidenillä ja viedään interaktiivisena HTML:nä, kyselytavissa olevana JSON:na ja tarkastusraporttina.
|
||||
|
||||
Jokainen suhde on merkitty `EXTRACTED`, `INFERRED` (luottamuspisteineen) tai `AMBIGUOUS`.
|
||||
|
||||
## Asennus
|
||||
|
||||
**Vaatimukset:** Python 3.10+ ja jokin seuraavista: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) ja muut.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# tai pipx:llä
|
||||
pipx install graphifyy && graphify install
|
||||
# tai pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Virallinen paketti:** PyPI-paketti on nimeltään `graphifyy`. Ainoa virallinen repositorio on [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Käyttö
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "mikä yhdistää Attentionin optimizeriin?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Mitä saat
|
||||
|
||||
**Jumalsolmut** — korkeimman asteen käsitteet · **Yllättävät yhteydet** — pisteiden mukaan järjestetty · **Ehdotetut kysymykset** · **"Miksi"** — docstringit ja suunnitteluperusteet solmuina · **Token-vertailu** — **71,5x** vähemmän tokeneita sekakorpuksessa.
|
||||
|
||||
## Yksityisyys
|
||||
|
||||
Kooditiedostot käsitellään paikallisesti tree-sitter AST:n kautta. Videot litteroidaan paikallisesti faster-whisperillä. Ei telemetriaa.
|
||||
|
||||
## Rakennettu graphifyn päälle — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) on graphifyn päälle rakennettu yritystaso. **Ilmainen kokeilujakso tulossa pian.** [Liity odotuslistalle →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a> | 🇵🇭 <a href="README.fil-PH.md">Filipino</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**Kasanayan para sa mga AI coding assistant.** I-type ang `/graphify` sa Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, o Google Antigravity — binabasa nito ang iyong mga file, gumagawa ng knowledge graph, at ibinabalik sa iyo ang mga istrukturang hindi mo alam na nandoon pala. Maunawaan ang codebase nang mas mabilis. Tuklasin ang "bakit" sa likod ng mga desisyon sa arkitektura.
|
||||
|
||||
Ganap na multimodal. Magdagdag ng code, PDF, markdown, mga screenshot, diagram, larawan ng whiteboard, mga imahe sa ibang wika, o mga video at audio file — kine-extract ng graphify ang mga konsepto at relasyon mula sa lahat ng ito at pinag-uugnay ang mga ito sa iisang graph. Ang mga video ay tina-transcribe nang lokal gamit ang Whisper. Sumusuporta ng 25 na programming language sa pamamagitan ng tree-sitter AST.
|
||||
|
||||
> Si Andrej Karpathy ay nagpapanatili ng `/raw` folder kung saan nilalagay niya ang mga papel, tweet, screenshot, at tala. Ang graphify ang sagot sa problemang iyon — **71.5x** na mas kaunting token bawat query kumpara sa pagbasa ng mga raw file, at persistent sa pagitan ng mga session.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html interactive na graph — buksan sa kahit anong browser
|
||||
├── GRAPH_REPORT.md mga god node, nakakagulat na koneksyon, mga iminumungkahing tanong
|
||||
├── graph.json persistent na graph — maaaring i-query kahit pagkalipas ng mga linggo
|
||||
└── cache/ SHA256 cache — ang mga pag-uulit ay nagpo-proseso lang ng mga nabagong file
|
||||
```
|
||||
|
||||
## Paano Gumagana
|
||||
|
||||
Gumagana ang graphify sa tatlong pass. Una, isang deterministikong AST pass ang nag-e-extract ng istruktura mula sa mga code file nang walang LLM. Pagkatapos, ang mga video at audio file ay tina-transcribe nang lokal gamit ang faster-whisper. Panghuli, mga Claude sub-agent ang tumatakbo nang magkakasabay sa mga dokumento, papel, imahe, at transkripsyon. Ang mga resulta ay pinagsasama sa isang NetworkX graph, naka-cluster gamit ang Leiden, at ine-export bilang interactive na HTML, queryable na JSON, at audit report.
|
||||
|
||||
Ang bawat relasyon ay may label na `EXTRACTED`, `INFERRED` (may confidence score), o `AMBIGUOUS`.
|
||||
|
||||
## Pag-install
|
||||
|
||||
**Mga Kinakailangan:** Python 3.10+ at isa sa mga sumusunod: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) at iba pa.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# o gamit ang pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# o pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Opisyal na package:** Ang PyPI package ay pinangalanang `graphifyy`. Ang tanging opisyal na repository ay [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Paggamit
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "ano ang nagkokonekta sa Attention at sa optimizer?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Ano ang Makukuha Mo
|
||||
|
||||
**Mga god node** — mga konsepto na may pinakamataas na degree · **Mga nakakagulat na koneksyon** — naka-rank ayon sa score · **Mga iminumungkahing tanong** · **"Bakit"** — mga docstring at disenyo na rason ay ine-extract bilang mga node · **Token benchmark** — **71.5x** na mas kaunting token sa mixed corpus.
|
||||
|
||||
## Privacy
|
||||
|
||||
Ang mga code file ay prinoseso nang lokal sa pamamagitan ng tree-sitter AST. Ang mga video ay tina-transcribe nang lokal gamit ang faster-whisper. Walang telemetry.
|
||||
|
||||
## Binuo sa ibabaw ng graphify — Penpax
|
||||
|
||||
Ang [**Penpax**](https://graphifylabs.ai) ay ang enterprise layer sa ibabaw ng graphify. **Malapit nang magkaroon ng libreng trial.** [Sumali sa waitlist →](https://graphifylabs.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,170 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></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>
|
||||
</p>
|
||||
|
||||
**Une compétence pour assistant de code IA.** Tapez `/graphify` dans Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro ou Google Antigravity — il lit vos fichiers, construit un graphe de connaissances et vous révèle une structure que vous ne voyiez pas auparavant. Comprenez une base de code plus rapidement. Trouvez le « pourquoi » derrière les décisions architecturales.
|
||||
|
||||
Entièrement multimodal. Déposez du code, des PDFs, du markdown, des captures d'écran, des diagrammes, des photos de tableau blanc, des images dans d'autres langues, ou des fichiers vidéo et audio — graphify extrait les concepts et les relations de tout cela et les connecte en un seul graphe. Les vidéos sont transcrites localement avec Whisper grâce à un prompt adapté au domaine. 25 langages de programmation supportés via tree-sitter AST (Python, JS, TS, Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Lua, Zig, PowerShell, Elixir, Objective-C, Julia, Verilog, SystemVerilog, Vue, Svelte, Dart).
|
||||
|
||||
> Andrej Karpathy maintient un dossier `/raw` où il dépose des articles, tweets, captures d'écran et notes. graphify est la réponse à ce problème — 71,5 fois moins de tokens par requête versus la lecture des fichiers bruts, persistant entre les sessions, honnête sur ce qui a été trouvé versus déduit.
|
||||
|
||||
```
|
||||
/graphify . # fonctionne sur n'importe quel dossier — code, notes, articles, tout
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html graphe interactif — ouvrir dans un navigateur, cliquer, rechercher, filtrer
|
||||
├── GRAPH_REPORT.md nœuds dieu, connexions surprenantes, questions suggérées
|
||||
├── graph.json graphe persistant — interrogeable des semaines plus tard sans relire
|
||||
└── cache/ cache SHA256 — les réexécutions ne traitent que les fichiers modifiés
|
||||
```
|
||||
|
||||
Ajoutez un fichier `.graphifyignore` pour exclure des dossiers :
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
vendor/
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
```
|
||||
|
||||
Même syntaxe que `.gitignore`. Un seul `.graphifyignore` à la racine du dépôt suffit.
|
||||
|
||||
## Comment ça fonctionne
|
||||
|
||||
graphify s'exécute en trois passes. D'abord, un passage AST déterministe extrait la structure des fichiers de code (classes, fonctions, imports, graphes d'appel, docstrings, commentaires de justification) sans LLM. Ensuite, les fichiers vidéo et audio sont transcrits localement avec faster-whisper. Enfin, des sous-agents Claude s'exécutent en parallèle sur les docs, articles, images et transcriptions pour extraire concepts, relations et justifications de conception. Les résultats sont fusionnés dans un graphe NetworkX, regroupés avec la détection de communautés Leiden, et exportés en HTML interactif, JSON interrogeable et un rapport d'audit en langage naturel.
|
||||
|
||||
**Le clustering est basé sur la topologie du graphe — pas d'embeddings.** Leiden trouve les communautés par densité d'arêtes. Les arêtes de similarité sémantique extraites par Claude (`semantically_similar_to`, marquées INFERRED) sont déjà dans le graphe. La structure du graphe est le signal de similarité — pas d'étape d'embedding séparée ni de base de données vectorielle nécessaire.
|
||||
|
||||
Chaque relation est étiquetée `EXTRACTED` (trouvée directement dans la source), `INFERRED` (déduction raisonnable avec un score de confiance) ou `AMBIGUOUS` (marquée pour révision).
|
||||
|
||||
## Installation
|
||||
|
||||
**Prérequis :** Python 3.10+ et l'un de : [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com), [Gemini CLI](https://github.com/google-gemini/gemini-cli), [GitHub Copilot CLI](https://docs.github.com/en/copilot/how-tos/copilot-cli), [VS Code Copilot Chat](https://code.visualstudio.com/docs/copilot/overview), [Aider](https://aider.chat), [OpenClaw](https://openclaw.ai), [Factory Droid](https://factory.ai), [Trae](https://trae.ai), [Kiro](https://kiro.dev), Hermes ou [Google Antigravity](https://antigravity.google)
|
||||
|
||||
```bash
|
||||
# Recommandé — fonctionne sur Mac et Linux sans configuration du PATH
|
||||
uv tool install graphifyy && graphify install
|
||||
# ou avec pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# ou pip simple
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Package officiel :** Le package PyPI s'appelle `graphifyy` (installer avec `pip install graphifyy`). Les autres packages nommés `graphify*` sur PyPI ne sont pas affiliés à ce projet. Le seul dépôt officiel est [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
### Support des plateformes
|
||||
|
||||
| Plateforme | Commande d'installation |
|
||||
|------------|------------------------|
|
||||
| Claude Code (Linux/Mac) | `graphify install` |
|
||||
| Claude Code (Windows) | `graphify install` (détection automatique) ou `graphify install --platform windows` |
|
||||
| Codex | `graphify install --platform codex` |
|
||||
| OpenCode | `graphify install --platform opencode` |
|
||||
| GitHub Copilot CLI | `graphify install --platform copilot` |
|
||||
| VS Code Copilot Chat | `graphify vscode install` |
|
||||
| Aider | `graphify install --platform aider` |
|
||||
| OpenClaw | `graphify install --platform claw` |
|
||||
| Factory Droid | `graphify install --platform droid` |
|
||||
| Trae | `graphify install --platform trae` |
|
||||
| Trae CN | `graphify install --platform trae-cn` |
|
||||
| Gemini CLI | `graphify install --platform gemini` |
|
||||
| Hermes | `graphify install --platform hermes` |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
Ensuite, ouvrez votre assistant de code IA et tapez :
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
Note : Codex utilise `$` au lieu de `/` pour les compétences, tapez donc `$graphify .`.
|
||||
|
||||
### Toujours utiliser le graphe (recommandé)
|
||||
|
||||
Après avoir construit un graphe, exécutez ceci une fois dans votre projet :
|
||||
|
||||
| Plateforme | Commande |
|
||||
|------------|----------|
|
||||
| Claude Code | `graphify claude install` |
|
||||
| Codex | `graphify codex install` |
|
||||
| OpenCode | `graphify opencode install` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Gemini CLI | `graphify gemini install` |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
## Utilisation
|
||||
|
||||
```
|
||||
/graphify # répertoire courant
|
||||
/graphify ./raw # dossier spécifique
|
||||
/graphify ./raw --mode deep # extraction d'arêtes INFERRED plus agressive
|
||||
/graphify ./raw --update # ne réextraire que les fichiers modifiés
|
||||
/graphify ./raw --directed # graphe dirigé
|
||||
/graphify ./raw --cluster-only # relancer le clustering sur le graphe existant
|
||||
/graphify ./raw --no-viz # pas d'HTML, juste rapport + JSON
|
||||
/graphify ./raw --obsidian # générer un vault Obsidian (opt-in)
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # récupérer un article
|
||||
/graphify add <video-url> # télécharger l'audio, transcrire, ajouter
|
||||
/graphify query "qu'est-ce qui connecte Attention à l'optimiseur ?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
graphify hook install # installer les hooks Git
|
||||
graphify update ./src # réextraire les fichiers de code, sans LLM
|
||||
graphify watch ./src # mise à jour automatique du graphe
|
||||
```
|
||||
|
||||
## Ce que vous obtenez
|
||||
|
||||
**Nœuds dieu** — concepts avec le plus haut degré (tout passe par eux)
|
||||
|
||||
**Connexions surprenantes** — classées par score composite. Les arêtes code-article sont mieux notées. Chaque résultat inclut un pourquoi en langage naturel.
|
||||
|
||||
**Questions suggérées** — 4-5 questions que le graphe est particulièrement bien placé pour répondre
|
||||
|
||||
**Le « pourquoi »** — docstrings, commentaires inline (`# NOTE:`, `# IMPORTANT:`, `# HACK:`, `# WHY:`), et justifications de conception extraits comme nœuds `rationale_for`.
|
||||
|
||||
**Scores de confiance** — chaque arête INFERRED a un `confidence_score` (0,0-1,0).
|
||||
|
||||
**Benchmark de tokens** — affiché automatiquement après chaque exécution. Sur un corpus mixte : **71,5 fois** moins de tokens par requête vs fichiers bruts.
|
||||
|
||||
**Synchronisation automatique** (`--watch`) — met à jour le graphe automatiquement lors des modifications de code.
|
||||
|
||||
**Hooks Git** (`graphify hook install`) — installe des hooks post-commit et post-checkout.
|
||||
|
||||
## Confidentialité
|
||||
|
||||
graphify envoie le contenu des fichiers à l'API du modèle de votre assistant IA pour l'extraction sémantique des docs, articles et images. Les fichiers de code sont traités localement via tree-sitter AST. Les fichiers vidéo et audio sont transcrits localement avec faster-whisper. Aucune télémétrie, aucun suivi d'utilisation.
|
||||
|
||||
## Stack technique
|
||||
|
||||
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Extraction sémantique via Claude, GPT-4 ou le modèle de votre plateforme. Transcription vidéo via faster-whisper + yt-dlp (optionnel).
|
||||
|
||||
## Construit sur graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) est la couche enterprise au-dessus de graphify. Là où graphify transforme un dossier de fichiers en graphe de connaissances, Penpax applique le même graphe à toute votre vie professionnelle — en continu.
|
||||
|
||||
**Essai gratuit bientôt disponible.** [Rejoindre la liste d'attente →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
## Historique des étoiles
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,143 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></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>
|
||||
</p>
|
||||
|
||||
**एक AI कोडिंग असिस्टेंट स्किल।** Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro या Google Antigravity में `/graphify` टाइप करें — यह आपकी फ़ाइलें पढ़ता है, एक नॉलेज ग्राफ बनाता है, और आपको वह संरचना वापस देता है जो आप नहीं जानते थे कि मौजूद है। कोडबेस को तेज़ी से समझें। आर्किटेक्चरल निर्णयों के पीछे का "क्यों" खोजें।
|
||||
|
||||
पूरी तरह मल्टीमोडल। कोड, PDFs, मार्कडाउन, स्क्रीनशॉट, डायग्राम, व्हाइटबोर्ड फोटो, अन्य भाषाओं में छवियां, या वीडियो और ऑडियो फ़ाइलें डालें — graphify इन सभी से अवधारणाएं और संबंध निकालता है और उन्हें एक ग्राफ में जोड़ता है। वीडियो को Whisper से स्थानीय रूप से ट्रांसक्राइब किया जाता है। 25 प्रोग्रामिंग भाषाएं tree-sitter AST के माध्यम से समर्थित हैं (Python, JS, TS, Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Lua, Zig, PowerShell, Elixir, Objective-C, Julia, Verilog, SystemVerilog, Vue, Svelte, Dart)।
|
||||
|
||||
> Andrej Karpathy एक `/raw` फोल्डर रखते हैं जहां वह papers, tweets, स्क्रीनशॉट और नोट्स डालते हैं। graphify उस समस्या का जवाब है — रॉ फ़ाइलें पढ़ने की तुलना में प्रति क्वेरी **71.5x** कम tokens, सत्रों में स्थायी, ईमानदार कि क्या पाया गया बनाम अनुमान लगाया गया।
|
||||
|
||||
```
|
||||
/graphify . # किसी भी फोल्डर पर काम करता है — कोडबेस, नोट्स, papers, सब कुछ
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html इंटरेक्टिव ग्राफ — किसी भी ब्राउज़र में खोलें, नोड्स क्लिक करें, खोजें
|
||||
├── GRAPH_REPORT.md गॉड नोड्स, आश्चर्यजनक कनेक्शन, सुझाए गए प्रश्न
|
||||
├── graph.json स्थायी ग्राफ — हफ्तों बाद भी क्वेरी करें
|
||||
└── cache/ SHA256 कैश — पुनः चलाने पर केवल बदली हुई फ़ाइलें प्रोसेस होती हैं
|
||||
```
|
||||
|
||||
अनचाहे फोल्डर को बाहर करने के लिए `.graphifyignore` फ़ाइल जोड़ें:
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
vendor/
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
```
|
||||
|
||||
`.gitignore` जैसी ही सिंटेक्स।
|
||||
|
||||
## यह कैसे काम करता है
|
||||
|
||||
graphify तीन चरणों में चलता है। पहले, एक निर्धारक AST पास कोड फ़ाइलों से संरचना निकालता है — बिना किसी LLM के। दूसरे, वीडियो और ऑडियो फ़ाइलों को faster-whisper से स्थानीय रूप से ट्रांसक्राइब किया जाता है। तीसरे, Claude सबएजेंट दस्तावेज़ों, papers, छवियों और ट्रांसक्रिप्ट पर समानांतर में चलते हैं। परिणामों को NetworkX ग्राफ में मर्ज किया जाता है, Leiden कम्युनिटी डिटेक्शन से क्लस्टर किया जाता है, और इंटरेक्टिव HTML, क्वेरी करने योग्य JSON और एक ऑडिट रिपोर्ट के रूप में निर्यात किया जाता है।
|
||||
|
||||
**क्लस्टरिंग ग्राफ-टोपोलॉजी आधारित है — कोई embeddings नहीं।** Claude द्वारा निकाले गए सिमेंटिक समानता किनारे पहले से ग्राफ में हैं, इसलिए वे कम्युनिटी डिटेक्शन को सीधे प्रभावित करते हैं।
|
||||
|
||||
प्रत्येक संबंध `EXTRACTED` (स्रोत में सीधे पाया गया), `INFERRED` (उचित अनुमान, कॉन्फिडेंस स्कोर के साथ) या `AMBIGUOUS` (समीक्षा के लिए चिह्नित) के रूप में टैग किया जाता है।
|
||||
|
||||
## इंस्टॉलेशन
|
||||
|
||||
**आवश्यकताएं:** Python 3.10+ और निम्न में से एक: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com), [Gemini CLI](https://github.com/google-gemini/gemini-cli), [GitHub Copilot CLI](https://docs.github.com/en/copilot/how-tos/copilot-cli), [VS Code Copilot Chat](https://code.visualstudio.com/docs/copilot/overview), [Aider](https://aider.chat), [OpenClaw](https://openclaw.ai), [Factory Droid](https://factory.ai), [Trae](https://trae.ai), [Kiro](https://kiro.dev), Hermes या [Google Antigravity](https://antigravity.google)
|
||||
|
||||
```bash
|
||||
# अनुशंसित — Mac और Linux पर PATH सेटअप के बिना काम करता है
|
||||
uv tool install graphifyy && graphify install
|
||||
# या pipx के साथ
|
||||
pipx install graphifyy && graphify install
|
||||
# या सामान्य pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **आधिकारिक पैकेज:** PyPI पैकेज का नाम `graphifyy` है (`pip install graphifyy` से इंस्टॉल करें)। PyPI पर `graphify*` नाम वाले अन्य पैकेज इस प्रोजेक्ट से संबद्ध नहीं हैं। एकमात्र आधिकारिक रिपॉजिटरी [safishamsi/graphify](https://github.com/safishamsi/graphify) है।
|
||||
|
||||
### प्लेटफॉर्म समर्थन
|
||||
|
||||
| प्लेटफॉर्म | इंस्टॉल कमांड |
|
||||
|------------|---------------|
|
||||
| Claude Code (Linux/Mac) | `graphify install` |
|
||||
| Claude Code (Windows) | `graphify install` (स्वतः-पहचान) या `graphify install --platform windows` |
|
||||
| Codex | `graphify install --platform codex` |
|
||||
| OpenCode | `graphify install --platform opencode` |
|
||||
| GitHub Copilot CLI | `graphify install --platform copilot` |
|
||||
| VS Code Copilot Chat | `graphify vscode install` |
|
||||
| Aider | `graphify install --platform aider` |
|
||||
| OpenClaw | `graphify install --platform claw` |
|
||||
| Factory Droid | `graphify install --platform droid` |
|
||||
| Trae | `graphify install --platform trae` |
|
||||
| Gemini CLI | `graphify install --platform gemini` |
|
||||
| Hermes | `graphify install --platform hermes` |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
फिर अपना AI कोडिंग असिस्टेंट खोलें और टाइप करें:
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
## उपयोग
|
||||
|
||||
```
|
||||
/graphify # वर्तमान डायरेक्टरी
|
||||
/graphify ./raw # विशिष्ट फोल्डर
|
||||
/graphify ./raw --update # केवल बदली हुई फ़ाइलें फिर से निकालें
|
||||
/graphify ./raw --directed # निर्देशित ग्राफ
|
||||
/graphify ./raw --no-viz # केवल रिपोर्ट + JSON
|
||||
/graphify ./raw --obsidian # Obsidian vault बनाएं
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # paper प्राप्त करें
|
||||
/graphify add <video-url> # वीडियो ट्रांसक्राइब करें
|
||||
/graphify query "attention और optimizer को क्या जोड़ता है?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
graphify hook install # Git hooks इंस्टॉल करें
|
||||
graphify update ./src # कोड फ़ाइलें पुनः निकालें, LLM की जरूरत नहीं
|
||||
graphify watch ./src # स्वचालित ग्राफ अपडेट
|
||||
```
|
||||
|
||||
## आपको क्या मिलता है
|
||||
|
||||
**गॉड नोड्स** — सबसे अधिक डिग्री वाली अवधारणाएं (जिनसे सब कुछ गुजरता है)
|
||||
|
||||
**आश्चर्यजनक कनेक्शन** — कम्पोजिट स्कोर द्वारा रैंक किए गए। कोड-पेपर किनारे उच्च रैंक पाते हैं।
|
||||
|
||||
**सुझाए गए प्रश्न** — 4-5 प्रश्न जिन्हें ग्राफ विशेष रूप से अच्छी तरह उत्तर दे सकता है
|
||||
|
||||
**"क्यों"** — docstrings, inline comments, और design rationale को `rationale_for` नोड्स के रूप में निकाला जाता है।
|
||||
|
||||
**कॉन्फिडेंस स्कोर** — प्रत्येक INFERRED किनारे का `confidence_score` (0.0-1.0) होता है।
|
||||
|
||||
**टोकन बेंचमार्क** — प्रत्येक रन के बाद स्वचालित रूप से प्रिंट होता है। मिश्रित corpus पर: रॉ फ़ाइलों की तुलना में **71.5x** कम tokens।
|
||||
|
||||
## गोपनीयता
|
||||
|
||||
graphify दस्तावेज़ों, papers और छवियों के सिमेंटिक निष्कर्षण के लिए आपके AI असिस्टेंट की मॉडल API को फ़ाइल सामग्री भेजता है। कोड फ़ाइलें tree-sitter AST के माध्यम से स्थानीय रूप से प्रोसेस होती हैं। वीडियो और ऑडियो फ़ाइलें faster-whisper से स्थानीय रूप से ट्रांसक्राइब होती हैं। कोई टेलीमेट्री नहीं, कोई ट्रैकिंग नहीं।
|
||||
|
||||
## graphify पर बनाया — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) graphify के ऊपर एंटरप्राइज़ लेयर है। जहां graphify फ़ाइलों के एक फोल्डर को नॉलेज ग्राफ में बदलता है, Penpax वही ग्राफ आपके पूरे कार्य जीवन पर लागू करता है — निरंतर।
|
||||
|
||||
**फ्री ट्रायल जल्द लॉन्च होगा।** [वेटलिस्ट में शामिल हों →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
## Star इतिहास
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**Képesség AI kódolási asszisztensekhez.** Írja be a `/graphify` parancsot a Claude Code-ban, Codexben, OpenCode-ban, Cursorban, Gemini CLI-ben, GitHub Copilot CLI-ben, VS Code Copilot Chatben, Aiderben, OpenClawban, Factory Droidban, Traeben, Hermesben, Kiroban vagy a Google Antigravityben — beolvassa a fájljait, tudásgráfot épít, és visszaadja azt a struktúrát, amelyről nem tudta, hogy létezik. Értse meg gyorsabban a kódbázist. Találja meg az architektúrális döntések mögött álló „miértet".
|
||||
|
||||
Teljesen multimodális. Adjon hozzá kódot, PDF-eket, markdownt, képernyőképeket, diagramokat, táblafotókat, más nyelvű képeket vagy video- és hangfájlokat — a graphify mindenből kinyeri a fogalmakat és kapcsolatokat, és egyetlen gráfba köti össze őket. A videókat a Whisper segítségével helyben írja át. 25 programozási nyelvet támogat tree-sitter AST-n keresztül.
|
||||
|
||||
> Andrej Karpathy fenntart egy `/raw` mappát, ahova cikkeket, tweeteket, képernyőképeket és jegyzeteket helyez el. A graphify erre a problémára adott válasz — **71,5x** kevesebb token lekérdezésenként a nyers fájlok olvasásához képest, munkamenetek között is megmarad.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html interaktív gráf — nyissa meg bármely böngészőben
|
||||
├── GRAPH_REPORT.md isten-csúcspontok, meglepő kapcsolatok, javasolt kérdések
|
||||
├── graph.json állandó gráf — hetekkel később is lekérdezhető
|
||||
└── cache/ SHA256-gyorsítótár — ismételt futtatások csak a módosított fájlokat dolgozzák fel
|
||||
```
|
||||
|
||||
## Hogyan működik
|
||||
|
||||
A graphify három menetben dolgozik. Először egy determinisztikus AST-menet kinyeri a struktúrát a kódfájlokból LLM nélkül. Ezután a video- és hangfájlokat a faster-whisper segítségével helyben írja át. Végül a Claude alügynökök párhuzamosan futnak dokumentumokon, cikkeken, képeken és átiratokban. Az eredményeket egy NetworkX-gráfba olvasztja össze, Leiden-nel klaszterezik, és interaktív HTML-ként, lekérdezhető JSON-ként és auditjelentésként exportálja.
|
||||
|
||||
Minden kapcsolat `EXTRACTED`, `INFERRED` (megbízhatósági pontszámmal) vagy `AMBIGUOUS` feliratot kap.
|
||||
|
||||
## Telepítés
|
||||
|
||||
**Követelmények:** Python 3.10+ és az alábbiak egyike: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) és mások.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# vagy pipx-szel
|
||||
pipx install graphifyy && graphify install
|
||||
# vagy pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Hivatalos csomag:** A PyPI-csomag neve `graphifyy`. Az egyetlen hivatalos tároló a [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Használat
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "mi köti össze az Attentiont az optimalizálóval?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Mit kap
|
||||
|
||||
**Isten-csúcspontok** — a legmagasabb fokú fogalmak · **Meglepő kapcsolatok** — pontszám szerint rendezve · **Javasolt kérdések** · **A „miért"** — docstringek és tervezési indoklások csúcspontként kinyerve · **Token-benchmark** — **71,5x** kevesebb token vegyes korpuszon.
|
||||
|
||||
## Adatvédelem
|
||||
|
||||
A kódfájlokat helyben dolgozza fel tree-sitter AST-n keresztül. A videókat helyben írja át a faster-whisper. Nincs telemetria.
|
||||
|
||||
## A graphify-ra épülve — Penpax
|
||||
|
||||
A [**Penpax**](https://safishamsi.github.io/penpax.ai) a graphify feletti vállalati réteg. **Ingyenes próbaverzió hamarosan.** [Csatlakozzon a várólistához →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**Keterampilan untuk asisten kode AI.** Ketik `/graphify` di Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, atau Google Antigravity — membaca file Anda, membangun graf pengetahuan, dan mengembalikan struktur yang tidak Anda ketahui ada. Pahami codebase lebih cepat. Temukan "mengapa" di balik keputusan arsitektur.
|
||||
|
||||
Sepenuhnya multimodal. Tambahkan kode, PDF, markdown, tangkapan layar, diagram, foto papan tulis, gambar dalam bahasa lain, atau file video dan audio — graphify mengekstrak konsep dan hubungan dari semuanya dan menghubungkannya dalam satu graf. Video ditranskrip secara lokal dengan Whisper. Mendukung 25 bahasa pemrograman melalui tree-sitter AST.
|
||||
|
||||
> Andrej Karpathy memelihara folder `/raw` tempat ia menyimpan makalah, tweet, tangkapan layar, dan catatan. graphify adalah jawaban untuk masalah itu — **71,5x** lebih sedikit token per kueri dibandingkan membaca file mentah, persisten di antara sesi.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html graf interaktif — buka di browser mana saja
|
||||
├── GRAPH_REPORT.md node dewa, koneksi mengejutkan, pertanyaan yang disarankan
|
||||
├── graph.json graf persisten — dapat dikueri berminggu-minggu kemudian
|
||||
└── cache/ cache SHA256 — pengulangan hanya memproses file yang berubah
|
||||
```
|
||||
|
||||
## Cara Kerja
|
||||
|
||||
graphify bekerja dalam tiga tahap. Pertama, tahap AST deterministik mengekstrak struktur dari file kode tanpa LLM. Kemudian file video dan audio ditranskrip secara lokal dengan faster-whisper. Terakhir, sub-agen Claude berjalan secara paralel pada dokumen, makalah, gambar, dan transkripsi. Hasilnya digabungkan ke dalam graf NetworkX, dikelompokkan dengan Leiden, dan diekspor sebagai HTML interaktif, JSON yang dapat dikueri, dan laporan audit.
|
||||
|
||||
Setiap hubungan diberi label `EXTRACTED`, `INFERRED` (dengan skor kepercayaan), atau `AMBIGUOUS`.
|
||||
|
||||
## Instalasi
|
||||
|
||||
**Persyaratan:** Python 3.10+ dan salah satu dari: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) dan lainnya.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# atau dengan pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# atau pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Paket resmi:** Paket PyPI bernama `graphifyy`. Satu-satunya repositori resmi adalah [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Penggunaan
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "apa yang menghubungkan Attention dengan optimizer?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Apa yang Anda Dapatkan
|
||||
|
||||
**Node dewa** — konsep dengan derajat tertinggi · **Koneksi mengejutkan** — diurutkan berdasarkan skor · **Pertanyaan yang disarankan** · **"Mengapa"** — docstring dan alasan desain diekstrak sebagai node · **Benchmark token** — **71,5x** lebih sedikit token pada corpus campuran.
|
||||
|
||||
## Privasi
|
||||
|
||||
File kode diproses secara lokal melalui tree-sitter AST. Video ditranskrip secara lokal dengan faster-whisper. Tidak ada telemetri.
|
||||
|
||||
## Dibangun di atas graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) adalah lapisan enterprise di atas graphify. **Uji coba gratis segera hadir.** [Bergabunglah dengan daftar tunggu →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,78 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**Una skill per assistenti di codice IA.** Scrivi `/graphify` in Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro o Google Antigravity — legge i tuoi file, costruisce un grafo della conoscenza e ti restituisce struttura che non sapevi esistesse. Comprendi una codebase più velocemente. Trova il "perché" dietro le decisioni architetturali.
|
||||
|
||||
Completamente multimodale. Aggiungi codice, PDF, markdown, screenshot, diagrammi, foto di lavagne, immagini in altre lingue, o file video e audio — graphify estrae concetti e relazioni da tutto e li connette in un unico grafo. I video vengono trascritti localmente con Whisper. Supporta 25 linguaggi di programmazione via tree-sitter AST.
|
||||
|
||||
> Andrej Karpathy mantiene una cartella `/raw` dove deposita paper, tweet, screenshot e note. graphify è la risposta a quel problema — **71,5x** meno token per query rispetto alla lettura dei file grezzi, persistente tra le sessioni.
|
||||
|
||||
```
|
||||
/graphify . # funziona con qualsiasi cartella
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html grafo interattivo — apri in qualsiasi browser
|
||||
├── GRAPH_REPORT.md nodi dio, connessioni sorprendenti, domande suggerite
|
||||
├── graph.json grafo persistente — interrogabile settimane dopo
|
||||
└── cache/ cache SHA256 — le riesecuzioni elaborano solo i file modificati
|
||||
```
|
||||
|
||||
## Come funziona
|
||||
|
||||
graphify esegue in tre passaggi. Prima, un passaggio AST deterministico estrae la struttura dai file di codice senza LLM. Poi, i file video e audio vengono trascritti localmente con faster-whisper. Infine, i subagenti Claude eseguono in parallelo su documenti, paper, immagini e trascrizioni. I risultati vengono uniti in un grafo NetworkX, raggruppati con Leiden e esportati come HTML interattivo, JSON interrogabile e report di audit.
|
||||
|
||||
Ogni relazione è etichettata `EXTRACTED`, `INFERRED` (con punteggio di confidenza) o `AMBIGUOUS`.
|
||||
|
||||
## Installazione
|
||||
|
||||
**Requisiti:** Python 3.10+ e uno tra: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com), [Gemini CLI](https://github.com/google-gemini/gemini-cli), [Aider](https://aider.chat) e altri.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# oppure con pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# oppure pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Pacchetto ufficiale:** Il pacchetto PyPI si chiama `graphifyy`. L'unico repository ufficiale è [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Utilizzo
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update # solo file modificati
|
||||
/graphify ./raw --mode deep
|
||||
/graphify query "cosa connette Attention all'ottimizzatore?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Cosa ottieni
|
||||
|
||||
**Nodi dio** — concetti con il grado più alto · **Connessioni sorprendenti** — classificate per punteggio · **Domande suggerite** — 4-5 domande che il grafo è in grado di rispondere in modo unico · **Il "perché"** — docstring e rationale di design estratti come nodi · **Benchmark token** — **71,5x** meno token su corpus misto.
|
||||
|
||||
## Privacy
|
||||
|
||||
I file di codice vengono elaborati localmente via tree-sitter AST. I video vengono trascritti localmente con faster-whisper. Nessuna telemetria.
|
||||
|
||||
## Costruito su graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) è il livello enterprise su graphify. **Prova gratuita in arrivo.** [Unisciti alla lista d'attesa →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,238 @@
|
||||
# graphify
|
||||
|
||||
🇺🇸 [English](../../README.md) | 🇨🇳 [简体中文](README.zh-CN.md) | 🇯🇵 [日本語](README.ja-JP.md) | 🇰🇷 [한국어](README.ko-KR.md) | 🇩🇪 [Deutsch](README.de-DE.md) | 🇫🇷 [Français](README.fr-FR.md) | 🇪🇸 [Español](README.es-ES.md) | 🇮🇳 [हिन्दी](README.hi-IN.md) | 🇧🇷 [Português](README.pt-BR.md) | 🇷🇺 [Русский](README.ru-RU.md) | 🇸🇦 [العربية](README.ar-SA.md) | 🇮🇹 [Italiano](README.it-IT.md) | 🇵🇱 [Polski](README.pl-PL.md) | 🇳🇱 [Nederlands](README.nl-NL.md) | 🇹🇷 [Türkçe](README.tr-TR.md) | 🇺🇦 [Українська](README.uk-UA.md) | 🇻🇳 [Tiếng Việt](README.vi-VN.md) | 🇮🇩 [Bahasa Indonesia](README.id-ID.md) | 🇸🇪 [Svenska](README.sv-SE.md) | 🇬🇷 [Ελληνικά](README.el-GR.md) | 🇷🇴 [Română](README.ro-RO.md) | 🇨🇿 [Čeština](README.cs-CZ.md) | 🇫🇮 [Suomi](README.fi-FI.md) | 🇩🇰 [Dansk](README.da-DK.md) | 🇳🇴 [Norsk](README.no-NO.md) | 🇭🇺 [Magyar](README.hu-HU.md) | 🇹🇭 [ภาษาไทย](README.th-TH.md) | 🇺🇿 [Oʻzbekcha](README.uz-UZ.md) | 🇹🇼 [繁體中文](README.zh-TW.md)
|
||||
|
||||
[](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
|
||||
[](https://pypi.org/project/graphifyy/)
|
||||
[](https://github.com/sponsors/safishamsi)
|
||||
|
||||
**AIコーディングアシスタント向けのスキル。** Claude Code、Codex、OpenCode、OpenClaw、Factory Droid で `/graphify` と入力するだけで、ファイルを読み込んでナレッジグラフを構築し、あなたが気づいていなかった構造を返します。コードベースをより速く理解し、アーキテクチャ上の意思決定の「なぜ」を見つけ出します。
|
||||
|
||||
完全にマルチモーダル対応。コード、PDF、Markdown、スクリーンショット、図、ホワイトボード写真、他言語の画像まで――graphify は Claude Vision を使ってそれらすべてから概念と関係性を抽出し、1 つのグラフに接続します。tree-sitter AST により 19 言語をサポート(Python、JS、TS、Go、Rust、Java、C、C++、Ruby、C#、Kotlin、Scala、PHP、Swift、Lua、Zig、PowerShell、Elixir、Objective-C)。
|
||||
|
||||
> Andrej Karpathy は論文、ツイート、スクリーンショット、メモを放り込む `/raw` フォルダを持っています。graphify はまさにその問題への答えです――生ファイルを読むのに比べて1クエリあたりのトークン数が 71.5 倍少なく、セッションをまたいで永続化され、見つけたものと推測したものを正直に区別します。
|
||||
|
||||
```
|
||||
/graphify . # どのフォルダでも動作 - コードベース、メモ、論文、なんでも
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html インタラクティブなグラフ - ノードをクリック、検索、コミュニティでフィルタ
|
||||
├── GRAPH_REPORT.md ゴッドノード、意外なつながり、推奨される質問
|
||||
├── graph.json 永続化されたグラフ - 数週間後でも再読み込みなしでクエリ可能
|
||||
└── cache/ SHA256 キャッシュ - 再実行時は変更されたファイルのみ処理
|
||||
```
|
||||
|
||||
グラフに含めたくないフォルダを除外するには `.graphifyignore` ファイルを追加します:
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
vendor/
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
```
|
||||
|
||||
構文は `.gitignore` と同じです。パターンは graphify を実行したフォルダからの相対パスに対してマッチします。
|
||||
|
||||
## 仕組み
|
||||
|
||||
graphify は 2 パスで動作します。まず、決定論的な AST パスがコードファイルから構造(クラス、関数、インポート、コールグラフ、docstring、根拠コメント)を LLM なしで抽出します。次に、Claude サブエージェントがドキュメント、論文、画像に対して並列に実行され、概念、関係性、設計の根拠を抽出します。結果は NetworkX グラフにマージされ、Leiden コミュニティ検出でクラスタリングされ、インタラクティブ HTML、クエリ可能な JSON、平易な言葉の監査レポートとしてエクスポートされます。
|
||||
|
||||
**クラスタリングはグラフトポロジベース――埋め込みは使いません。** Leiden はエッジ密度によってコミュニティを見つけます。Claude が抽出する意味的類似性エッジ(`semantically_similar_to`、INFERRED とマーク)は既にグラフに含まれているため、コミュニティ検出に直接影響します。グラフ構造そのものが類似性シグナルであり――別途の埋め込みステップやベクターデータベースは不要です。
|
||||
|
||||
すべての関係は `EXTRACTED`(ソースから直接見つかった)、`INFERRED`(合理的な推論、信頼度スコア付き)、`AMBIGUOUS`(レビュー対象としてフラグ付け)のいずれかでタグ付けされます。何が見つかったもので何が推測されたものか、常に分かります。
|
||||
|
||||
## インストール
|
||||
|
||||
**必要なもの:** Python 3.10+ および以下のいずれか: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [OpenClaw](https://openclaw.ai), または [Factory Droid](https://factory.ai)
|
||||
|
||||
```bash
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> PyPI パッケージは `graphify` の名前が再取得されるまでの間、一時的に `graphifyy` となっています。CLI とスキルコマンドは依然として `graphify` です。
|
||||
|
||||
### プラットフォームサポート
|
||||
|
||||
| プラットフォーム | インストールコマンド |
|
||||
|----------|----------------|
|
||||
| Claude Code (Linux/Mac) | `graphify install` |
|
||||
| Claude Code (Windows) | `graphify install`(自動検出)または `graphify install --platform windows` |
|
||||
| Codex | `graphify install --platform codex` |
|
||||
| OpenCode | `graphify install --platform opencode` |
|
||||
| OpenClaw | `graphify install --platform claw` |
|
||||
| Factory Droid | `graphify install --platform droid` |
|
||||
|
||||
Codex ユーザーは並列抽出のために `~/.codex/config.toml` の `[features]` の下に `multi_agent = true` も必要です。Factory Droid は並列サブエージェントディスパッチに `Task` ツールを使用します。OpenClaw は逐次抽出を使用します(並列エージェントサポートはこのプラットフォームではまだ初期段階です)。
|
||||
|
||||
次に、AI コーディングアシスタントを開いて入力します:
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
注意:Codex はスキル呼び出しに `/` ではなく `$` を使用するため、代わりに `$graphify .` と入力してください。
|
||||
|
||||
### アシスタントに常にグラフを使わせる(推奨)
|
||||
|
||||
グラフを構築した後、プロジェクトで一度だけ以下を実行します:
|
||||
|
||||
| プラットフォーム | コマンド |
|
||||
|----------|---------|
|
||||
| Claude Code | `graphify claude install` |
|
||||
| Codex | `graphify codex install` |
|
||||
| OpenCode | `graphify opencode install` |
|
||||
| OpenClaw | `graphify claw install` |
|
||||
| Factory Droid | `graphify droid install` |
|
||||
|
||||
**Claude Code** は 2 つのことを行います:Claude にアーキテクチャの質問に答える前に `graphify-out/GRAPH_REPORT.md` を読むように指示する `CLAUDE.md` セクションを書き込み、すべての Glob と Grep 呼び出しの前に発火する **PreToolUse フック**(`settings.json`)をインストールします。ナレッジグラフが存在する場合、Claude は次のメッセージを見ます:_"graphify: Knowledge graph exists. Read GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ ――これにより Claude はすべてのファイルを grep するのではなく、グラフを介してナビゲートします。
|
||||
|
||||
**Codex、OpenCode、OpenClaw、Factory Droid** は同じルールをプロジェクトルートの `AGENTS.md` に書き込みます。これらのプラットフォームは PreToolUse フックをサポートしていないため、AGENTS.md が常時有効のメカニズムとなります。
|
||||
|
||||
アンインストールは対応するアンインストールコマンドで行います(例:`graphify claude uninstall`)。
|
||||
|
||||
**常時有効 vs 明示的トリガー――何が違うのか?**
|
||||
|
||||
常時有効のフックは `GRAPH_REPORT.md` を表面化します――これはゴッドノード、コミュニティ、意外なつながりを 1 ページにまとめた要約です。アシスタントはファイル検索の前にこれを読み、キーワードマッチではなく構造に基づいてナビゲートします。これで日常的な質問のほとんどをカバーできます。
|
||||
|
||||
`/graphify query`、`/graphify path`、`/graphify explain` はさらに深く踏み込みます:生の `graph.json` をホップごとに辿り、ノード間の正確なパスをトレースし、エッジレベルの詳細(関係タイプ、信頼度スコア、ソース位置)を表面化します。一般的なオリエンテーションではなく、特定の質問をグラフから答えさせたいときに使います。
|
||||
|
||||
こう考えてください:常時有効のフックはアシスタントに地図を与え、`/graphify` コマンドはその地図を正確にナビゲートさせます。
|
||||
|
||||
<details>
|
||||
<summary>手動インストール(curl)</summary>
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.claude/skills/graphify
|
||||
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/skill.md \
|
||||
> ~/.claude/skills/graphify/SKILL.md
|
||||
```
|
||||
|
||||
`~/.claude/CLAUDE.md` に追加します:
|
||||
|
||||
```
|
||||
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
|
||||
When the user types `/graphify`, use the installed graphify skill or instructions before doing anything else.
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
## 使い方
|
||||
|
||||
```
|
||||
/graphify # カレントディレクトリで実行
|
||||
/graphify ./raw # 特定のフォルダで実行
|
||||
/graphify ./raw --mode deep # より積極的な INFERRED エッジ抽出
|
||||
/graphify ./raw --update # 変更されたファイルのみ再抽出し、既存グラフにマージ
|
||||
/graphify ./raw --cluster-only # 既存グラフのクラスタリングを再実行(再抽出なし)
|
||||
/graphify ./raw --no-viz # HTML をスキップ、レポート + JSON のみ生成
|
||||
/graphify ./raw --obsidian # Obsidian ボールトも生成(オプトイン)
|
||||
/graphify ./raw --obsidian --obsidian-dir ~/vaults/myproject # ボールトを特定のディレクトリに書き込み
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # 論文を取得、保存、グラフを更新
|
||||
/graphify add https://x.com/karpathy/status/... # ツイートを取得
|
||||
/graphify add https://... --author "Name" # 元の著者をタグ付け
|
||||
/graphify add https://... --contributor "Name" # コーパスに追加した人をタグ付け
|
||||
|
||||
/graphify query "アテンションとオプティマイザを結ぶものは?"
|
||||
/graphify query "アテンションとオプティマイザを結ぶものは?" --dfs # 特定のパスをトレース
|
||||
/graphify query "アテンションとオプティマイザを結ぶものは?" --budget 1500 # N トークンで上限設定
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
/graphify ./raw --watch # ファイル変更時にグラフを自動同期(コード:即時、ドキュメント:通知)
|
||||
/graphify ./raw --wiki # エージェントがクロール可能な wiki を構築(index.md + コミュニティごとの記事)
|
||||
/graphify ./raw --svg # graph.svg をエクスポート
|
||||
/graphify ./raw --graphml # graph.graphml をエクスポート(Gephi、yEd)
|
||||
/graphify ./raw --neo4j # Neo4j 用の cypher.txt を生成
|
||||
/graphify ./raw --neo4j-push bolt://localhost:7687 # 実行中の Neo4j インスタンスに直接プッシュ
|
||||
/graphify ./raw --mcp # MCP stdio サーバーを起動
|
||||
|
||||
# git フック - プラットフォーム非依存、コミット時とブランチ切り替え時にグラフを再構築
|
||||
graphify hook install
|
||||
graphify hook uninstall
|
||||
graphify hook status
|
||||
|
||||
# 常時有効のアシスタント指示 - プラットフォーム固有
|
||||
graphify claude install # CLAUDE.md + PreToolUse フック(Claude Code)
|
||||
graphify claude uninstall
|
||||
graphify codex install # AGENTS.md(Codex)
|
||||
graphify opencode install # AGENTS.md(OpenCode)
|
||||
graphify claw install # AGENTS.md(OpenClaw)
|
||||
graphify droid install # AGENTS.md(Factory Droid)
|
||||
|
||||
# ターミナルから直接グラフをクエリ(AI アシスタント不要)
|
||||
graphify query "アテンションとオプティマイザを結ぶものは?"
|
||||
graphify query "認証フローを表示" --dfs
|
||||
graphify query "CfgNode とは?" --budget 500
|
||||
graphify query "..." --graph path/to/graph.json
|
||||
```
|
||||
|
||||
あらゆるファイルタイプの組み合わせで動作します:
|
||||
|
||||
| タイプ | 拡張子 | 抽出方法 |
|
||||
|------|-----------|------------|
|
||||
| コード | `.py .ts .js .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1 .ex .exs .m .mm` | tree-sitter による AST + コールグラフ + docstring/コメントの根拠 |
|
||||
| ドキュメント | `.md .txt .rst` | Claude による概念 + 関係性 + 設計根拠 |
|
||||
| Office | `.docx .xlsx` | Markdown に変換した後 Claude で抽出(`pip install graphifyy[office]` が必要) |
|
||||
| 論文 | `.pdf` | 引用マイニング + 概念抽出 |
|
||||
| 画像 | `.png .jpg .webp .gif` | Claude Vision - スクリーンショット、図、任意の言語 |
|
||||
|
||||
## 得られるもの
|
||||
|
||||
**ゴッドノード** - 最高次数の概念(すべてが接続するもの)
|
||||
|
||||
**意外なつながり** - 複合スコアでランク付け。コード-論文のエッジはコード-コードよりも高くランクされます。各結果には平易な英語の理由が含まれます。
|
||||
|
||||
**推奨される質問** - グラフがユニークに答えられる 4〜5 の質問
|
||||
|
||||
**「なぜ」** - docstring、インラインコメント(`# NOTE:`、`# IMPORTANT:`、`# HACK:`、`# WHY:`)、ドキュメントからの設計根拠が `rationale_for` ノードとして抽出されます。コードが何をするかだけでなく――なぜそのように書かれたか。
|
||||
|
||||
**信頼度スコア** - すべての INFERRED エッジには `confidence_score`(0.0〜1.0)があります。何が推測されたかだけでなく、モデルがどれだけ確信していたかもわかります。EXTRACTED エッジは常に 1.0 です。
|
||||
|
||||
**意味的類似性エッジ** - 構造的接続のないクロスファイル概念リンク。互いを呼び出さずに同じ問題を解いている 2 つの関数、同じアルゴリズムを記述しているコード内のクラスと論文内の概念など。
|
||||
|
||||
**ハイパーエッジ** - ペアワイズエッジでは表現できない 3+ ノードを接続するグループ関係。共有プロトコルを実装するすべてのクラス、認証フロー内のすべての関数、論文セクションから 1 つのアイデアを形成するすべての概念など。
|
||||
|
||||
**トークンベンチマーク** - 実行ごとに自動的に出力されます。混合コーパス(Karpathy リポジトリ + 論文 + 画像)で、生ファイルを読むのに比べて 1 クエリあたり **71.5 倍** 少ないトークン。最初の実行で抽出とグラフ構築を行います(これにはトークンがかかります)。以降のクエリはすべて生ファイルではなくコンパクトなグラフを読みます――ここで節約が複利的に効いてきます。SHA256 キャッシュにより、再実行時は変更されたファイルのみ再処理されます。
|
||||
|
||||
**自動同期** (`--watch`) - バックグラウンドターミナルで実行し、コードベースが変更されるとグラフが自動的に更新されます。コードファイルの保存は即座の再構築をトリガーします(AST のみ、LLM なし)。ドキュメント/画像の変更は、LLM の再パスのために `--update` を実行するよう通知します。
|
||||
|
||||
**Git フック** (`graphify hook install`) - post-commit と post-checkout フックをインストールします。コミットごと、ブランチ切り替えごとにグラフが自動的に再構築されます。再構築が失敗した場合、フックは非ゼロコードで終了するため、git がエラーを表面化し、静かに続行することはありません。バックグラウンドプロセスは不要です。
|
||||
|
||||
**Wiki** (`--wiki`) - コミュニティごとおよびゴッドノードごとの Wikipedia スタイルの Markdown 記事と、`index.md` エントリポイント。任意のエージェントを `index.md` に向ければ、JSON をパースする代わりにファイルを読むことでナレッジベースをナビゲートできます。
|
||||
|
||||
## 実例
|
||||
|
||||
| コーパス | ファイル数 | 削減率 | 出力 |
|
||||
|--------|-------|-----------|--------|
|
||||
| Karpathy リポジトリ + 論文5本 + 画像4枚 | 52 | **71.5x** | [`worked/karpathy-repos/`](worked/karpathy-repos/) |
|
||||
| graphify ソース + Transformer 論文 | 4 | **5.4x** | [`worked/mixed-corpus/`](worked/mixed-corpus/) |
|
||||
| httpx(合成 Python ライブラリ) | 6 | ~1x | [`worked/httpx/`](worked/httpx/) |
|
||||
|
||||
トークン削減はコーパスサイズに応じてスケールします。6 ファイルはいずれにせよコンテキストウィンドウに収まるため、そこでのグラフの価値は圧縮ではなく構造的明瞭さです。52 ファイル(コード + 論文 + 画像)では 71 倍以上が得られます。各 `worked/` フォルダには生の入力ファイルと実際の出力(`GRAPH_REPORT.md`、`graph.json`)があり、自分で実行して数字を検証できます。
|
||||
|
||||
## プライバシー
|
||||
|
||||
graphify はドキュメント、論文、画像の意味的抽出のために、ファイル内容を AI コーディングアシスタントの基盤モデル API に送信します――Anthropic(Claude Code)、OpenAI(Codex)、またはプラットフォームが使用するプロバイダーです。コードファイルは tree-sitter AST を介してローカルで処理されます――コードに関してはファイル内容がマシンから出ることはありません。テレメトリ、利用追跡、分析は一切ありません。ネットワーク呼び出しは抽出中のプラットフォームのモデル API への呼び出しのみで、あなた自身の API キーを使用します。
|
||||
|
||||
## 技術スタック
|
||||
|
||||
NetworkX + Leiden(graspologic) + tree-sitter + vis.js。意味的抽出は Claude(Claude Code)、GPT-4(Codex)、またはプラットフォームが実行するモデルを介して行われます。Neo4j は不要、サーバーも不要、完全にローカルで実行されます。
|
||||
|
||||
## スター履歴
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
|
||||
<details>
|
||||
<summary>コントリビューション</summary>
|
||||
|
||||
**実例** は最も信頼を築くコントリビューションです。実際のコーパスで `/graphify` を実行し、出力を `worked/{slug}/` に保存し、グラフが正しく捉えたもの・間違えたものを評価する正直な `review.md` を書き、PR を提出してください。
|
||||
|
||||
**抽出バグ** - 入力ファイル、キャッシュエントリ(`graphify-out/cache/`)、何が見逃された/捏造されたかを添えて issue を開いてください。
|
||||
|
||||
モジュールの責任と言語の追加方法については [ARCHITECTURE.md](ARCHITECTURE.md) を参照してください。
|
||||
|
||||
</details>
|
||||
@@ -0,0 +1,282 @@
|
||||
# graphify
|
||||
|
||||
🇺🇸 [English](../../README.md) | 🇨🇳 [简体中文](README.zh-CN.md) | 🇯🇵 [日本語](README.ja-JP.md) | 🇰🇷 [한국어](README.ko-KR.md) | 🇩🇪 [Deutsch](README.de-DE.md) | 🇫🇷 [Français](README.fr-FR.md) | 🇪🇸 [Español](README.es-ES.md) | 🇮🇳 [हिन्दी](README.hi-IN.md) | 🇧🇷 [Português](README.pt-BR.md) | 🇷🇺 [Русский](README.ru-RU.md) | 🇸🇦 [العربية](README.ar-SA.md) | 🇮🇹 [Italiano](README.it-IT.md) | 🇵🇱 [Polski](README.pl-PL.md) | 🇳🇱 [Nederlands](README.nl-NL.md) | 🇹🇷 [Türkçe](README.tr-TR.md) | 🇺🇦 [Українська](README.uk-UA.md) | 🇻🇳 [Tiếng Việt](README.vi-VN.md) | 🇮🇩 [Bahasa Indonesia](README.id-ID.md) | 🇸🇪 [Svenska](README.sv-SE.md) | 🇬🇷 [Ελληνικά](README.el-GR.md) | 🇷🇴 [Română](README.ro-RO.md) | 🇨🇿 [Čeština](README.cs-CZ.md) | 🇫🇮 [Suomi](README.fi-FI.md) | 🇩🇰 [Dansk](README.da-DK.md) | 🇳🇴 [Norsk](README.no-NO.md) | 🇭🇺 [Magyar](README.hu-HU.md) | 🇹🇭 [ภาษาไทย](README.th-TH.md) | 🇺🇿 [Oʻzbekcha](README.uz-UZ.md) | 🇹🇼 [繁體中文](README.zh-TW.md)
|
||||
|
||||
[](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
|
||||
[](https://pypi.org/project/graphifyy/)
|
||||
[](https://github.com/sponsors/safishamsi)
|
||||
|
||||
**AI 코딩 어시스턴트를 위한 스킬.** Claude Code, Codex, OpenCode, OpenClaw, Factory Droid, 또는 Trae에서 `/graphify`를 입력하면 파일을 읽고 지식 그래프를 구축하여, 미처 몰랐던 구조를 보여줍니다. 코드베이스를 더 빠르게 이해하고, 아키텍처 결정의 "이유"를 찾아보세요.
|
||||
|
||||
완전한 멀티모달 지원. 코드, PDF, 마크다운, 스크린샷, 다이어그램, 화이트보드 사진, 심지어 다른 언어로 된 이미지까지 — graphify는 Claude Vision을 사용하여 이 모든 것에서 개념과 관계를 추출하고 하나의 그래프로 연결합니다. tree-sitter AST를 통해 20개 언어를 지원합니다(Python, JS, TS, Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Lua, Zig, PowerShell, Elixir, Objective-C, Julia).
|
||||
|
||||
> Andrej Karpathy는 논문, 트윗, 스크린샷, 메모를 모아두는 `/raw` 폴더를 관리합니다. graphify는 바로 그 문제에 대한 답입니다 — 원본 파일을 직접 읽는 것 대비 쿼리당 토큰 소비가 71.5배 적고, 세션 간에 영속적이며, 발견한 것과 추측한 것을 정직하게 구분합니다.
|
||||
|
||||
```
|
||||
/graphify . # 어떤 폴더든 동작 - 코드베이스, 노트, 논문, 무엇이든
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html 인터랙티브 그래프 - 노드 클릭, 검색, 커뮤니티별 필터
|
||||
├── GRAPH_REPORT.md 갓 노드, 의외의 연결, 추천 질문
|
||||
├── graph.json 영속 그래프 - 몇 주 후에도 재읽기 없이 쿼리 가능
|
||||
└── cache/ SHA256 캐시 - 재실행 시 변경된 파일만 처리
|
||||
```
|
||||
|
||||
그래프에 포함하지 않을 폴더를 제외하려면 `.graphifyignore` 파일을 추가하세요:
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
vendor/
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
```
|
||||
|
||||
`.gitignore`와 동일한 문법입니다. 패턴은 graphify를 실행한 폴더 기준의 상대 경로에 대해 매칭됩니다.
|
||||
|
||||
## 동작 원리
|
||||
|
||||
graphify는 두 번의 패스로 실행됩니다. 첫 번째는 결정론적 AST 패스로, 코드 파일에서 구조(클래스, 함수, 임포트, 콜 그래프, docstring, 근거 주석)를 LLM 없이 추출합니다. 두 번째는 Claude 서브에이전트가 문서, 논문, 이미지에 대해 병렬로 실행되어 개념, 관계, 설계 근거를 추출합니다. 결과는 NetworkX 그래프로 병합되고, Leiden 커뮤니티 탐지로 클러스터링되며, 인터랙티브 HTML, 쿼리 가능한 JSON, 그리고 일반 언어 감사 보고서로 내보내집니다.
|
||||
|
||||
**클러스터링은 그래프 토폴로지 기반 — 임베딩을 사용하지 않습니다.** Leiden은 엣지 밀도를 기반으로 커뮤니티를 찾습니다. Claude가 추출하는 의미적 유사성 엣지(`semantically_similar_to`, INFERRED로 표시)는 이미 그래프에 포함되어 있으므로 커뮤니티 탐지에 직접 영향을 줍니다. 그래프 구조 자체가 유사성 신호이며 — 별도의 임베딩 단계나 벡터 데이터베이스가 필요하지 않습니다.
|
||||
|
||||
모든 관계는 `EXTRACTED`(소스에서 직접 발견), `INFERRED`(합리적 추론, 신뢰도 점수 포함), `AMBIGUOUS`(리뷰 필요 표시) 중 하나로 태깅됩니다. 무엇이 발견된 것이고 무엇이 추측된 것인지 항상 알 수 있습니다.
|
||||
|
||||
## 설치
|
||||
|
||||
**필수 요구사항:** Python 3.10+ 및 다음 중 하나: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [OpenClaw](https://openclaw.ai), [Factory Droid](https://factory.ai), 또는 [Trae](https://trae.ai)
|
||||
|
||||
```bash
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> PyPI 패키지는 `graphify` 이름을 되찾는 동안 임시로 `graphifyy`로 명명되어 있습니다. CLI와 스킬 명령은 여전히 `graphify`입니다.
|
||||
|
||||
### 플랫폼 지원
|
||||
|
||||
| 플랫폼 | 설치 명령 |
|
||||
|--------|-----------|
|
||||
| Claude Code (Linux/Mac) | `graphify install` |
|
||||
| Claude Code (Windows) | `graphify install` (자동 감지) 또는 `graphify install --platform windows` |
|
||||
| Codex | `graphify install --platform codex` |
|
||||
| OpenCode | `graphify install --platform opencode` |
|
||||
| OpenClaw | `graphify install --platform claw` |
|
||||
| Factory Droid | `graphify install --platform droid` |
|
||||
| Trae | `graphify install --platform trae` |
|
||||
| Trae CN | `graphify install --platform trae-cn` |
|
||||
|
||||
Codex 사용자는 병렬 추출을 위해 `~/.codex/config.toml`의 `[features]` 아래에 `multi_agent = true`도 필요합니다. Factory Droid는 병렬 서브에이전트 디스패치에 `Task` 도구를 사용합니다. OpenClaw는 순차 추출을 사용합니다(해당 플랫폼의 병렬 에이전트 지원은 아직 초기 단계입니다). Trae는 병렬 서브에이전트 디스패치에 Agent 도구를 사용하며 PreToolUse 훅을 **지원하지 않습니다** — AGENTS.md가 상시 작동 메커니즘입니다.
|
||||
|
||||
그런 다음 AI 코딩 어시스턴트를 열고 입력하세요:
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
참고: Codex는 스킬 호출에 `/` 대신 `$`를 사용하므로 `$graphify .`라고 입력하세요.
|
||||
|
||||
### 어시스턴트가 항상 그래프를 사용하도록 설정 (권장)
|
||||
|
||||
그래프를 빌드한 후, 프로젝트에서 한 번만 실행하세요:
|
||||
|
||||
| 플랫폼 | 명령 |
|
||||
|--------|------|
|
||||
| Claude Code | `graphify claude install` |
|
||||
| Codex | `graphify codex install` |
|
||||
| OpenCode | `graphify opencode install` |
|
||||
| OpenClaw | `graphify claw install` |
|
||||
| Factory Droid | `graphify droid install` |
|
||||
| Trae | `graphify trae install` |
|
||||
| Trae CN | `graphify trae-cn install` |
|
||||
|
||||
**Claude Code**는 두 가지를 수행합니다: 아키텍처 질문에 답하기 전에 `graphify-out/GRAPH_REPORT.md`를 읽도록 Claude에게 지시하는 `CLAUDE.md` 섹션을 작성하고, 모든 Glob 및 Grep 호출 전에 실행되는 **PreToolUse 훅**(`settings.json`)을 설치합니다. 지식 그래프가 존재하면 Claude는 다음 메시지를 보게 됩니다: _"graphify: Knowledge graph exists. Read GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ — 이를 통해 Claude는 모든 파일을 grep하는 대신 그래프를 통해 탐색합니다.
|
||||
|
||||
**Codex**는 `AGENTS.md`에 작성하고 Bash 도구 호출 전에 실행되는 **PreToolUse 훅**을 `.codex/hooks.json`에 설치합니다 — Claude Code와 동일한 상시 작동 메커니즘입니다.
|
||||
|
||||
**OpenCode, OpenClaw, Factory Droid, Trae**는 프로젝트 루트의 `AGENTS.md`에 동일한 규칙을 작성합니다. 이 플랫폼들은 PreToolUse 훅을 지원하지 않으므로 AGENTS.md가 상시 작동 메커니즘입니다.
|
||||
|
||||
제거는 대응하는 uninstall 명령으로 수행합니다(예: `graphify claude uninstall`).
|
||||
|
||||
**상시 작동 vs 명시적 트리거 — 차이점은?**
|
||||
|
||||
상시 작동 훅은 `GRAPH_REPORT.md`를 노출합니다 — 갓 노드, 커뮤니티, 의외의 연결을 한 페이지로 요약한 것입니다. 어시스턴트는 파일 검색 전에 이것을 읽으므로 키워드 매칭이 아닌 구조 기반으로 탐색합니다. 이것만으로 대부분의 일상적인 질문을 처리할 수 있습니다.
|
||||
|
||||
`/graphify query`, `/graphify path`, `/graphify explain`은 더 깊이 들어갑니다: 원시 `graph.json`을 홉 단위로 순회하고, 노드 간의 정확한 경로를 추적하며, 엣지 수준의 세부 정보(관계 유형, 신뢰도 점수, 소스 위치)를 보여줍니다. 일반적인 오리엔테이션이 아닌 그래프에서 특정 질문에 답하고 싶을 때 사용하세요.
|
||||
|
||||
이렇게 생각하면 됩니다: 상시 작동 훅은 어시스턴트에게 지도를 주고, `/graphify` 명령은 그 지도를 정확하게 탐색하게 합니다.
|
||||
|
||||
## `graph.json`을 LLM과 함께 사용하기
|
||||
|
||||
`graph.json`은 프롬프트에 한 번에 전부 붙여넣기 위한 것이 아닙니다. 유용한 워크플로우는 다음과 같습니다:
|
||||
|
||||
1. `graphify-out/GRAPH_REPORT.md`로 높은 수준의 개요를 파악합니다.
|
||||
2. `graphify query`를 사용하여 답하려는 특정 질문에 대한 더 작은 서브그래프를 가져옵니다.
|
||||
3. 전체 원시 코퍼스 대신 그 집중된 결과를 어시스턴트에게 제공합니다.
|
||||
|
||||
예를 들어, 프로젝트에서 graphify를 실행한 후:
|
||||
|
||||
```bash
|
||||
graphify query "show the auth flow" --graph graphify-out/graph.json
|
||||
graphify query "what connects DigestAuth to Response?" --graph graphify-out/graph.json
|
||||
```
|
||||
|
||||
출력에는 노드 레이블, 엣지 유형, 신뢰도 태그, 소스 파일, 소스 위치가 포함됩니다. 이는 LLM을 위한 좋은 중간 컨텍스트 블록이 됩니다:
|
||||
|
||||
```text
|
||||
이 그래프 쿼리 결과를 사용하여 질문에 답하세요. 추측보다 그래프 구조를 우선하고,
|
||||
가능한 경우 소스 파일을 인용하세요.
|
||||
```
|
||||
|
||||
어시스턴트가 도구 호출이나 MCP를 지원하는 경우, 텍스트를 붙여넣는 대신 그래프를 직접 사용하세요. graphify는 `graph.json`을 MCP 서버로 노출할 수 있습니다:
|
||||
|
||||
```bash
|
||||
python -m graphify.serve graphify-out/graph.json
|
||||
```
|
||||
|
||||
이를 통해 어시스턴트가 `query_graph`, `get_node`, `get_neighbors`, `shortest_path` 같은 반복 쿼리에 구조화된 그래프 접근을 할 수 있습니다.
|
||||
|
||||
<details>
|
||||
<summary>수동 설치 (curl)</summary>
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.claude/skills/graphify
|
||||
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/skill.md \
|
||||
> ~/.claude/skills/graphify/SKILL.md
|
||||
```
|
||||
|
||||
`~/.claude/CLAUDE.md`에 추가:
|
||||
|
||||
```
|
||||
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
|
||||
When the user types `/graphify`, use the installed graphify skill or instructions before doing anything else.
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
## 사용법
|
||||
|
||||
```
|
||||
/graphify # 현재 디렉토리에서 실행
|
||||
/graphify ./raw # 특정 폴더에서 실행
|
||||
/graphify ./raw --mode deep # 더 적극적인 INFERRED 엣지 추출
|
||||
/graphify ./raw --update # 변경된 파일만 재추출하여 기존 그래프에 병합
|
||||
/graphify ./raw --cluster-only # 기존 그래프의 클러스터링만 재실행, 재추출 없음
|
||||
/graphify ./raw --no-viz # HTML 건너뛰기, 보고서 + JSON만 생성
|
||||
/graphify ./raw --obsidian # Obsidian 볼트도 생성 (옵트인)
|
||||
/graphify ./raw --obsidian --obsidian-dir ~/vaults/myproject # 볼트를 특정 디렉토리에 생성
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # 논문 가져오기, 저장, 그래프 업데이트
|
||||
/graphify add https://x.com/karpathy/status/... # 트윗 가져오기
|
||||
/graphify add https://... --author "Name" # 원저자 태그
|
||||
/graphify add https://... --contributor "Name" # 코퍼스에 추가한 사람 태그
|
||||
|
||||
/graphify query "어텐션과 옵티마이저를 연결하는 것은?"
|
||||
/graphify query "어텐션과 옵티마이저를 연결하는 것은?" --dfs # 특정 경로 추적
|
||||
/graphify query "어텐션과 옵티마이저를 연결하는 것은?" --budget 1500 # N 토큰으로 제한
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
/graphify ./raw --watch # 파일 변경 시 그래프 자동 동기화 (코드: 즉시, 문서: 알림)
|
||||
/graphify ./raw --wiki # 에이전트가 크롤 가능한 위키 빌드 (index.md + 커뮤니티별 문서)
|
||||
/graphify ./raw --svg # graph.svg 내보내기
|
||||
/graphify ./raw --graphml # graph.graphml 내보내기 (Gephi, yEd)
|
||||
/graphify ./raw --neo4j # Neo4j용 cypher.txt 생성
|
||||
/graphify ./raw --neo4j-push bolt://localhost:7687 # 실행 중인 Neo4j 인스턴스에 직접 푸시
|
||||
/graphify ./raw --mcp # MCP stdio 서버 시작
|
||||
|
||||
# git 훅 - 플랫폼 무관, 커밋 및 브랜치 전환 시 그래프 재빌드
|
||||
graphify hook install
|
||||
graphify hook uninstall
|
||||
graphify hook status
|
||||
|
||||
# 상시 작동 어시스턴트 지시 - 플랫폼별
|
||||
graphify claude install # CLAUDE.md + PreToolUse 훅 (Claude Code)
|
||||
graphify claude uninstall
|
||||
graphify codex install # AGENTS.md (Codex)
|
||||
graphify opencode install # AGENTS.md (OpenCode)
|
||||
graphify claw install # AGENTS.md (OpenClaw)
|
||||
graphify droid install # AGENTS.md (Factory Droid)
|
||||
graphify trae install # AGENTS.md (Trae)
|
||||
graphify trae uninstall
|
||||
graphify trae-cn install # AGENTS.md (Trae CN)
|
||||
graphify trae-cn uninstall
|
||||
|
||||
# 터미널에서 직접 그래프 쿼리 (AI 어시스턴트 불필요)
|
||||
graphify query "어텐션과 옵티마이저를 연결하는 것은?"
|
||||
graphify query "인증 흐름 보기" --dfs
|
||||
graphify query "CfgNode이 뭐지?" --budget 500
|
||||
graphify query "..." --graph path/to/graph.json
|
||||
```
|
||||
|
||||
다양한 파일 유형의 조합과 함께 동작합니다:
|
||||
|
||||
| 유형 | 확장자 | 추출 방식 |
|
||||
|------|--------|-----------|
|
||||
| 코드 | `.py .ts .js .jsx .tsx .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1 .ex .exs .m .mm .jl` | tree-sitter AST + 콜 그래프 + docstring/주석 근거 |
|
||||
| 문서 | `.md .txt .rst` | Claude를 통한 개념 + 관계 + 설계 근거 |
|
||||
| 오피스 | `.docx .xlsx` | 마크다운으로 변환 후 Claude를 통해 추출 (`pip install graphifyy[office]` 필요) |
|
||||
| 논문 | `.pdf` | 인용 마이닝 + 개념 추출 |
|
||||
| 이미지 | `.png .jpg .webp .gif` | Claude Vision - 스크린샷, 다이어그램, 모든 언어 |
|
||||
|
||||
## 결과물
|
||||
|
||||
**갓 노드** - 최고 차수의 개념 (모든 것이 연결되는 허브)
|
||||
|
||||
**의외의 연결** - 복합 점수로 순위 지정. 코드-논문 엣지는 코드-코드보다 높게 순위됩니다. 각 결과에는 쉬운 설명이 포함됩니다.
|
||||
|
||||
**추천 질문** - 그래프가 고유하게 답할 수 있는 4~5개의 질문
|
||||
|
||||
**"이유"** - docstring, 인라인 주석(`# NOTE:`, `# IMPORTANT:`, `# HACK:`, `# WHY:`), 문서의 설계 근거가 `rationale_for` 노드로 추출됩니다. 코드가 무엇을 하는지뿐만 아니라 — 왜 그렇게 작성되었는지.
|
||||
|
||||
**신뢰도 점수** - 모든 INFERRED 엣지에는 `confidence_score`(0.0~1.0)가 있습니다. 무엇이 추측되었는지뿐 아니라 모델이 얼마나 확신했는지도 알 수 있습니다. EXTRACTED 엣지는 항상 1.0입니다.
|
||||
|
||||
**의미적 유사성 엣지** - 구조적 연결 없는 파일 간 개념 링크. 서로를 호출하지 않으면서 같은 문제를 해결하는 두 함수, 코드의 클래스와 같은 알고리즘을 설명하는 논문의 개념 등.
|
||||
|
||||
**하이퍼엣지** - 쌍별 엣지로는 표현할 수 없는 3개 이상 노드의 그룹 관계. 공유 프로토콜을 구현하는 모든 클래스, 인증 흐름의 모든 함수, 논문 섹션에서 하나의 아이디어를 구성하는 모든 개념 등.
|
||||
|
||||
**토큰 벤치마크** - 매 실행 후 자동으로 출력됩니다. 혼합 코퍼스(Karpathy 리포지토리 + 논문 + 이미지)에서: 원본 파일 대비 쿼리당 **71.5배** 적은 토큰. 첫 실행은 추출과 그래프 빌드를 수행합니다(토큰이 소비됩니다). 이후 모든 쿼리는 원본 파일 대신 압축된 그래프를 읽습니다 — 여기서 절약이 복리로 누적됩니다. SHA256 캐시로 재실행 시 변경된 파일만 재처리합니다.
|
||||
|
||||
**자동 동기화** (`--watch`) - 백그라운드 터미널에서 실행하면 코드베이스가 변경될 때 그래프가 자동으로 업데이트됩니다. 코드 파일 저장 시 즉시 재빌드가 트리거됩니다(AST만, LLM 없음). 문서/이미지 변경 시에는 LLM 재처리를 위해 `--update` 실행을 알려줍니다.
|
||||
|
||||
**Git 훅** (`graphify hook install`) - post-commit 및 post-checkout 훅을 설치합니다. 모든 커밋과 브랜치 전환 후 그래프가 자동으로 재빌드됩니다. 재빌드가 실패하면 훅이 0이 아닌 코드로 종료하여 git이 에러를 표시하고 조용히 계속 진행하지 않습니다. 백그라운드 프로세스가 필요 없습니다.
|
||||
|
||||
**위키** (`--wiki`) - 커뮤니티 및 갓 노드별 위키피디아 스타일 마크다운 문서와 `index.md` 진입점. 어떤 에이전트든 `index.md`를 가리키면 JSON을 파싱하는 대신 파일을 읽어서 지식 베이스를 탐색할 수 있습니다.
|
||||
|
||||
## 실전 예제
|
||||
|
||||
| 코퍼스 | 파일 수 | 축소율 | 결과 |
|
||||
|--------|---------|--------|------|
|
||||
| Karpathy 리포지토리 + 논문 5편 + 이미지 4장 | 52 | **71.5x** | [`worked/karpathy-repos/`](worked/karpathy-repos/) |
|
||||
| graphify 소스 + Transformer 논문 | 4 | **5.4x** | [`worked/mixed-corpus/`](worked/mixed-corpus/) |
|
||||
| httpx (합성 Python 라이브러리) | 6 | ~1x | [`worked/httpx/`](worked/httpx/) |
|
||||
|
||||
토큰 축소는 코퍼스 크기에 비례하여 확장됩니다. 6개 파일은 어차피 컨텍스트 윈도우에 들어가므로, 그래프의 가치는 압축이 아닌 구조적 명확성에 있습니다. 52개 파일(코드 + 논문 + 이미지)에서는 71배 이상을 달성합니다. 각 `worked/` 폴더에는 원본 입력 파일과 실제 출력(`GRAPH_REPORT.md`, `graph.json`)이 있어 직접 실행하여 수치를 검증할 수 있습니다.
|
||||
|
||||
## 개인정보 보호
|
||||
|
||||
graphify는 문서, 논문, 이미지의 의미적 추출을 위해 파일 내용을 AI 코딩 어시스턴트의 기반 모델 API로 전송합니다 — Anthropic(Claude Code), OpenAI(Codex), 또는 사용 중인 플랫폼의 제공자. 코드 파일은 tree-sitter AST를 통해 로컬에서 처리됩니다 — 코드의 경우 파일 내용이 사용자의 머신을 벗어나지 않습니다. 어떠한 텔레메트리, 사용 추적, 분석도 없습니다. 유일한 네트워크 호출은 추출 중 플랫폼 모델 API에 대한 것이며, 사용자 본인의 API 키를 사용합니다.
|
||||
|
||||
## 기술 스택
|
||||
|
||||
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. 의미적 추출은 Claude(Claude Code), GPT-4(Codex), 또는 플랫폼이 실행하는 모델을 통해 수행됩니다. Neo4j 불필요, 서버 불필요, 완전히 로컬에서 실행됩니다.
|
||||
|
||||
## 다음 계획
|
||||
|
||||
graphify는 그래프 레이어입니다. 그 위에 [Penpax](https://safishamsi.github.io/penpax.ai)를 개발하고 있습니다 — 회의, 브라우저 기록, 파일, 이메일, 코드를 하나의 지속적으로 업데이트되는 지식 그래프로 연결하는 온디바이스 디지털 트윈입니다. 클라우드 없음, 데이터 학습 없음. [대기 목록에 등록하세요.](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
## 스타 히스토리
|
||||
|
||||
[](https://starchart.cc/safishamsi/graphify)
|
||||
|
||||
<details>
|
||||
<summary>기여하기</summary>
|
||||
|
||||
**실전 예제**는 가장 신뢰를 쌓는 기여 방식입니다. 실제 코퍼스에서 `/graphify`를 실행하고, 결과를 `worked/{slug}/`에 저장하고, 그래프가 맞게 파악한 것과 틀린 것을 평가하는 솔직한 `review.md`를 작성하여 PR을 제출하세요.
|
||||
|
||||
**추출 버그** - 입력 파일, 캐시 엔트리(`graphify-out/cache/`), 그리고 누락되거나 날조된 내용과 함께 이슈를 열어주세요.
|
||||
|
||||
모듈 책임과 언어 추가 방법은 [ARCHITECTURE.md](ARCHITECTURE.md)를 참조하세요.
|
||||
|
||||
</details>
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**Een vaardigheid voor AI-codeassistenten.** Typ `/graphify` in Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro of Google Antigravity — het leest je bestanden, bouwt een kennisgraaf en geeft je structuur terug die je niet wist dat er was. Begrijp een codebase sneller. Vind het "waarom" achter architecturale beslissingen.
|
||||
|
||||
Volledig multimodaal. Voeg code, PDF's, markdown, schermafbeeldingen, diagrammen, whiteboard-foto's, afbeeldingen in andere talen of video- en audiobestanden toe — graphify extraheert concepten en relaties uit alles en verbindt ze in één graaf. Video's worden lokaal getranscribeerd met Whisper. Ondersteunt 25 programmeertalen via tree-sitter AST.
|
||||
|
||||
> Andrej Karpathy houdt een `/raw`-map bij waar hij papers, tweets, schermafbeeldingen en notities neerlegt. graphify is het antwoord op dat probleem — **71,5x** minder tokens per query versus het lezen van ruwe bestanden, persistent tussen sessies.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html interactieve graaf — open in elke browser
|
||||
├── GRAPH_REPORT.md godknooppunten, verrassende verbindingen, voorgestelde vragen
|
||||
├── graph.json persistente graaf — weken later opvraagbaar
|
||||
└── cache/ SHA256-cache — herhaalde runs verwerken alleen gewijzigde bestanden
|
||||
```
|
||||
|
||||
## Hoe het werkt
|
||||
|
||||
graphify werkt in drie passes. Eerst extraheert een deterministische AST-pass structuur uit codebestanden zonder LLM. Vervolgens worden video- en audiobestanden lokaal getranscribeerd met faster-whisper. Ten slotte werken Claude-subagenten parallel over documenten, papers, afbeeldingen en transcripties. De resultaten worden samengevoegd in een NetworkX-graaf, geclusterd met Leiden en geëxporteerd als interactieve HTML, opvraagbare JSON en een auditrapport.
|
||||
|
||||
Elke relatie is gelabeld als `EXTRACTED`, `INFERRED` (met betrouwbaarheidsscore) of `AMBIGUOUS`.
|
||||
|
||||
## Installatie
|
||||
|
||||
**Vereisten:** Python 3.10+ en één van: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [Cursor](https://cursor.com), [Aider](https://aider.chat) en andere.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# of met pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# of pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Officieel pakket:** Het PyPI-pakket heet `graphifyy`. De enige officiële repository is [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Gebruik
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "wat verbindt Attention met de optimizer?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Wat je krijgt
|
||||
|
||||
**Godknooppunten** — concepten met de hoogste graad · **Verrassende verbindingen** — gerangschikt op score · **Voorgestelde vragen** · **Het "waarom"** — docstrings en ontwerprationale als knooppunten · **Tokenbenchmark** — **71,5x** minder tokens op gemengd corpus.
|
||||
|
||||
## Privacy
|
||||
|
||||
Codebestanden worden lokaal verwerkt via tree-sitter AST. Video's lokaal getranscribeerd met faster-whisper. Geen telemetrie.
|
||||
|
||||
## Gebouwd op graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) is de enterprise-laag boven op graphify. **Gratis proefversie binnenkort.** [Meld je aan voor de wachtlijst →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**En ferdighet for AI-kodeassistenter.** Skriv `/graphify` i Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro eller Google Antigravity — den leser filene dine, bygger en kunnskapsgraf og gir deg tilbake strukturen du ikke visste eksisterte. Forstå en kodebase raskere. Finn «hvorfor» bak arkitektoniske beslutninger.
|
||||
|
||||
Fullt multimodal. Legg til kode, PDF-er, markdown, skjermbilder, diagrammer, whiteboardbilder, bilder på andre språk eller video- og lydfiler — graphify ekstraherer begreper og relasjoner fra alt og kobler dem i én graf. Videoer transkriberes lokalt med Whisper. Støtter 25 programmeringsspråk via tree-sitter AST.
|
||||
|
||||
> Andrej Karpathy opprettholder en `/raw`-mappe der han legger artikler, tweets, skjermbilder og notater. graphify er svaret på det problemet — **71,5x** færre tokens per spørring sammenlignet med å lese råfiler, vedvarende mellom sesjoner.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html interaktiv graf — åpne i en hvilken som helst nettleser
|
||||
├── GRAPH_REPORT.md gudnoder, overraskende forbindelser, foreslåtte spørsmål
|
||||
├── graph.json vedvarende graf — forespørselbar uker senere
|
||||
└── cache/ SHA256-cache — gjentatte kjøringer behandler bare endrede filer
|
||||
```
|
||||
|
||||
## Hvordan det fungerer
|
||||
|
||||
graphify arbeider i tre gjennomganger. Først ekstraherer et deterministisk AST-gjennomgang struktur fra kodefiler uten LLM. Deretter transkriberes video- og lydfiler lokalt med faster-whisper. Til slutt kjører Claude-underagenter parallelt på dokumenter, artikler, bilder og transkripsjoner. Resultatene slås sammen i en NetworkX-graf, klynges med Leiden og eksporteres som interaktiv HTML, forespørselbar JSON og revisjonsrapport.
|
||||
|
||||
Hver relasjon er merket `EXTRACTED`, `INFERRED` (med konfidenspoeng) eller `AMBIGUOUS`.
|
||||
|
||||
## Installasjon
|
||||
|
||||
**Krav:** Python 3.10+ og én av: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) og andre.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# eller med pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# eller pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Offisiell pakke:** PyPI-pakken heter `graphifyy`. Det eneste offisielle depotet er [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Bruk
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "hva kobler Attention til optimizeren?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Hva du får
|
||||
|
||||
**Gudnoder** — begreper med høyest grad · **Overraskende forbindelser** — rangert etter poeng · **Foreslåtte spørsmål** · **«Hvorfor»** — docstrings og designbegrunnelse ekstrahert som noder · **Token-benchmark** — **71,5x** færre tokens på blandet korpus.
|
||||
|
||||
## Personvern
|
||||
|
||||
Kodefiler behandles lokalt via tree-sitter AST. Videoer transkriberes lokalt med faster-whisper. Ingen telemetri.
|
||||
|
||||
## Bygget på graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) er enterprise-laget oppå graphify. **Gratis prøveperiode kommer snart.** [Bli med på ventelisten →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,78 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**Umiejętność dla asystenta kodowania AI.** Wpisz `/graphify` w Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro lub Google Antigravity — czyta Twoje pliki, buduje graf wiedzy i zwraca Ci strukturę, o której nie wiedziałeś, że istnieje. Rozumiej bazę kodu szybciej. Znajdź „dlaczego" za decyzjami architektonicznymi.
|
||||
|
||||
W pełni multimodalny. Dodaj kod, PDF, markdown, zrzuty ekranu, diagramy, zdjęcia tablic, obrazy w innych językach lub pliki wideo i audio — graphify wyodrębnia koncepcje i relacje ze wszystkiego i łączy je w jeden graf. Wideo są transkrybowane lokalnie za pomocą Whisper. Obsługuje 25 języków programowania przez tree-sitter AST.
|
||||
|
||||
> Andrej Karpathy prowadzi folder `/raw`, gdzie wrzuca artykuły, tweety, zrzuty ekranu i notatki. graphify jest odpowiedzią na ten problem — **71,5x** mniej tokenów na zapytanie w porównaniu z czytaniem surowych plików, trwały między sesjami.
|
||||
|
||||
```
|
||||
/graphify . # działa na dowolnym folderze
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html interaktywny graf — otwórz w dowolnej przeglądarce
|
||||
├── GRAPH_REPORT.md węzły boga, zaskakujące połączenia, sugerowane pytania
|
||||
├── graph.json trwały graf — zapytaj tygodnie później
|
||||
└── cache/ cache SHA256 — ponowne uruchomienia przetwarzają tylko zmienione pliki
|
||||
```
|
||||
|
||||
## Jak to działa
|
||||
|
||||
graphify działa w trzech przebiegach. Najpierw deterministyczny przebieg AST wyodrębnia strukturę z plików kodu bez LLM. Następnie pliki wideo i audio są transkrybowane lokalnie za pomocą faster-whisper. Na koniec subagenci Claude działają równolegle na dokumentach, artykułach, obrazach i transkrypcjach. Wyniki są łączone w graf NetworkX, grupowane za pomocą Leiden i eksportowane jako interaktywny HTML, JSON i raport audytu.
|
||||
|
||||
Każda relacja jest oznaczona `EXTRACTED`, `INFERRED` (z wynikiem pewności) lub `AMBIGUOUS`.
|
||||
|
||||
## Instalacja
|
||||
|
||||
**Wymagania:** Python 3.10+ i jedno z: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) i inne.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# lub z pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# lub pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Oficjalny pakiet:** Pakiet PyPI nazywa się `graphifyy`. Jedyne oficjalne repozytorium to [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Użycie
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update # tylko zmienione pliki
|
||||
/graphify ./raw --mode deep
|
||||
/graphify query "co łączy Attention z optymalizatorem?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Co otrzymujesz
|
||||
|
||||
**Węzły boga** — koncepcje o najwyższym stopniu · **Zaskakujące połączenia** — posortowane według wyniku · **Sugerowane pytania** — 4-5 pytań, na które graf jest wyjątkowo zdolny odpowiedzieć · **„Dlaczego"** — docstringi i uzasadnienia projektowe wyodrębnione jako węzły · **Benchmark tokenów** — **71,5x** mniej tokenów na mieszanym korpusie.
|
||||
|
||||
## Prywatność
|
||||
|
||||
Pliki kodu są przetwarzane lokalnie przez tree-sitter AST. Wideo transkrybowane lokalnie z faster-whisper. Brak telemetrii.
|
||||
|
||||
## Zbudowane na graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) to warstwa enterprise nad graphify. **Bezpłatna wersja próbna wkrótce.** [Dołącz do listy oczekujących →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,170 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></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>
|
||||
</p>
|
||||
|
||||
**Uma habilidade para assistentes de código IA.** Digite `/graphify` no Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro ou Google Antigravity — ele lê seus arquivos, constrói um grafo de conhecimento e devolve a você estrutura que você não sabia que existia. Entenda uma base de código mais rapidamente. Encontre o "porquê" por trás das decisões arquiteturais.
|
||||
|
||||
Totalmente multimodal. Adicione código, PDFs, markdown, capturas de tela, diagramas, fotos de quadros brancos, imagens em outros idiomas, ou arquivos de vídeo e áudio — graphify extrai conceitos e relações de tudo isso e os conecta em um único grafo. Vídeos são transcritos localmente com Whisper usando um prompt adaptado ao domínio derivado do seu corpus. 25 linguagens de programação suportadas via tree-sitter AST (Python, JS, TS, Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Lua, Zig, PowerShell, Elixir, Objective-C, Julia, Verilog, SystemVerilog, Vue, Svelte, Dart).
|
||||
|
||||
> Andrej Karpathy mantém uma pasta `/raw` onde deposita papers, tweets, capturas de tela e notas. graphify é a resposta para esse problema — 71,5x menos tokens por consulta versus ler os arquivos brutos, persistente entre sessões, honesto sobre o que foi encontrado versus inferido.
|
||||
|
||||
```
|
||||
/graphify . # funciona em qualquer pasta — seu código, notas, papers, tudo
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html grafo interativo — abrir em qualquer navegador, clicar em nós, pesquisar
|
||||
├── GRAPH_REPORT.md nós deus, conexões surpreendentes, perguntas sugeridas
|
||||
├── graph.json grafo persistente — consultar semanas depois sem reler
|
||||
└── cache/ cache SHA256 — re-execuções processam apenas arquivos modificados
|
||||
```
|
||||
|
||||
Adicione um arquivo `.graphifyignore` para excluir pastas:
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
vendor/
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
```
|
||||
|
||||
Mesma sintaxe do `.gitignore`.
|
||||
|
||||
## Como funciona
|
||||
|
||||
graphify executa em três passes. Primeiro, uma passagem AST determinística extrai estrutura de arquivos de código (classes, funções, importações, grafos de chamadas, docstrings, comentários de justificativa) sem LLM. Segundo, arquivos de vídeo e áudio são transcritos localmente com faster-whisper. Terceiro, subagentes Claude executam em paralelo sobre documentos, papers, imagens e transcrições para extrair conceitos, relações e justificativas de design. Os resultados são mesclados em um grafo NetworkX, agrupados com detecção de comunidades Leiden, e exportados como HTML interativo, JSON consultável e um relatório de auditoria em linguagem natural.
|
||||
|
||||
**O clustering é baseado em topologia de grafo — sem embeddings.** Leiden encontra comunidades por densidade de arestas. As arestas de similaridade semântica que Claude extrai (`semantically_similar_to`, marcadas INFERRED) já estão no grafo. A estrutura do grafo é o sinal de similaridade — nenhum passo de embedding separado ou banco de dados vetorial é necessário.
|
||||
|
||||
Cada relação é marcada como `EXTRACTED` (encontrada diretamente na fonte), `INFERRED` (inferência razoável com pontuação de confiança) ou `AMBIGUOUS` (marcada para revisão).
|
||||
|
||||
## Instalação
|
||||
|
||||
**Requisitos:** Python 3.10+ e um de: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com), [Gemini CLI](https://github.com/google-gemini/gemini-cli), [GitHub Copilot CLI](https://docs.github.com/en/copilot/how-tos/copilot-cli), [VS Code Copilot Chat](https://code.visualstudio.com/docs/copilot/overview), [Aider](https://aider.chat), [OpenClaw](https://openclaw.ai), [Factory Droid](https://factory.ai), [Trae](https://trae.ai), [Kiro](https://kiro.dev), Hermes ou [Google Antigravity](https://antigravity.google)
|
||||
|
||||
```bash
|
||||
# Recomendado — funciona no Mac e Linux sem configurar o PATH
|
||||
uv tool install graphifyy && graphify install
|
||||
# ou com pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# ou pip simples
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Pacote oficial:** O pacote PyPI chama-se `graphifyy` (instalar com `pip install graphifyy`). Outros pacotes chamados `graphify*` no PyPI não são afiliados a este projeto. O único repositório oficial é [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
### Suporte a plataformas
|
||||
|
||||
| Plataforma | Comando de instalação |
|
||||
|------------|-----------------------|
|
||||
| Claude Code (Linux/Mac) | `graphify install` |
|
||||
| Claude Code (Windows) | `graphify install` (detecção automática) ou `graphify install --platform windows` |
|
||||
| Codex | `graphify install --platform codex` |
|
||||
| OpenCode | `graphify install --platform opencode` |
|
||||
| GitHub Copilot CLI | `graphify install --platform copilot` |
|
||||
| VS Code Copilot Chat | `graphify vscode install` |
|
||||
| Aider | `graphify install --platform aider` |
|
||||
| OpenClaw | `graphify install --platform claw` |
|
||||
| Factory Droid | `graphify install --platform droid` |
|
||||
| Trae | `graphify install --platform trae` |
|
||||
| Trae CN | `graphify install --platform trae-cn` |
|
||||
| Gemini CLI | `graphify install --platform gemini` |
|
||||
| Hermes | `graphify install --platform hermes` |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
Depois abra seu assistente de código IA e digite:
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
Nota: Codex usa `$` em vez de `/` para habilidades, então digite `$graphify .`.
|
||||
|
||||
### Fazer o assistente sempre usar o grafo (recomendado)
|
||||
|
||||
Após construir um grafo, execute isso uma vez no seu projeto:
|
||||
|
||||
| Plataforma | Comando |
|
||||
|------------|---------|
|
||||
| Claude Code | `graphify claude install` |
|
||||
| Codex | `graphify codex install` |
|
||||
| OpenCode | `graphify opencode install` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Gemini CLI | `graphify gemini install` |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
## Uso
|
||||
|
||||
```
|
||||
/graphify # diretório atual
|
||||
/graphify ./raw # pasta específica
|
||||
/graphify ./raw --mode deep # extração de arestas INFERRED mais agressiva
|
||||
/graphify ./raw --update # re-extrair apenas arquivos modificados
|
||||
/graphify ./raw --directed # grafo dirigido
|
||||
/graphify ./raw --cluster-only # re-executar clustering no grafo existente
|
||||
/graphify ./raw --no-viz # sem HTML, apenas relatório + JSON
|
||||
/graphify ./raw --obsidian # gerar vault do Obsidian (opt-in)
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # buscar um paper
|
||||
/graphify add <video-url> # baixar áudio, transcrever, adicionar
|
||||
/graphify query "o que conecta Attention ao otimizador?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
graphify hook install # instalar hooks do Git
|
||||
graphify update ./src # re-extrair arquivos de código, sem LLM
|
||||
graphify watch ./src # atualização automática do grafo
|
||||
```
|
||||
|
||||
## O que você obtém
|
||||
|
||||
**Nós deus** — conceitos com maior grau (por onde tudo passa)
|
||||
|
||||
**Conexões surpreendentes** — classificadas por pontuação composta. Arestas código-paper pontuam mais alto. Cada resultado inclui um porquê em linguagem natural.
|
||||
|
||||
**Perguntas sugeridas** — 4-5 perguntas que o grafo está em posição única de responder
|
||||
|
||||
**O "porquê"** — docstrings, comentários inline (`# NOTE:`, `# IMPORTANT:`, `# HACK:`, `# WHY:`), e justificativas de design extraídas como nós `rationale_for`.
|
||||
|
||||
**Pontuações de confiança** — cada aresta INFERRED tem um `confidence_score` (0,0-1,0).
|
||||
|
||||
**Benchmark de tokens** — impresso automaticamente após cada execução. Em um corpus misto: **71,5x** menos tokens por consulta vs arquivos brutos.
|
||||
|
||||
**Sincronização automática** (`--watch`) — atualiza o grafo automaticamente quando o código muda.
|
||||
|
||||
**Hooks do Git** (`graphify hook install`) — instala hooks post-commit e post-checkout.
|
||||
|
||||
## Privacidade
|
||||
|
||||
graphify envia conteúdo de arquivos para a API do modelo do seu assistente IA para extração semântica de documentos, papers e imagens. Arquivos de código são processados localmente via tree-sitter AST. Arquivos de vídeo e áudio são transcritos localmente com faster-whisper. Sem telemetria, sem rastreamento de uso.
|
||||
|
||||
## Stack técnico
|
||||
|
||||
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Extração semântica via Claude, GPT-4 ou o modelo da sua plataforma. Transcrição de vídeo via faster-whisper + yt-dlp (opcional).
|
||||
|
||||
## Construído sobre graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) é a camada enterprise sobre o graphify. Onde o graphify transforma uma pasta de arquivos em um grafo de conhecimento, o Penpax aplica o mesmo grafo a toda a sua vida profissional — continuamente.
|
||||
|
||||
**Teste gratuito em breve.** [Entrar na lista de espera →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
## Histórico de estrelas
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**O abilitate pentru asistenții de cod AI.** Tastați `/graphify` în Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro sau Google Antigravity — citește fișierele dvs., construiește un graf de cunoștințe și vă returnează structura pe care nu știați că există. Înțelegeți mai rapid o bază de cod. Găsiți „de ce"-ul din spatele deciziilor arhitecturale.
|
||||
|
||||
Complet multimodal. Adăugați cod, PDF-uri, markdown, capturi de ecran, diagrame, fotografii cu tablă albă, imagini în alte limbi sau fișiere video și audio — graphify extrage concepte și relații din toate și le conectează într-un singur graf. Videoclipurile sunt transcrise local cu Whisper. Suportă 25 de limbaje de programare prin tree-sitter AST.
|
||||
|
||||
> Andrej Karpathy menține un folder `/raw` unde depune lucrări, tweet-uri, capturi de ecran și note. graphify este răspunsul la această problemă — **71,5x** mai puțini token pe interogare față de citirea fișierelor brute, persistent între sesiuni.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html graf interactiv — deschideți în orice browser
|
||||
├── GRAPH_REPORT.md noduri-zeu, conexiuni surprinzătoare, întrebări sugerate
|
||||
├── graph.json graf persistent — interogabil săptămâni mai târziu
|
||||
└── cache/ cache SHA256 — rulările repetate procesează doar fișierele modificate
|
||||
```
|
||||
|
||||
## Cum funcționează
|
||||
|
||||
graphify lucrează în trei treceri. Mai întâi, o trecere AST deterministă extrage structura din fișierele de cod fără LLM. Apoi fișierele video și audio sunt transcrise local cu faster-whisper. În final, sub-agenții Claude rulează în paralel pe documente, lucrări, imagini și transcrieri. Rezultatele sunt îmbinate într-un graf NetworkX, grupate cu Leiden și exportate ca HTML interactiv, JSON interogabil și raport de audit.
|
||||
|
||||
Fiecare relație este etichetată `EXTRACTED`, `INFERRED` (cu scor de încredere) sau `AMBIGUOUS`.
|
||||
|
||||
## Instalare
|
||||
|
||||
**Cerințe:** Python 3.10+ și unul din: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) și altele.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# sau cu pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# sau pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Pachet oficial:** Pachetul PyPI se numește `graphifyy`. Singurul depozit oficial este [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Utilizare
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "ce conectează Attention cu optimizatorul?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Ce obțineți
|
||||
|
||||
**Noduri-zeu** — concepte cu cel mai mare grad · **Conexiuni surprinzătoare** — clasificate după scor · **Întrebări sugerate** · **„De ce"** — docstring-uri și raționale de design extrase ca noduri · **Benchmark token** — **71,5x** mai puțini token pe corpus mixt.
|
||||
|
||||
## Confidențialitate
|
||||
|
||||
Fișierele de cod sunt procesate local prin tree-sitter AST. Videoclipurile sunt transcrise local cu faster-whisper. Fără telemetrie.
|
||||
|
||||
## Construit pe graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) este stratul enterprise peste graphify. **Perioadă de probă gratuită în curând.** [Alăturați-vă listei de așteptare →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,170 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></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>
|
||||
</p>
|
||||
|
||||
**Навык для AI-ассистента по написанию кода.** Введите `/graphify` в Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro или Google Antigravity — он прочитает ваши файлы, построит граф знаний и вернёт вам структуру, о существовании которой вы не подозревали. Понимайте кодовую базу быстрее. Находите «почему» за архитектурными решениями.
|
||||
|
||||
Полностью мультимодальный. Добавляйте код, PDF, markdown, скриншоты, диаграммы, фотографии досок, изображения на других языках, видео и аудиофайлы — graphify извлекает концепции и связи из всего этого и объединяет их в один граф. Видео транскрибируются локально с Whisper, используя доменный промпт из вашего корпуса. Поддерживается 25 языков программирования через tree-sitter AST (Python, JS, TS, Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Lua, Zig, PowerShell, Elixir, Objective-C, Julia, Verilog, SystemVerilog, Vue, Svelte, Dart).
|
||||
|
||||
> Андрей Карпати ведёт папку `/raw`, куда складывает статьи, твиты, скриншоты и заметки. graphify — ответ на эту проблему: в **71,5 раза** меньше токенов на запрос по сравнению с чтением сырых файлов, сохранение между сессиями, честность относительно того, что найдено, а что выведено.
|
||||
|
||||
```
|
||||
/graphify . # работает с любой папкой — код, заметки, статьи, всё что угодно
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html интерактивный граф — открыть в браузере, кликать по узлам, искать, фильтровать
|
||||
├── GRAPH_REPORT.md бог-узлы, неожиданные связи, предлагаемые вопросы
|
||||
├── graph.json постоянный граф — запрашивать через недели без повторного чтения
|
||||
└── cache/ SHA256-кэш — повторные запуски обрабатывают только изменённые файлы
|
||||
```
|
||||
|
||||
Добавьте файл `.graphifyignore` для исключения папок:
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
vendor/
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
```
|
||||
|
||||
Синтаксис аналогичен `.gitignore`.
|
||||
|
||||
## Как это работает
|
||||
|
||||
graphify работает в три прохода. Сначала детерминированный AST-проход извлекает структуру из файлов кода (классы, функции, импорты, графы вызовов, docstrings, комментарии с обоснованием) — без LLM. Затем видео и аудиофайлы транскрибируются локально с faster-whisper. Наконец, Claude-субагенты запускаются параллельно над документами, статьями, изображениями и транскриптами для извлечения концепций, связей и обоснований дизайна. Результаты объединяются в граф NetworkX, кластеризуются с помощью Leiden-детекции сообществ и экспортируются как интерактивный HTML, запрашиваемый JSON и аудит-отчёт на естественном языке.
|
||||
|
||||
**Кластеризация основана на топологии графа — без эмбеддингов.** Leiden находит сообщества по плотности рёбер. Рёбра семантического сходства, извлечённые Claude (`semantically_similar_to`, помечены как INFERRED), уже в графе. Структура графа — это сигнал сходства. Отдельный шаг с эмбеддингами или векторная база данных не нужны.
|
||||
|
||||
Каждая связь помечена как `EXTRACTED` (найдена непосредственно в источнике), `INFERRED` (обоснованный вывод с оценкой уверенности) или `AMBIGUOUS` (помечена для проверки).
|
||||
|
||||
## Установка
|
||||
|
||||
**Требования:** Python 3.10+ и одно из: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com), [Gemini CLI](https://github.com/google-gemini/gemini-cli), [GitHub Copilot CLI](https://docs.github.com/en/copilot/how-tos/copilot-cli), [VS Code Copilot Chat](https://code.visualstudio.com/docs/copilot/overview), [Aider](https://aider.chat), [OpenClaw](https://openclaw.ai), [Factory Droid](https://factory.ai), [Trae](https://trae.ai), [Kiro](https://kiro.dev), Hermes или [Google Antigravity](https://antigravity.google)
|
||||
|
||||
```bash
|
||||
# Рекомендуется — работает на Mac и Linux без настройки PATH
|
||||
uv tool install graphifyy && graphify install
|
||||
# или с pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# или обычный pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Официальный пакет:** Пакет PyPI называется `graphifyy` (установить через `pip install graphifyy`). Другие пакеты с именем `graphify*` на PyPI не связаны с этим проектом. Единственный официальный репозиторий — [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
### Поддержка платформ
|
||||
|
||||
| Платформа | Команда установки |
|
||||
|-----------|-------------------|
|
||||
| Claude Code (Linux/Mac) | `graphify install` |
|
||||
| Claude Code (Windows) | `graphify install` (авто-определение) или `graphify install --platform windows` |
|
||||
| Codex | `graphify install --platform codex` |
|
||||
| OpenCode | `graphify install --platform opencode` |
|
||||
| GitHub Copilot CLI | `graphify install --platform copilot` |
|
||||
| VS Code Copilot Chat | `graphify vscode install` |
|
||||
| Aider | `graphify install --platform aider` |
|
||||
| OpenClaw | `graphify install --platform claw` |
|
||||
| Factory Droid | `graphify install --platform droid` |
|
||||
| Trae | `graphify install --platform trae` |
|
||||
| Trae CN | `graphify install --platform trae-cn` |
|
||||
| Gemini CLI | `graphify install --platform gemini` |
|
||||
| Hermes | `graphify install --platform hermes` |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
Затем откройте AI-ассистент и введите:
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
Примечание: Codex использует `$` вместо `/` для навыков, поэтому вводите `$graphify .`.
|
||||
|
||||
### Заставить ассистента всегда использовать граф (рекомендуется)
|
||||
|
||||
После построения графа выполните это один раз в вашем проекте:
|
||||
|
||||
| Платформа | Команда |
|
||||
|-----------|---------|
|
||||
| Claude Code | `graphify claude install` |
|
||||
| Codex | `graphify codex install` |
|
||||
| OpenCode | `graphify opencode install` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Gemini CLI | `graphify gemini install` |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
## Использование
|
||||
|
||||
```
|
||||
/graphify # текущая директория
|
||||
/graphify ./raw # конкретная папка
|
||||
/graphify ./raw --mode deep # более агрессивное извлечение INFERRED-рёбер
|
||||
/graphify ./raw --update # повторно извлечь только изменённые файлы
|
||||
/graphify ./raw --directed # направленный граф
|
||||
/graphify ./raw --cluster-only # перезапустить кластеризацию на существующем графе
|
||||
/graphify ./raw --no-viz # без HTML, только отчёт + JSON
|
||||
/graphify ./raw --obsidian # создать Obsidian vault (opt-in)
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # получить статью
|
||||
/graphify add <video-url> # скачать аудио, транскрибировать, добавить
|
||||
/graphify query "что связывает Attention с оптимизатором?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
graphify hook install # установить Git-хуки
|
||||
graphify update ./src # повторно извлечь файлы кода, без LLM
|
||||
graphify watch ./src # автоматическое обновление графа
|
||||
```
|
||||
|
||||
## Что вы получаете
|
||||
|
||||
**Бог-узлы** — концепции с наибольшей степенью (через которые проходит всё)
|
||||
|
||||
**Неожиданные связи** — отсортированы по составному баллу. Рёбра код-статья получают более высокий рейтинг. Каждый результат содержит объяснение «почему» на естественном языке.
|
||||
|
||||
**Предлагаемые вопросы** — 4-5 вопросов, на которые граф уникально способен ответить
|
||||
|
||||
**«Почему»** — docstrings, встроенные комментарии (`# NOTE:`, `# IMPORTANT:`, `# HACK:`, `# WHY:`), и обоснования дизайна из документов извлекаются как узлы `rationale_for`.
|
||||
|
||||
**Оценки уверенности** — каждое INFERRED-ребро имеет `confidence_score` (0,0-1,0).
|
||||
|
||||
**Бенчмарк токенов** — выводится автоматически после каждого запуска. На смешанном корпусе: **71,5-кратное** сокращение токенов на запрос vs сырые файлы.
|
||||
|
||||
**Авто-синхронизация** (`--watch`) — обновляет граф автоматически при изменении кода.
|
||||
|
||||
**Git-хуки** (`graphify hook install`) — устанавливает post-commit и post-checkout хуки.
|
||||
|
||||
## Конфиденциальность
|
||||
|
||||
graphify отправляет содержимое файлов в API модели вашего AI-ассистента для семантического извлечения из документов, статей и изображений. Файлы кода обрабатываются локально через tree-sitter AST. Видео и аудиофайлы транскрибируются локально с faster-whisper. Никакой телеметрии, никакого отслеживания использования.
|
||||
|
||||
## Технологический стек
|
||||
|
||||
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Семантическое извлечение через Claude, GPT-4 или модель вашей платформы. Транскрипция видео через faster-whisper + yt-dlp (опционально).
|
||||
|
||||
## Построено на graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) — корпоративный слой поверх graphify. Там, где graphify превращает папку с файлами в граф знаний, Penpax применяет тот же граф ко всей вашей рабочей жизни — непрерывно.
|
||||
|
||||
**Бесплатный пробный период скоро.** [Вступить в список ожидания →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
## История звёзд
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**En färdighet för AI-kodassistenter.** Skriv `/graphify` i Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro eller Google Antigravity — den läser dina filer, bygger ett kunskapsgrafer och ger tillbaka strukturen du inte visste fanns. Förstå en kodbas snabbare. Hitta "varför" bakom arkitekturella beslut.
|
||||
|
||||
Helt multimodal. Lägg till kod, PDF:er, markdown, skärmdumpar, diagram, whiteboardfoton, bilder på andra språk eller video- och ljudfiler — graphify extraherar begrepp och relationer från allt och kopplar samman dem i ett enda graf. Videor transkriberas lokalt med Whisper. Stödjer 25 programmeringsspråk via tree-sitter AST.
|
||||
|
||||
> Andrej Karpathy håller en `/raw`-mapp där han lägger papper, tweets, skärmdumpar och anteckningar. graphify är svaret på det problemet — **71,5x** färre tokens per fråga jämfört med att läsa råfiler, beständigt mellan sessioner.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html interaktivt diagram — öppna i valfri webbläsare
|
||||
├── GRAPH_REPORT.md gudnoder, överraskande kopplingar, föreslagna frågor
|
||||
├── graph.json beständigt diagram — kan frågas veckor senare
|
||||
└── cache/ SHA256-cache — upprepade körningar behandlar bara ändrade filer
|
||||
```
|
||||
|
||||
## Hur det fungerar
|
||||
|
||||
graphify arbetar i tre pass. Först extraherar ett deterministiskt AST-pass struktur från kodfiler utan LLM. Sedan transkriberas video- och ljudfiler lokalt med faster-whisper. Slutligen kör Claude-subagenter parallellt på dokument, papper, bilder och transkriptioner. Resultaten slås samman i ett NetworkX-diagram, klustras med Leiden och exporteras som interaktiv HTML, frågebar JSON och revisionsrapport.
|
||||
|
||||
Varje relation är märkt `EXTRACTED`, `INFERRED` (med konfidenspoäng) eller `AMBIGUOUS`.
|
||||
|
||||
## Installation
|
||||
|
||||
**Krav:** Python 3.10+ och ett av: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) med flera.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# eller med pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# eller pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Officiellt paket:** PyPI-paketet heter `graphifyy`. Det enda officiella förrådet är [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Användning
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "vad kopplar Attention till optimizern?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Vad du får
|
||||
|
||||
**Gudnoder** — begrepp med högst grad · **Överraskande kopplingar** — rangordnade efter poäng · **Föreslagna frågor** · **"Varför"** — docsträngar och designmotivering extraherade som noder · **Token-benchmark** — **71,5x** färre tokens på blandat korpus.
|
||||
|
||||
## Integritet
|
||||
|
||||
Kodfiler behandlas lokalt via tree-sitter AST. Videor transkriberas lokalt med faster-whisper. Ingen telemetri.
|
||||
|
||||
## Byggt på graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) är enterprise-lagret ovanpå graphify. **Gratis provperiod kommer snart.** [Gå med i väntelistan →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**ทักษะสำหรับผู้ช่วยเขียนโค้ด AI** พิมพ์ `/graphify` ใน Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro หรือ Google Antigravity — มันจะอ่านไฟล์ของคุณ สร้างกราฟความรู้ และส่งคืนโครงสร้างที่คุณไม่รู้ว่ามีอยู่ ทำความเข้าใจ codebase ได้เร็วขึ้น ค้นหา "ทำไม" เบื้องหลังการตัดสินใจด้านสถาปัตยกรรม
|
||||
|
||||
มัลติโมดัลอย่างสมบูรณ์ เพิ่มโค้ด, PDF, markdown, ภาพหน้าจอ, ไดอะแกรม, ภาพถ่ายกระดานไวท์บอร์ด, รูปภาพในภาษาอื่น หรือไฟล์วิดีโอและเสียง — graphify ดึงแนวคิดและความสัมพันธ์จากทุกอย่างและเชื่อมต่อกันในกราฟเดียว วิดีโอถูกถอดเสียงในเครื่องด้วย Whisper รองรับ 25 ภาษาการเขียนโปรแกรมผ่าน tree-sitter AST
|
||||
|
||||
> Andrej Karpathy รักษาโฟลเดอร์ `/raw` ที่เขาวางงานวิจัย, ทวีต, ภาพหน้าจอ และบันทึก graphify คือคำตอบสำหรับปัญหานั้น — **71.5 เท่า** โทเค็นน้อยลงต่อการสืบค้นเมื่อเทียบกับการอ่านไฟล์ดิบ, ยั่งยืนระหว่างเซสชัน
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html กราฟแบบโต้ตอบ — เปิดในเบราว์เซอร์ใดก็ได้
|
||||
├── GRAPH_REPORT.md โหนดพระเจ้า, การเชื่อมต่อที่น่าประหลาดใจ, คำถามที่แนะนำ
|
||||
├── graph.json กราฟถาวร — สามารถสืบค้นได้หลายสัปดาห์ต่อมา
|
||||
└── cache/ SHA256-cache — การรันซ้ำประมวลผลเฉพาะไฟล์ที่เปลี่ยนแปลง
|
||||
```
|
||||
|
||||
## วิธีการทำงาน
|
||||
|
||||
graphify ทำงานใน 3 รอบ ก่อนอื่น AST pass แบบ deterministic ดึงโครงสร้างจากไฟล์โค้ดโดยไม่ต้องใช้ LLM จากนั้นไฟล์วิดีโอและเสียงถูกถอดเสียงในเครื่องด้วย faster-whisper สุดท้าย Claude sub-agent ทำงานแบบขนานกันบนเอกสาร, งานวิจัย, รูปภาพ และบทถอดเสียง ผลลัพธ์ถูกรวมเข้ากับกราฟ NetworkX, จัดกลุ่มด้วย Leiden และส่งออกเป็น HTML แบบโต้ตอบ, JSON ที่สืบค้นได้ และรายงานการตรวจสอบ
|
||||
|
||||
ความสัมพันธ์แต่ละอย่างถูกติดป้าย `EXTRACTED`, `INFERRED` (พร้อมคะแนนความเชื่อมั่น) หรือ `AMBIGUOUS`
|
||||
|
||||
## การติดตั้ง
|
||||
|
||||
**ข้อกำหนด:** Python 3.10+ และหนึ่งใน: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) และอื่นๆ
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# หรือกับ pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# หรือ pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **แพ็กเกจอย่างเป็นทางการ:** แพ็กเกจ PyPI ชื่อ `graphifyy` repository อย่างเป็นทางการเดียวคือ [safishamsi/graphify](https://github.com/safishamsi/graphify)
|
||||
|
||||
## การใช้งาน
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "อะไรเชื่อม Attention กับ optimizer?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## สิ่งที่คุณได้รับ
|
||||
|
||||
**โหนดพระเจ้า** — แนวคิดที่มีระดับสูงสุด · **การเชื่อมต่อที่น่าประหลาดใจ** — จัดอันดับตามคะแนน · **คำถามที่แนะนำ** · **"ทำไม"** — docstring และเหตุผลการออกแบบที่ดึงออกมาเป็นโหนด · **เกณฑ์มาตรฐานโทเค็น** — **71.5 เท่า** โทเค็นน้อยลงบน corpus ผสม
|
||||
|
||||
## ความเป็นส่วนตัว
|
||||
|
||||
ไฟล์โค้ดถูกประมวลผลในเครื่องผ่าน tree-sitter AST วิดีโอถูกถอดเสียงในเครื่องด้วย faster-whisper ไม่มีการส่งข้อมูลวัดผล
|
||||
|
||||
## สร้างบน graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) คือชั้น enterprise เหนือ graphify **ทดลองใช้ฟรีเร็วๆ นี้** [เข้าร่วมรายชื่อรอ →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**Yapay zeka kod asistanları için bir beceri.** Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro veya Google Antigravity'de `/graphify` yazın — dosyalarınızı okur, bir bilgi grafiği oluşturur ve farkında olmadığınız yapıyı size geri verir. Kod tabanını daha hızlı anlayın. Mimari kararların arkasındaki "neden"i bulun.
|
||||
|
||||
Tamamen çok modlu. Kod, PDF, markdown, ekran görüntüleri, diyagramlar, beyaz tahta fotoğrafları, başka dillerdeki görüntüler veya video ve ses dosyaları ekleyin — graphify her şeyden kavramları ve ilişkileri çıkarır ve bunları tek bir grafikte birleştirir. Videolar Whisper ile yerel olarak transkribe edilir. tree-sitter AST aracılığıyla 25 programlama dilini destekler.
|
||||
|
||||
> Andrej Karpathy, makaleleri, tweetleri, ekran görüntülerini ve notları bıraktığı bir `/raw` klasörü tutar. graphify bu soruna yanıttır — ham dosyaları okumaya kıyasla sorgu başına **71,5x** daha az token, oturumlar arasında kalıcı.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html etkileşimli grafik — herhangi bir tarayıcıda açın
|
||||
├── GRAPH_REPORT.md tanrı düğümleri, şaşırtıcı bağlantılar, önerilen sorular
|
||||
├── graph.json kalıcı grafik — haftalar sonra sorgulanabilir
|
||||
└── cache/ SHA256 önbelleği — tekrarlanan çalışmalar yalnızca değiştirilen dosyaları işler
|
||||
```
|
||||
|
||||
## Nasıl çalışır
|
||||
|
||||
graphify üç geçişte çalışır. Önce deterministik bir AST geçişi, LLM olmadan kod dosyalarından yapı çıkarır. Ardından video ve ses dosyaları faster-whisper ile yerel olarak transkribe edilir. Son olarak Claude alt ajanları belgeler, makaleler, görüntüler ve transkriptler üzerinde paralel olarak çalışır. Sonuçlar bir NetworkX grafiğinde birleştirilir, Leiden ile kümelenir ve etkileşimli HTML, sorgulanabilir JSON ve denetim raporu olarak dışa aktarılır.
|
||||
|
||||
Her ilişki `EXTRACTED`, `INFERRED` (güven puanıyla) veya `AMBIGUOUS` olarak etiketlenir.
|
||||
|
||||
## Kurulum
|
||||
|
||||
**Gereksinimler:** Python 3.10+ ve şunlardan biri: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) ve diğerleri.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# veya pipx ile
|
||||
pipx install graphifyy && graphify install
|
||||
# veya pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Resmi paket:** PyPI paketi `graphifyy` olarak adlandırılır. Tek resmi depo [safishamsi/graphify](https://github.com/safishamsi/graphify)'dir.
|
||||
|
||||
## Kullanım
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "Attention'ı optimizer'a ne bağlıyor?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Ne elde edersiniz
|
||||
|
||||
**Tanrı düğümleri** — en yüksek dereceli kavramlar · **Şaşırtıcı bağlantılar** — puana göre sıralanmış · **Önerilen sorular** · **"Neden"** — doküman dizileri ve tasarım gerekçeleri düğümler olarak çıkarılır · **Token kıyaslaması** — karma derlemede **71,5x** daha az token.
|
||||
|
||||
## Gizlilik
|
||||
|
||||
Kod dosyaları tree-sitter AST aracılığıyla yerel olarak işlenir. Videolar faster-whisper ile yerel olarak transkribe edilir. Telemetri yok.
|
||||
|
||||
## graphify üzerine inşa edildi — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai), graphify üzerindeki kurumsal katmandır. **Ücretsiz deneme yakında.** [Bekleme listesine katılın →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,592 @@
|
||||
<p align="center">
|
||||
<a href="https://graphifylabs.ai"><img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://www.ycombinator.com/companies/graphify"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
<a href="https://safishamsi.gumroad.com/l/qetvlo"><img src="https://img.shields.io/badge/Book-The%20Memory%20Layer-2ea44f?style=flat&logo=gitbook&logoColor=white" alt="The Memory Layer"/></a>
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://clickpy.clickhouse.com/dashboard/graphifyy"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fsql-clickhouse.clickhouse.com%2F%3Fquery%3DSELECT%2520concat%2528toString%2528round%2528sum%2528count%2529%2F1000%2529%2529%2C%2520%2527k%2527%2529%2520AS%2520c%2520FROM%2520pypi.pypi_downloads%2520WHERE%2520project%253D%2527graphifyy%2527%2520FORMAT%2520JSON%26user%3Ddemo&query=%24.data%5B0%5D.c&label=downloads&color=blue" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></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://x.com/graphifyy"><img src="https://img.shields.io/badge/X-graphifyy-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://star-history.com/#safishamsi/graphify&Date">
|
||||
<img src="https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date" alt="Star History Chart" width="370"/>
|
||||
</a>
|
||||
</p>
|
||||
|
||||
Введіть `/graphify` у своєму ШІ-асистенті для кодингу, і він нанесе весь ваш проект — код, документи, PDF, зображення, відео — на граф знань, який можна запитувати замість того, щоб шукати по файлах.
|
||||
|
||||
Працює в Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kimi Code, Kiro, Pi та Google Antigravity.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
Це все. Ви отримуєте три файли:
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html відкрийте в будь-якому браузері — клікайте по вузлах, фільтруйте, шукайте
|
||||
├── GRAPH_REPORT.md основне: ключові концепції, неочікувані зв’язки, запропоновані запитання
|
||||
└── graph.json повний граф — запитуйте його будь-коли без повторного перечитування ваших файлів
|
||||
```
|
||||
|
||||
Для читабельної сторінки архітектури з діаграмами викликів Mermaid виконайте:
|
||||
|
||||
```bash
|
||||
graphify export callflow-html
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Вимоги
|
||||
|
||||
| Вимога | Мінімум | Перевірка | Встановлення |
|
||||
|---|---|---|---|
|
||||
| Python | 3.10+ | `python --version` | [python.org](https://www.python.org/downloads/) |
|
||||
| uv *(рекомендовано)* | будь-яка | `uv --version` | `curl -LsSf https://astral.sh/uv/install.sh \| sh` |
|
||||
| pipx *(альтернатива)* | будь-яка | `pipx --version` | `pip install pipx` |
|
||||
|
||||
**Швидке встановлення на macOS (Homebrew):**
|
||||
```bash
|
||||
brew install python@3.12 uv
|
||||
```
|
||||
|
||||
**Швидке встановлення на Windows:**
|
||||
```powershell
|
||||
winget install astral-sh.uv
|
||||
```
|
||||
|
||||
**Ubuntu/Debian:**
|
||||
```bash
|
||||
sudo apt install python3.12 python3-pip pipx
|
||||
# або встановити uv:
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Встановлення
|
||||
|
||||
> **Офіційний пакет:** Пакет PyPI — `graphifyy` (подвійна y). Інші пакети `graphify*` на PyPI не є афілійованими. Команда CLI залишається `graphify`.
|
||||
|
||||
**Крок 1 — встановити пакет:**
|
||||
|
||||
```bash
|
||||
# Рекомендовано (uv автоматично додає graphify до PATH):
|
||||
uv tool install graphifyy
|
||||
|
||||
# Альтернативи:
|
||||
pipx install graphifyy
|
||||
pip install graphifyy
|
||||
```
|
||||
|
||||
**Крок 2 — зареєструвати навичку у вашому ШІ-асистенті:**
|
||||
|
||||
```bash
|
||||
graphify install
|
||||
```
|
||||
|
||||
Це все. Відкрийте асистента і введіть `/graphify .`
|
||||
|
||||
Щоб встановити навичку в поточний репозиторій замість профілю користувача, додайте `--project`:
|
||||
|
||||
```bash
|
||||
graphify install --project
|
||||
graphify install --project --platform codex
|
||||
```
|
||||
|
||||
Встановлення на рівні проєкту записуються в поточну директорію, наприклад .claude/skills/graphify/SKILL.md або .agents/skills/graphify/SKILL.md, і виводять підказку git add для файлів, які можна закомітити. Команди для окремих платформ, що підтримують інсталяції на рівні проєкту, приймають той самий прапорець, наприклад graphify claude install --project або graphify codex install --project.
|
||||
|
||||
> **Примітка для PowerShell:** Використовуйте `graphify .` замість `/graphify .` — ведучий слеш є роздільником шляху в PowerShell.
|
||||
|
||||
> **`graphify: command not found`?** Використовуйте `uv tool install graphifyy` або `pipx install graphifyy` — обидва автоматично додають CLI до PATH. При використанні звичайного `pip` додайте `~/.local/bin` (Linux) або `~/Library/Python/3.x/bin` (Mac) до вашого PATH, або запустіть `python -m graphify`.
|
||||
|
||||
### Оберіть платформу
|
||||
|
||||
| Платформа | Команда встановлення |
|
||||
|----------|----------------|
|
||||
| Claude Code (Linux/Mac) | `graphify install` |
|
||||
| Claude Code (Windows) | `graphify install --platform windows` |
|
||||
| Codex | `graphify install --platform codex` |
|
||||
| OpenCode | `graphify install --platform opencode` |
|
||||
| GitHub Copilot CLI | `graphify install --platform copilot` |
|
||||
| VS Code Copilot Chat | `graphify vscode install` |
|
||||
| Aider | `graphify install --platform aider` |
|
||||
| OpenClaw | `graphify install --platform claw` |
|
||||
| Factory Droid | `graphify install --platform droid` |
|
||||
| Trae | `graphify install --platform trae` |
|
||||
| Trae CN | `graphify install --platform trae-cn` |
|
||||
| Gemini CLI | `graphify install --platform gemini` |
|
||||
| Hermes | `graphify install --platform hermes` |
|
||||
| Kimi Code | `graphify install --platform kimi` |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Pi coding agent | `graphify install --platform pi` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
> Користувачам Codex: також додайте `multi_agent = true` під `[features]` у `~/.codex/config.toml`.
|
||||
> Codex використовує `$graphify` замість `/graphify`.
|
||||
|
||||
### Додаткові пакети (опціонально)
|
||||
|
||||
Встановіть лише те, що потрібно:
|
||||
|
||||
| Пакет | Що додає | Встановлення |
|
||||
|---|---|---|
|
||||
| `pdf` | Вилучення PDF | `pip install "graphifyy[pdf]"` |
|
||||
| `office` | Підтримка `.docx` та `.xlsx` | `pip install "graphifyy[office]"` |
|
||||
| `google` | Рендеринг Google Sheets | `pip install "graphifyy[google]"` |
|
||||
| `video` | Транскрипція відео/аудіо (faster-whisper + yt-dlp) | `pip install "graphifyy[video]"` |
|
||||
| `mcp` | MCP stdio-сервер | `pip install "graphifyy[mcp]"` |
|
||||
| `neo4j` | Підтримка надсилання до Neo4j | `pip install "graphifyy[neo4j]"` |
|
||||
| `svg` | Експорт графу в SVG | `pip install "graphifyy[svg]"` |
|
||||
| `leiden` | Виявлення спільнот Leiden (лише Python < 3.13) | `pip install "graphifyy[leiden]"` |
|
||||
| `ollama` | Локальний вивід Ollama | `pip install "graphifyy[ollama]"` |
|
||||
| `openai` | OpenAI / OpenAI-сумісні API | `pip install "graphifyy[openai]"` |
|
||||
| `gemini` | Google Gemini API | `pip install "graphifyy[gemini]"` |
|
||||
| `bedrock` | AWS Bedrock (використовує IAM, без API-ключа) | `pip install "graphifyy[bedrock]"` |
|
||||
| `sql` | Вилучення SQL схем | `pip install "graphifyy[sql]"` |
|
||||
| `all` | Все вищезазначене | `pip install "graphifyy[all]"` |
|
||||
|
||||
---
|
||||
|
||||
## Змусьте асистента завжди використовувати граф
|
||||
|
||||
Виконайте один раз у своєму проекті після побудови графу:
|
||||
|
||||
| Платформа | Команда |
|
||||
|----------|---------|
|
||||
| Claude Code | `graphify claude install` |
|
||||
| Codex | `graphify codex install` |
|
||||
| OpenCode | `graphify opencode install` |
|
||||
| GitHub Copilot CLI | `graphify copilot install` |
|
||||
| VS Code Copilot Chat | `graphify vscode install` |
|
||||
| Aider | `graphify aider install` |
|
||||
| OpenClaw | `graphify claw install` |
|
||||
| Factory Droid | `graphify droid install` |
|
||||
| Trae | `graphify trae install` |
|
||||
| Trae CN | `graphify trae-cn install` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Gemini CLI | `graphify gemini install` |
|
||||
| Hermes | `graphify hermes install` |
|
||||
| Kimi Code | `graphify install --platform kimi` |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Pi coding agent | `graphify pi install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
Це записує невеликий конфігураційний файл, який каже асистенту звертатися до графу знань для питань про кодову базу — надаючи перевагу локалізованим запитам на кшталт `graphify query "<питання>"` замість читання повного звіту або пошуку по сирих файлах. На платформах, що підтримують хуки з корисним навантаженням (Claude Code, Gemini CLI), хук спрацьовує автоматично перед пошуковими викликами інструментів і спрямовує асистента до графу. На інших (Codex, OpenCode, Cursor тощо) постійні файли інструкцій (`AGENTS.md`, `.cursor/rules/` тощо) забезпечують таке саме керівництво. `GRAPH_REPORT.md` все ще доступний для загального огляду архітектури.
|
||||
|
||||
Щоб видалити graphify з усіх платформ одразу: `graphify uninstall` (додайте `--purge`, щоб також видалити `graphify-out/`). Або скористайтеся командою для конкретної платформи (напр. `graphify claude uninstall`).
|
||||
|
||||
---
|
||||
|
||||
## Що є у звіті
|
||||
|
||||
- **Вузли-боги** — найбільш пов'язані концепції у вашому проекті. Через них проходить все.
|
||||
- **Несподівані зв'язки** — зв'язки між речами з різних файлів або модулів. Відсортовані за ступенем несподіваності.
|
||||
- **«Чому»** — рядкові коментарі (`# NOTE:`, `# WHY:`, `# HACK:`), рядки документації та обґрунтування дизайну з документів витягуються як окремі вузли, пов'язані з кодом, який вони пояснюють.
|
||||
- **Запропоновані питання** — 4–5 питань, на які граф унікально здатний відповісти.
|
||||
- **Теги впевненості** — кожен виведений зв'язок позначений як `EXTRACTED`, `INFERRED` або `AMBIGUOUS`. Ви завжди знаєте, що знайдено, а що виведено.
|
||||
|
||||
---
|
||||
|
||||
## Які файли підтримуються
|
||||
|
||||
| Тип | Розширення |
|
||||
|------|-----------|
|
||||
| Код (31 мова) | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .h .hpp .rb .cs .kt .scala .php .swift .lua .luau .zig .ps1 .ex .exs .m .mm .jl .vue .svelte .astro .groovy .gradle .dart .v .sv .sql .f .f90 .f95 .f03 .f08 .pas .pp .dpr .dpk .lpr .inc .dfm .lfm .lpk .sh .bash .json` |
|
||||
| Документи | `.md .mdx .qmd .html .txt .rst .yaml .yml` |
|
||||
| Office | `.docx .xlsx` (потрібен `pip install graphifyy[office]`) |
|
||||
| Google Workspace | `.gdoc .gsheet .gslides` (опціонально; потрібна автентифікація `gws` та `--google-workspace`; Sheets потребує `pip install graphifyy[google]`) |
|
||||
| PDF | `.pdf` |
|
||||
| Зображення | `.png .jpg .webp .gif` |
|
||||
| Відео / Аудіо | `.mp4 .mov .mp3 .wav` та інші (потрібен `pip install graphifyy[video]`) |
|
||||
| YouTube / URL | будь-який URL відео (потрібен `pip install graphifyy[video]`) |
|
||||
|
||||
Код витягується локально без API-викликів (AST через tree-sitter). Все інше обробляється через API моделі вашого ШІ-асистента.
|
||||
|
||||
Файли `.gdoc`, `.gsheet` та `.gslides` з Google Drive for desktop — це ярлики-посилання, а не вміст документів. Щоб включити нативні Google Docs, Sheets та Slides у безголове витягування, встановіть та автентифікуйте [`gws` CLI](https://github.com/googleworkspace/cli), потім запустіть:
|
||||
|
||||
```bash
|
||||
pip install "graphifyy[google]" # потрібен для рендерингу таблиць Google Sheets
|
||||
gws auth login -s drive
|
||||
graphify extract ./docs --google-workspace
|
||||
```
|
||||
|
||||
Також можна встановити `GRAPHIFY_GOOGLE_WORKSPACE=1`. Graphify експортує ярлики в `graphify-out/converted/` як Markdown-сайдкари, а потім витягує ці файли.
|
||||
|
||||
---
|
||||
|
||||
## Часті команди
|
||||
|
||||
```bash
|
||||
/graphify . # побудувати граф для поточної папки
|
||||
/graphify ./docs --update # повторно витягнути лише змінені файли
|
||||
/graphify . --cluster-only # перезапустити кластеризацію без повторного витягування
|
||||
/graphify . --cluster-only --resolution 1.5 # більш дрібні спільноти
|
||||
/graphify . --cluster-only --exclude-hubs 99 # виключити утилітарні суперхаби з рейтингів “god-node” вузлів-богів
|
||||
/graphify . --no-viz # пропустити HTML, лише звіт + JSON
|
||||
/graphify . --wiki # побудувати markdown-вікі з графу
|
||||
graphify export callflow-html # Mermaid архітектура/flow-викликів HTML (автоматично регенерується на кожен git-коміт, якщо встановлений hook)
|
||||
|
||||
/graphify query "що пов'язує auth з базою даних?"
|
||||
/graphify path "UserService" "DatabasePool"
|
||||
/graphify explain "RateLimiter"
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # завантажити статтю і додати її
|
||||
/graphify add <youtube-url> # транскрибувати і додати відео
|
||||
|
||||
graphify hook install # автоматичне перебудування при git-коміті
|
||||
graphify merge-graphs a.json b.json # об'єднати два графи
|
||||
|
||||
graphify prs # дашборд PR: стан CI, статус рев’ю, мапінг worktree
|
||||
graphify prs 42 # детальний огляд PR #42 з впливом на граф
|
||||
graphify prs --triage # ШІ оцінює вашу чергу рев’ю (використовує будь-який налаштований бекенд)
|
||||
graphify prs --conflicts # PR-и, що ділять спільні графові спільноти — ризик порядку злиття
|
||||
```
|
||||
|
||||
Дивіться [повний довідник команд](#повний-довідник-команд) нижче.
|
||||
|
||||
---
|
||||
|
||||
## Ігнорування файлів
|
||||
|
||||
Створіть `.graphifyignore` у кореневій директорії проекту — той самий синтаксис, що й `.gitignore`, включно з запереченням `!`:
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
|
||||
# індексувати лише src/, ігнорувати все інше
|
||||
*
|
||||
!src/
|
||||
!src/**
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Налаштування для команди
|
||||
|
||||
`graphify-out/` призначений для коміту в git, щоб кожен у команді починав із картою.
|
||||
|
||||
**Рекомендовані доповнення до `.gitignore`:**
|
||||
```
|
||||
graphify-out/manifest.json # базується на mtime, ламається після git clone
|
||||
graphify-out/cost.json # лише локальний
|
||||
# graphify-out/cache/ # опціонально: комітьте для швидкості, пропустіть для меншого репо
|
||||
```
|
||||
|
||||
**Робочий процес:**
|
||||
1. Одна людина запускає `/graphify .` і комітить `graphify-out/`.
|
||||
2. Усі виконують pull — їхній асистент одразу читає граф.
|
||||
3. Запустіть `graphify hook install` для автоматичного перебудування після кожного коміту (лише AST, без витрат API). Це також налаштовує git merge driver, щоб `graph.json` ніколи не залишався з маркерами конфліктів — два розробники, що комітять одночасно, отримають автоматично об'єднані графи.
|
||||
4. Коли документи або статті змінюються, запустіть `/graphify --update`, щоб оновити ці вузли.
|
||||
|
||||
---
|
||||
|
||||
## Використання графу напряму
|
||||
|
||||
```bash
|
||||
# запит до графу з терміналу
|
||||
graphify query "покажи потік автентифікації"
|
||||
graphify query "що пов'язує DigestAuth з Response?" --graph graphify-out/graph.json
|
||||
|
||||
# відкрити граф як MCP-сервер (для повторного доступу через інструменти)
|
||||
python -m graphify.serve graphify-out/graph.json
|
||||
|
||||
# зареєструвати в Kimi Code:
|
||||
kimi mcp add --transport stdio graphify -- python -m graphify.serve graphify-out/graph.json
|
||||
```
|
||||
|
||||
MCP-сервер надає асистенту структурований доступ: `query_graph`, `get_node`, `get_neighbors`, `shortest_path`, `list_prs`, `get_pr_impact`, `triage_prs`.
|
||||
|
||||
> **Примітка для WSL / Linux:** Ubuntu постачає `python3`, а не `python`. Використовуйте venv, щоб уникнути конфліктів:
|
||||
> ```bash
|
||||
> python3 -m venv .venv && .venv/bin/pip install "graphifyy[mcp]"
|
||||
> ```
|
||||
|
||||
---
|
||||
|
||||
## Змінні середовища
|
||||
|
||||
Потрібні лише для **headless / CI витягування** (`graphify extract`). При запуску через навичку `/graphify` у вашому IDE API моделі надається сесією IDE — додаткових ключів не потрібно.
|
||||
|
||||
| Змінна | Використання | Коли потрібна |
|
||||
|---|---|---|
|
||||
| `ANTHROPIC_API_KEY` | Backend Claude (Anthropic) | `--backend claude` |
|
||||
| `ANTHROPIC_BASE_URL` | URL Anthropic-сумісного endpoint (LiteLLM proxy, шлюзи, ...) | `--backend claude` (типово: `https://api.anthropic.com`) |
|
||||
| `ANTHROPIC_MODEL` | Назва моделі для backend Claude — для власних endpoint використовуйте назву/псевдонім моделі вашого сервера | `--backend claude` (типово: `claude-sonnet-4-6`) |
|
||||
| `GEMINI_API_KEY` або `GOOGLE_API_KEY` | Backend Google Gemini | `--backend gemini` |
|
||||
| `OPENAI_API_KEY` | OpenAI або OpenAI-сумісні API | `--backend openai` (локальні сервери приймають будь-яке непорожнє значення) |
|
||||
| `OPENAI_BASE_URL` | URL OpenAI-сумісного сервера (llama.cpp, vLLM, LM Studio, ...) | `--backend openai` (типово: `https://api.openai.com/v1`) |
|
||||
| `OPENAI_MODEL` | Назва моделі для backend OpenAI — для self-hosted серверів використовуйте назву/псевдонім моделі, яку надає ваш сервер (див. його endpoint `/v1/models`), напр. `LFM2.5-8B-A1B-UD-Q4_K_XL` для llama.cpp | `--backend openai` (типово: `gpt-4.1-mini`) |
|
||||
| `DEEPSEEK_API_KEY` | Backend DeepSeek | `--backend deepseek` |
|
||||
| `MOONSHOT_API_KEY` | Backend Kimi Code | `--backend kimi` |
|
||||
| `OLLAMA_BASE_URL` | URL локального виводу Ollama | `--backend ollama` (типово: `http://localhost:11434`) |
|
||||
| `OLLAMA_MODEL` | Назва моделі Ollama | `--backend ollama` (типово: автовизначення) |
|
||||
| `GRAPHIFY_OLLAMA_NUM_CTX` | Перевизначити розмір KV-кеш вікна Ollama | опціонально — автоматично за замовчуванням |
|
||||
| `GRAPHIFY_OLLAMA_KEEP_ALIVE` | Хвилини утримання моделі Ollama завантаженою | опціонально — встановіть `0` для вивантаження після кожного шматка |
|
||||
| `AWS_*` / `~/.aws/credentials` | AWS Bedrock — стандартний ланцюг облікових даних | `--backend bedrock` (без API-ключа, використовує IAM) |
|
||||
| `GRAPHIFY_MAX_WORKERS` | Кількість потоків паралелізму AST | опціонально — також прапор `--max-workers` |
|
||||
| `GRAPHIFY_MAX_OUTPUT_TOKENS` | Підвищити ліміт виводу для щільних корпусів | опціонально — напр. `32768` для великих файлів |
|
||||
| `GRAPHIFY_API_TIMEOUT` | HTTP тайм-аут у секундах (типово: 600) | опціонально — також прапор `--api-timeout` |
|
||||
| `GRAPHIFY_FORCE` | Примусове перебудування графу навіть із меншою кількістю вузлів | опціонально — також прапор `--force` |
|
||||
| `GRAPHIFY_GOOGLE_WORKSPACE` | Автоввімкнення експорту Google Workspace | опціонально — встановіть в `1` |
|
||||
| `GRAPHIFY_TRIAGE_BACKEND` | Backend для `graphify prs --triage` | опціонально — автовизначення з наявних ключів |
|
||||
| `GRAPHIFY_TRIAGE_MODEL` | Перевизначення моделі для triage | опціонально — напр. `claude-opus-4-7` |
|
||||
|
||||
---
|
||||
|
||||
## Конфіденційність
|
||||
|
||||
- **Файли коду** — обробляються локально через tree-sitter. Нічого не покидає ваш комп'ютер.
|
||||
- **Відео / аудіо** — транскрибуються локально за допомогою faster-whisper. Нічого не покидає ваш комп'ютер.
|
||||
- **Документи, PDF, зображення** — надсилаються до вашого ШІ-асистента для семантичного витягування (через навичку `/graphify`, використовуючи модель, що запущена у вашому IDE). Безголове `graphify extract` потребує `GEMINI_API_KEY` / `GOOGLE_API_KEY` (Gemini), `MOONSHOT_API_KEY` (Kimi), `ANTHROPIC_API_KEY` (Claude), `OPENAI_API_KEY` (OpenAI), `DEEPSEEK_API_KEY` (DeepSeek), запущеного екземпляра Ollama (`OLLAMA_BASE_URL`), AWS-облікових даних через стандартний ланцюг провайдерів (Bedrock — без API-ключа, використовує IAM) або бінарного файлу `claude` CLI (Claude Code — без API-ключа, використовує вашу підписку Claude). Прапор `--dedup-llm` використовує той самий ключ.
|
||||
- Без телеметрії, без відстеження використання, без аналітики.
|
||||
|
||||
---
|
||||
|
||||
## Вирішення проблем
|
||||
|
||||
**`graphify: command not found` після `pip install graphifyy`**
|
||||
pip встановлює скрипти в директорію bin для користувача, яка може не бути в PATH. Виправлення:
|
||||
- macOS: додайте `~/Library/Python/3.x/bin` до PATH у `~/.zshrc`
|
||||
- Linux: додайте `~/.local/bin` до PATH у `~/.bashrc`
|
||||
- Або використовуйте `uv tool install graphifyy` / `pipx install graphifyy` — обидва автоматично керують PATH.
|
||||
|
||||
**`python -m graphify` працює, але команда `graphify` — ні**
|
||||
PATH вашої оболонки не включає директорію скриптів Python. Використовуйте `uv` або `pipx` замість звичайного `pip`.
|
||||
|
||||
**`/graphify .` викликає "path not recognized" в PowerShell**
|
||||
PowerShell трактує ведучий `/` як роздільник шляху. Використовуйте `graphify .` (без слеша) на Windows.
|
||||
|
||||
**Граф має менше вузлів після `--update` або перебудови**
|
||||
Якщо рефакторинг видалив файли, старі вузли залишаються. Передайте `--force` (або встановіть `GRAPHIFY_FORCE=1`), щоб перезаписати навіть якщо перебудова має менше вузлів.
|
||||
|
||||
**Граф має дублікати вузлів для однієї сутності (фантомні дублікати)**
|
||||
Це трапляється, коли семантичне та AST-витягування не погодилось щодо формату ID вузла. Запустіть повне повторне витягування для очищення:
|
||||
```bash
|
||||
graphify extract . --force
|
||||
```
|
||||
|
||||
**Ollama вичерпує VRAM / перевищено вікно контексту**
|
||||
KV-кеш вікно автоматично розраховується, але може бути завеликим для вашого GPU. Зменшіть його:
|
||||
```bash
|
||||
GRAPHIFY_OLLAMA_NUM_CTX=8192 graphify extract ./docs --backend ollama --token-budget 4000
|
||||
```
|
||||
|
||||
**HTML графу занадто великий для відкриття в браузері (>5000 вузлів)**
|
||||
Пропустіть генерацію HTML і використовуйте JSON напряму:
|
||||
```bash
|
||||
graphify cluster-only ./my-project --no-viz
|
||||
graphify query "..."
|
||||
```
|
||||
|
||||
**`graph.json` має маркери конфліктів після одночасного коміту двох розробників**
|
||||
Запустіть `graphify hook install` — це налаштовує git merge driver, який автоматично об'єднує `graph.json`, щоб конфліктів ніколи не виникало.
|
||||
|
||||
**Вилучення повертає порожні вузли/ребра для документів або PDF**
|
||||
Документи та PDF потребують LLM-виклику. Перевірте, що API-ключ встановлено і backend правильний:
|
||||
```bash
|
||||
ANTHROPIC_API_KEY=sk-... graphify extract ./docs --backend claude
|
||||
```
|
||||
|
||||
**Попередження про невідповідність версій навички у вашому IDE**
|
||||
Встановлена версія graphify відрізняється від файлу навички. Оновіть:
|
||||
```bash
|
||||
uv tool upgrade graphifyy
|
||||
graphify install # перезаписує файл навички
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Повний довідник команд
|
||||
|
||||
```
|
||||
/graphify # запустити в поточному каталозі
|
||||
/graphify ./raw # запустити у конкретній папці
|
||||
/graphify ./raw --mode deep # більш агресивне витягування зв'язків
|
||||
/graphify ./raw --update # повторно витягнути лише змінені файли
|
||||
/graphify ./raw --directed # зберегти напрямок ребер
|
||||
/graphify ./raw --cluster-only # повторна кластеризація існуючого графу
|
||||
/graphify ./raw --no-viz # пропустити HTML-візуалізацію
|
||||
/graphify ./raw --obsidian # згенерувати сховище Obsidian
|
||||
/graphify ./raw --wiki # побудувати markdown-вікі для обходу агентами
|
||||
/graphify ./raw --svg # експортувати graph.svg
|
||||
/graphify ./raw --graphml # експортувати для Gephi / yEd
|
||||
/graphify ./raw --neo4j # згенерувати cypher.txt для Neo4j
|
||||
/graphify ./raw --neo4j-push bolt://localhost:7687
|
||||
/graphify ./raw --watch # автосинхронізація при зміні файлів
|
||||
/graphify ./raw --mcp # запустити MCP stdio-сервер
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762
|
||||
/graphify add <video-url>
|
||||
/graphify add https://... --author "Name" --contributor "Name"
|
||||
|
||||
/graphify query "що пов'язує attention з optimizer?"
|
||||
/graphify query "..." --dfs --budget 1500
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
graphify uninstall # видалити з усіх платформ одразу
|
||||
graphify uninstall --purge # також видалити graphify-out/
|
||||
graphify uninstall --project --platform codex # видалити лише файли проектного встановлення
|
||||
|
||||
graphify hook install # хуки post-commit + post-checkout
|
||||
graphify hook uninstall
|
||||
graphify hook status
|
||||
|
||||
graphify claude install / uninstall
|
||||
graphify codex install / uninstall
|
||||
graphify opencode install
|
||||
graphify cursor install / uninstall
|
||||
graphify gemini install / uninstall
|
||||
graphify copilot install / uninstall
|
||||
graphify aider install / uninstall
|
||||
graphify claw install / uninstall
|
||||
graphify droid install / uninstall
|
||||
graphify trae install / uninstall
|
||||
graphify trae-cn install / uninstall
|
||||
graphify hermes install / uninstall
|
||||
graphify kiro install / uninstall
|
||||
graphify antigravity install / uninstall
|
||||
|
||||
graphify extract ./docs # headless LLM-витягування для CI (без IDE)
|
||||
graphify extract ./docs --backend gemini # явний backend: gemini, kimi, claude, openai, deepseek, ollama, bedrock або claude-cli
|
||||
graphify extract ./docs --backend gemini --model gemini-3.1-pro-preview
|
||||
graphify extract ./docs --backend ollama # локальний Ollama (встановіть OLLAMA_BASE_URL / OLLAMA_MODEL) — без API-ключа для loopback
|
||||
OPENAI_BASE_URL=http://localhost:8080/v1 OPENAI_MODEL=my-model graphify extract ./docs --backend openai # будь-який OpenAI-сумісний сервер (llama.cpp, vLLM, LM Studio)
|
||||
ANTHROPIC_BASE_URL=http://localhost:4000 ANTHROPIC_MODEL=my-model graphify extract ./docs --backend claude # будь-який Anthropic-сумісний endpoint (LiteLLM proxy, шлюзи)
|
||||
GRAPHIFY_OLLAMA_NUM_CTX=32768 graphify extract ./docs --backend ollama # перевизначити KV-кеш вікно (автоматично за замовчуванням)
|
||||
GRAPHIFY_OLLAMA_KEEP_ALIVE=0 graphify extract ./docs --backend ollama # вивантажити модель після кожного шматка (економить VRAM на малих GPU)
|
||||
graphify extract ./docs --backend bedrock # AWS Bedrock через IAM — без API-ключа, використовує ланцюг облікових даних AWS
|
||||
graphify extract ./docs --backend claude-cli # маршрутизація через Claude Code CLI — без API-ключа, використовує вашу підписку Claude
|
||||
graphify extract ./docs --max-workers 16 # паралелізм AST (також GRAPHIFY_MAX_WORKERS)
|
||||
graphify extract ./docs --token-budget 30000 # менші семантичні шматки для локальних/малих моделей
|
||||
graphify extract ./docs --max-concurrency 2 # менше паралельних LLM-викликів (корисно для локального виводу)
|
||||
graphify extract ./docs --api-timeout 900 # довший HTTP тайм-аут для повільних локальних моделей (типово 600с)
|
||||
graphify extract ./docs --google-workspace # експортувати .gdoc/.gsheet/.gslides через gws перед витягуванням
|
||||
graphify extract ./docs --no-cluster # лише сире витягування, пропустити кластеризацію
|
||||
graphify extract ./docs --force # перезаписати graph.json навіть якщо новий граф має менше вузлів (використовуйте після рефакторингу або для очищення фантомних дублікатів)
|
||||
graphify extract ./docs --dedup-llm # LLM-арбітр для неоднозначних пар сутностей (використовує той самий API-ключ)
|
||||
graphify extract ./docs --global --as myrepo # витягнути і зареєструвати в крос-проектний глобальний граф
|
||||
GRAPHIFY_MAX_OUTPUT_TOKENS=32768 graphify extract ./docs --backend claude # підвищити ліміт виводу для щільних корпусів
|
||||
|
||||
graphify export callflow-html # graphify-out/<project>-callflow.html
|
||||
graphify export callflow-html --max-sections 8 # обмежити кількість згенерованих секцій архітектури
|
||||
graphify export callflow-html --output docs/arch.html
|
||||
graphify export callflow-html ./some-repo/graphify-out
|
||||
|
||||
graphify global add graphify-out/graph.json myrepo # зареєструвати граф проекту в ~/.graphify/global.json
|
||||
graphify global remove myrepo # видалити проект з глобального графу
|
||||
graphify global list # показати всі зареєстровані репо + кількість вузлів/ребер
|
||||
graphify global path # вивести шлях до файлу глобального графу
|
||||
|
||||
graphify prs # дашборд PR: CI, рев’ю, worktree, вплив на граф
|
||||
graphify prs 42 # детальний огляд PR #42
|
||||
graphify prs --triage # AI ранжування пріоритизації (автоматично визначає бекенд з середовища)
|
||||
graphify prs --worktrees # worktree → гілка → PR зіставлення
|
||||
graphify prs --conflicts # PR-и, що ділять спільні графові спільноти (ризик порядку злиття)
|
||||
graphify prs --base main # фільтр PR-ів за цільовою базовою гілкою
|
||||
graphify prs --repo owner/repo # запустити для іншого GitHub-репо
|
||||
GRAPHIFY_TRIAGE_BACKEND=kimi graphify prs --triage # використовувати конкретний backend для triage
|
||||
|
||||
graphify clone https://github.com/karpathy/nanoGPT
|
||||
graphify merge-graphs a.json b.json --out merged.json
|
||||
graphify --version # вивести встановлену версію
|
||||
graphify watch ./src
|
||||
graphify check-update ./src
|
||||
graphify update ./src
|
||||
graphify update ./src --no-cluster # пропустити рекластеризацію, записати лише сирий AST граф
|
||||
graphify update ./src --force # перезаписати навіть якщо новий граф має менше вузлів
|
||||
graphify cluster-only ./my-project
|
||||
graphify cluster-only ./my-project --graph path/to/graph.json # власне розташування графу
|
||||
graphify cluster-only ./my-project --resolution 1.5 # більше, менших спільнот
|
||||
graphify cluster-only ./my-project --exclude-hubs 99 # виключити вузли p99 ступеня з розбиття
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Дізнатися більше
|
||||
|
||||
- [Як це працює](../how-it-works.md) — пайплайн витягування, виявлення спільнот, оцінка впевненості, бенчмарки
|
||||
- [ARCHITECTURE.md](../../ARCHITECTURE.md) — опис модулів, як додати мову
|
||||
- [Опціональні інтеграції](../docker-mcp-sqlite.md) — Docker MCP Toolkit + SQLite
|
||||
|
||||
---
|
||||
|
||||
## Побудовано на graphify — Penpax
|
||||
|
||||
[**Penpax**](https://graphifylabs.ai) — це завжди активний шар поверх graphify, він застосовує той самий графовий підхід до всього робочого життя: зустрічей, історії браузера, email-ів, файлів і коду, постійно оновлюючись у фоновому режимі.
|
||||
|
||||
Створений для людей, чия робота розкидана по сотнях розмов і документів, які неможливо повністю відтворити. Без хмари, повністю на пристрої.
|
||||
|
||||
**Безкоштовна пробна версія незабаром.** [Приєднайтесь до списку очікування →](https://graphifylabs.ai)
|
||||
|
||||
---
|
||||
|
||||
<details>
|
||||
<summary>Участь у розробці</summary>
|
||||
|
||||
### Налаштування розробки
|
||||
|
||||
Клонуйте репо і встановіть у редагованому режимі:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/safishamsi/graphify.git
|
||||
cd graphify
|
||||
git checkout v8 # гілка активної розробки
|
||||
|
||||
# Створіть віртуальне середовище (потрібен Python 3.10+):
|
||||
python3 -m venv .venv
|
||||
source .venv/bin/activate # Windows: .venv\Scripts\activate
|
||||
|
||||
# Встановіть у редагованому режимі з усіма опціональними пакетами:
|
||||
pip install -e ".[all]"
|
||||
```
|
||||
|
||||
Перевірте редаговане встановлення:
|
||||
```bash
|
||||
graphify --version
|
||||
python -c "import graphify; print(graphify.__file__)"
|
||||
```
|
||||
|
||||
### Запуск тестів
|
||||
|
||||
```bash
|
||||
pip install pytest
|
||||
pytest tests/ -q # запустити весь набір тестів
|
||||
pytest tests/test_extract.py -q # один модуль
|
||||
pytest tests/ -q -k "python" # фільтрація за назвою
|
||||
```
|
||||
|
||||
> Примітка для macOS: набір тестів включає обидва файли `sample.f90` та `sample.F90`. Вони конфліктують на файлових системах HFS+ / APFS без урахування регістру. Запускайте на Linux або в Docker-контейнері, якщо потрібно тестувати обидва варіанти Fortran одночасно.
|
||||
|
||||
### Робочий процес з git
|
||||
|
||||
- Активна розробка відбувається в гілці `v8`.
|
||||
- Стиль комітів: `fix: <опис>` / `feat: <опис>` / `docs: <опис>`
|
||||
- Перед відкриттям PR запустіть `pytest tests/ -q` і переконайтесь, що він проходить.
|
||||
- Додайте файл-фікстуру до `tests/fixtures/` і тести до `tests/test_languages.py` для будь-якого нового екстрактора мови.
|
||||
|
||||
### Що варто додати
|
||||
|
||||
Найкорисніший внесок — це **опрацьовані приклади**. Запустіть `/graphify` на реальному корпусі, збережіть результат у `worked/{slug}/`, напишіть чесний `review.md` про те, що граф зробив правильно і неправильно, і відкрийте PR.
|
||||
|
||||
**Помилки витягування** — відкрийте issue з вхідним файлом, записом кешу (`graphify-out/cache/`) і тим, що було пропущено або неправильно.
|
||||
|
||||
Дивіться [ARCHITECTURE.md](../../ARCHITECTURE.md) щодо відповідальностей модулів і того, як додати мову.
|
||||
|
||||
</details>
|
||||
@@ -0,0 +1,170 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></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>
|
||||
</p>
|
||||
|
||||
**Sun'iy intellektga asoslangan kod yordamchilari uchun ko'nikma.** Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro yoki Google Antigravity da `/graphify` deb yozing — u sizning fayllaringizni o'qiydi, bilim grafini quradi va siz bilmagan tuzilmani sizga qaytaradi. Kod bazasini tezroq tushuning. Arxitektura qarorlari ortidagi "nima uchun" savoliga javob toping.
|
||||
|
||||
To'liq multimodal. Kod, PDF, markdown, ekran tasvirlari, diagrammalar, doska suratlari, boshqa tillardagi tasvirlar, video va audio fayllarni qo'shing — graphify ularning barchasidan tushuncha va aloqalarni chiqarib, bitta grafga birlashtiradi. Videolar Whisper yordamida mahalliy ravishda transkripsiya qilinadi, sizning korpusingizdan olingan domen-maxsus so'rov bilan. tree-sitter AST orqali 25 ta dasturlash tilini qo'llab-quvvatlaydi (Python, JS, TS, Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Lua, Zig, PowerShell, Elixir, Objective-C, Julia, Verilog, SystemVerilog, Vue, Svelte, Dart).
|
||||
|
||||
> Andrej Karpati maqolalar, tvitlar, ekran tasvirlari va eslatmalarni saqlaydigan `/raw` papkasini yuritadi. graphify ushbu muammoga javob — xom fayllarni o'qishga nisbatan har bir so'rov uchun **71,5 marta** kamroq token, sessiyalar orasida saqlanadi, topilgan va xulosa qilinganlar haqida halol.
|
||||
|
||||
```
|
||||
/graphify . # istalgan papka bilan ishlaydi — kod, eslatmalar, maqolalar, hammasi
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html interaktiv graf — brauzerda oching, tugunlarni bosing, qidiring, filtrlang
|
||||
├── GRAPH_REPORT.md god-tugunlar, kutilmagan aloqalar, taklif qilingan savollar
|
||||
├── graph.json doimiy graf — haftalardan keyin qayta o'qimasdan so'rov qiling
|
||||
└── cache/ SHA256-kesh — qayta ishga tushirish faqat o'zgargan fayllarni qayta ishlaydi
|
||||
```
|
||||
|
||||
Papkalarni istisno qilish uchun `.graphifyignore` faylini qo'shing:
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
vendor/
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
```
|
||||
|
||||
Sintaksisi `.gitignore` ga o'xshash.
|
||||
|
||||
## Qanday ishlaydi
|
||||
|
||||
graphify uch bosqichda ishlaydi. Birinchi navbatda, deterministik AST bosqichi kod fayllaridan tuzilmani chiqaradi (klasslar, funksiyalar, importlar, chaqiruv graflari, docstring lar, sabab izohlari) — LLM ishtirokisiz. Keyin video va audio fayllar faster-whisper yordamida mahalliy ravishda transkripsiya qilinadi. Nihoyat, Claude subagentlari hujjatlar, maqolalar, tasvirlar va transkriptlar ustida parallel ishlab, tushunchalar, aloqalar va dizayn asoslarini chiqarib oladi. Natijalar NetworkX grafiga birlashtiriladi, Leiden hamjamiyat aniqlash algoritmi bilan klasterlanadi va interaktiv HTML, so'rov qilinadigan JSON hamda tabiiy tildagi audit hisoboti sifatida eksport qilinadi.
|
||||
|
||||
**Klasterlash graf topologiyasiga asoslangan — embedding ishlatilmaydi.** Leiden hamjamiyatlarni qirralar zichligi bo'yicha topadi. Claude tomonidan chiqarilgan semantik o'xshashlik qirralari (`semantically_similar_to`, INFERRED deb belgilangan) allaqachon grafda. Graf tuzilmasining o'zi o'xshashlik signali. Alohida embedding bosqichi yoki vektor ma'lumotlar bazasi shart emas.
|
||||
|
||||
Har bir aloqa `EXTRACTED` (manbada to'g'ridan-to'g'ri topilgan), `INFERRED` (ishonch bahosi bilan asoslangan xulosa) yoki `AMBIGUOUS` (tekshirish uchun belgilangan) deb teglanadi.
|
||||
|
||||
## O'rnatish
|
||||
|
||||
**Talablar:** Python 3.10+ va quyidagilardan biri: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com), [Gemini CLI](https://github.com/google-gemini/gemini-cli), [GitHub Copilot CLI](https://docs.github.com/en/copilot/how-tos/copilot-cli), [VS Code Copilot Chat](https://code.visualstudio.com/docs/copilot/overview), [Aider](https://aider.chat), [OpenClaw](https://openclaw.ai), [Factory Droid](https://factory.ai), [Trae](https://trae.ai), [Kiro](https://kiro.dev), Hermes yoki [Google Antigravity](https://antigravity.google)
|
||||
|
||||
```bash
|
||||
# Tavsiya etiladi — Mac va Linux da PATH ni sozlashsiz ishlaydi
|
||||
uv tool install graphifyy && graphify install
|
||||
# yoki pipx bilan
|
||||
pipx install graphifyy && graphify install
|
||||
# yoki oddiy pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Rasmiy paket:** PyPI dagi paket nomi `graphifyy` (`pip install graphifyy` orqali o'rnatiladi). PyPI dagi boshqa `graphify*` nomli paketlar bu loyiha bilan bog'liq emas. Yagona rasmiy repozitoriy — [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
### Platforma qo'llab-quvvatlash
|
||||
|
||||
| Platforma | O'rnatish buyrug'i |
|
||||
|-----------|--------------------|
|
||||
| Claude Code (Linux/Mac) | `graphify install` |
|
||||
| Claude Code (Windows) | `graphify install` (avto-aniqlash) yoki `graphify install --platform windows` |
|
||||
| Codex | `graphify install --platform codex` |
|
||||
| OpenCode | `graphify install --platform opencode` |
|
||||
| GitHub Copilot CLI | `graphify install --platform copilot` |
|
||||
| VS Code Copilot Chat | `graphify vscode install` |
|
||||
| Aider | `graphify install --platform aider` |
|
||||
| OpenClaw | `graphify install --platform claw` |
|
||||
| Factory Droid | `graphify install --platform droid` |
|
||||
| Trae | `graphify install --platform trae` |
|
||||
| Trae CN | `graphify install --platform trae-cn` |
|
||||
| Gemini CLI | `graphify install --platform gemini` |
|
||||
| Hermes | `graphify install --platform hermes` |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
Keyin AI yordamchingizni oching va kiriting:
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
Eslatma: Codex ko'nikmalar uchun `/` o'rniga `$` ishlatadi, shuning uchun `$graphify .` deb kiriting.
|
||||
|
||||
### Yordamchini har doim grafdan foydalanishga majbur qilish (tavsiya etiladi)
|
||||
|
||||
Graf qurilgandan so'ng, loyihangizda buni bir marta bajaring:
|
||||
|
||||
| Platforma | Buyruq |
|
||||
|-----------|--------|
|
||||
| Claude Code | `graphify claude install` |
|
||||
| Codex | `graphify codex install` |
|
||||
| OpenCode | `graphify opencode install` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Gemini CLI | `graphify gemini install` |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
## Foydalanish
|
||||
|
||||
```
|
||||
/graphify # joriy katalog
|
||||
/graphify ./raw # ma'lum bir papka
|
||||
/graphify ./raw --mode deep # INFERRED qirralarini agressivroq chiqarish
|
||||
/graphify ./raw --update # faqat o'zgargan fayllarni qayta chiqarish
|
||||
/graphify ./raw --directed # yo'naltirilgan graf
|
||||
/graphify ./raw --cluster-only # mavjud grafda klasterlashni qayta ishga tushirish
|
||||
/graphify ./raw --no-viz # HTML siz, faqat hisobot + JSON
|
||||
/graphify ./raw --obsidian # Obsidian vault yaratish (opsional)
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # maqolani olish
|
||||
/graphify add <video-url> # audio yuklab olish, transkripsiya qilish va qo'shish
|
||||
/graphify query "Attention ni optimallashtiruvchi bilan nima bog'laydi?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
graphify hook install # Git ilgaklarini o'rnatish
|
||||
graphify update ./src # kod fayllarini qayta chiqarish, LLM siz
|
||||
graphify watch ./src # grafni avtomatik yangilash
|
||||
```
|
||||
|
||||
## Nima olasiz
|
||||
|
||||
**God-tugunlar** — eng yuqori darajadagi tushunchalar (hamma narsa ular orqali o'tadi)
|
||||
|
||||
**Kutilmagan aloqalar** — qo'shma ball bo'yicha tartiblangan. Kod-maqola qirralari yuqoriroq baholanadi. Har bir natijada tabiiy tildagi "nima uchun" tushuntirishi bor.
|
||||
|
||||
**Taklif qilingan savollar** — graf alohida javob bera oladigan 4-5 ta savol
|
||||
|
||||
**"Nima uchun"** — docstring lar, ichki izohlar (`# NOTE:`, `# IMPORTANT:`, `# HACK:`, `# WHY:`) va hujjatlardagi dizayn asoslari `rationale_for` tugunlari sifatida chiqariladi.
|
||||
|
||||
**Ishonch ballari** — har bir INFERRED qirrasida `confidence_score` (0,0-1,0) mavjud.
|
||||
|
||||
**Token benchmark** — har bir ishga tushirishdan keyin avtomatik chiqariladi. Aralash korpusda: so'rov uchun **71,5 marta** kamroq token, xom fayllarga nisbatan.
|
||||
|
||||
**Avto-sinxronlash** (`--watch`) — kod o'zgarganida grafni avtomatik yangilaydi.
|
||||
|
||||
**Git ilgaklari** (`graphify hook install`) — post-commit va post-checkout ilgaklarini o'rnatadi.
|
||||
|
||||
## Maxfiylik
|
||||
|
||||
graphify hujjatlar, maqolalar va tasvirlardan semantik chiqarish uchun fayl mazmunini AI yordamchingizning model API siga yuboradi. Kod fayllari tree-sitter AST orqali mahalliy ravishda qayta ishlanadi. Video va audio fayllar faster-whisper bilan mahalliy ravishda transkripsiya qilinadi. Hech qanday telemetriya, foydalanishni kuzatish yo'q.
|
||||
|
||||
## Texnologiyalar to'plami
|
||||
|
||||
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Semantik chiqarish Claude, GPT-4 yoki sizning platformangiz modeli orqali. Video transkripsiyasi faster-whisper + yt-dlp orqali (opsional).
|
||||
|
||||
## graphify ustida qurilgan — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) — graphify ustidagi korporativ qatlam. graphify fayllar papkasini bilim grafiga aylantirganidek, Penpax o'sha yondashuvni butun ish hayotingizga uzluksiz qo'llaydi.
|
||||
|
||||
**Tez orada bepul sinov muddati.** [Kutish ro'yxatiga qo'shiling →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
## Yulduzlar tarixi
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**Kỹ năng dành cho trợ lý lập trình AI.** Gõ `/graphify` trong Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro hoặc Google Antigravity — nó đọc các tệp của bạn, xây dựng đồ thị kiến thức và trả lại cho bạn cấu trúc mà bạn không biết là tồn tại. Hiểu codebase nhanh hơn. Tìm ra "tại sao" đằng sau các quyết định kiến trúc.
|
||||
|
||||
Hoàn toàn đa phương thức. Thêm code, PDF, markdown, ảnh chụp màn hình, sơ đồ, ảnh bảng trắng, hình ảnh bằng ngôn ngữ khác hoặc tệp video và âm thanh — graphify trích xuất các khái niệm và mối quan hệ từ tất cả mọi thứ và kết nối chúng trong một đồ thị duy nhất. Video được phiên âm cục bộ bằng Whisper. Hỗ trợ 25 ngôn ngữ lập trình qua tree-sitter AST.
|
||||
|
||||
> Andrej Karpathy duy trì một thư mục `/raw` nơi anh ấy đặt các bài báo, tweet, ảnh chụp màn hình và ghi chú. graphify là câu trả lời cho vấn đề đó — **71,5x** ít token hơn trên mỗi truy vấn so với đọc các tệp thô, liên tục giữa các phiên.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html đồ thị tương tác — mở trong bất kỳ trình duyệt nào
|
||||
├── GRAPH_REPORT.md nút thần, kết nối bất ngờ, câu hỏi được đề xuất
|
||||
├── graph.json đồ thị liên tục — có thể truy vấn sau nhiều tuần
|
||||
└── cache/ bộ nhớ đệm SHA256 — các lần chạy lại chỉ xử lý các tệp đã thay đổi
|
||||
```
|
||||
|
||||
## Cách hoạt động
|
||||
|
||||
graphify hoạt động theo ba lần duyệt. Đầu tiên, một lần duyệt AST xác định trích xuất cấu trúc từ các tệp code mà không cần LLM. Sau đó, các tệp video và âm thanh được phiên âm cục bộ bằng faster-whisper. Cuối cùng, các sub-agent Claude chạy song song trên các tài liệu, bài báo, hình ảnh và bản phiên âm. Kết quả được hợp nhất vào đồ thị NetworkX, phân cụm với Leiden và xuất dưới dạng HTML tương tác, JSON có thể truy vấn và báo cáo kiểm tra.
|
||||
|
||||
Mỗi mối quan hệ được gắn nhãn `EXTRACTED`, `INFERRED` (với điểm tin cậy) hoặc `AMBIGUOUS`.
|
||||
|
||||
## Cài đặt
|
||||
|
||||
**Yêu cầu:** Python 3.10+ và một trong: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com) và các công cụ khác.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# hoặc với pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# hoặc pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **Gói chính thức:** Gói PyPI có tên là `graphifyy`. Kho lưu trữ chính thức duy nhất là [safishamsi/graphify](https://github.com/safishamsi/graphify).
|
||||
|
||||
## Sử dụng
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "điều gì kết nối Attention với optimizer?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## Những gì bạn nhận được
|
||||
|
||||
**Nút thần** — các khái niệm có bậc cao nhất · **Kết nối bất ngờ** — được xếp hạng theo điểm · **Câu hỏi được đề xuất** · **"Tại sao"** — docstring và lý do thiết kế được trích xuất dưới dạng nút · **Benchmark token** — **71,5x** ít token hơn trên corpus hỗn hợp.
|
||||
|
||||
## Quyền riêng tư
|
||||
|
||||
Các tệp code được xử lý cục bộ qua tree-sitter AST. Video được phiên âm cục bộ với faster-whisper. Không có telemetry.
|
||||
|
||||
## Được xây dựng trên graphify — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) là lớp doanh nghiệp trên graphify. **Dùng thử miễn phí sắp ra mắt.** [Tham gia danh sách chờ →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -0,0 +1,226 @@
|
||||
# graphify
|
||||
|
||||
🇺🇸 [English](../../README.md) | 🇨🇳 [简体中文](README.zh-CN.md) | 🇯🇵 [日本語](README.ja-JP.md) | 🇰🇷 [한국어](README.ko-KR.md) | 🇩🇪 [Deutsch](README.de-DE.md) | 🇫🇷 [Français](README.fr-FR.md) | 🇪🇸 [Español](README.es-ES.md) | 🇮🇳 [हिन्दी](README.hi-IN.md) | 🇧🇷 [Português](README.pt-BR.md) | 🇷🇺 [Русский](README.ru-RU.md) | 🇸🇦 [العربية](README.ar-SA.md) | 🇮🇹 [Italiano](README.it-IT.md) | 🇵🇱 [Polski](README.pl-PL.md) | 🇳🇱 [Nederlands](README.nl-NL.md) | 🇹🇷 [Türkçe](README.tr-TR.md) | 🇺🇦 [Українська](README.uk-UA.md) | 🇻🇳 [Tiếng Việt](README.vi-VN.md) | 🇮🇩 [Bahasa Indonesia](README.id-ID.md) | 🇸🇪 [Svenska](README.sv-SE.md) | 🇬🇷 [Ελληνικά](README.el-GR.md) | 🇷🇴 [Română](README.ro-RO.md) | 🇨🇿 [Čeština](README.cs-CZ.md) | 🇫🇮 [Suomi](README.fi-FI.md) | 🇩🇰 [Dansk](README.da-DK.md) | 🇳🇴 [Norsk](README.no-NO.md) | 🇭🇺 [Magyar](README.hu-HU.md) | 🇹🇭 [ภาษาไทย](README.th-TH.md) | 🇺🇿 [Oʻzbekcha](README.uz-UZ.md) | 🇹🇼 [繁體中文](README.zh-TW.md)
|
||||
|
||||
[](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
|
||||
[](https://pypi.org/project/graphifyy/)
|
||||
|
||||
**一个面向 AI 编码助手的技能。** 在 Claude Code、CodeBuddy、Codex、OpenCode、OpenClaw、Factory Droid 或 Trae 中输入 `/graphify`,它会读取你的文件、构建知识图谱,并把原本不明显的结构关系还给你。更快理解代码库,找到架构决策背后的"为什么"。
|
||||
|
||||
完全多模态。你可以直接丢进去代码、PDF、Markdown、截图、流程图、白板照片,甚至其他语言的图片 —— graphify 会用 Claude vision 从这些内容中提取概念和关系,并把它们连接到同一张图里。
|
||||
|
||||
> Andrej Karpathy 会维护一个 `/raw` 文件夹,把论文、推文、截图和笔记都丢进去。graphify 就是在解决这类问题 —— 相比直接读取原始文件,每次查询的 token 消耗可降低 **71.5 倍**,结果还能跨会话持久保存,并且会明确区分哪些内容是实际发现的,哪些只是合理推断。
|
||||
|
||||
```
|
||||
/graphify . # 可用于任意目录:代码库、笔记、论文都可以
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html 可交互图谱:可点节点、搜索、按社区过滤
|
||||
├── GRAPH_REPORT.md God nodes、意外连接、建议提问
|
||||
├── graph.json 持久化图谱:数周后仍可查询,无需重新读原始文件
|
||||
└── cache/ SHA256 缓存:重复运行时只处理变更过的文件
|
||||
```
|
||||
|
||||
## 工作原理
|
||||
|
||||
graphify 分两轮执行。第一轮是确定性的 AST 提取,对代码文件做结构分析(类、函数、导入、调用图、docstring、解释性注释),这一轮不需要 LLM。第二轮会并行调用 Claude 子代理处理文档、论文和图片,从中提取概念、关系和设计动机。最后把两边结果合并到一个 NetworkX 图里,用 Leiden 社区发现算法做聚类,并导出成可交互 HTML、可查询 JSON,以及一份人类可读的审计报告。
|
||||
|
||||
**聚类是基于图拓扑完成的,不依赖 embeddings。** Leiden 按边密度发现社区。Claude 抽取出的语义相似边(`semantically_similar_to`,标记为 `INFERRED`)本来就存在于图中,所以会直接影响社区划分。图结构本身就是相似性信号,不需要额外的 embedding 步骤,也不需要向量数据库。
|
||||
|
||||
每条关系都会被标记为 `EXTRACTED`(直接在源材料中找到)、`INFERRED`(合理推断,并附带置信度分数)或 `AMBIGUOUS`(有歧义,需要复核)。所以你始终知道哪些是实际发现的,哪些是模型猜出来的。
|
||||
|
||||
## 安装
|
||||
|
||||
**要求:** Python 3.10+,并且使用以下平台之一:[Claude Code](https://claude.ai/code)、[CodeBuddy](https://codebuddy.ai)、[Codex](https://openai.com/codex)、[OpenCode](https://opencode.ai)、[OpenClaw](https://openclaw.ai)、[Factory Droid](https://factory.ai) 或 [Trae](https://trae.ai)
|
||||
|
||||
```bash
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> PyPI 包当前暂时叫 `graphifyy`,因为 `graphify` 这个名字还在回收中。CLI 命令和 skill 命令仍然都是 `graphify`。
|
||||
|
||||
### 平台支持
|
||||
|
||||
| 平台 | 安装命令 |
|
||||
|------|----------|
|
||||
| Claude Code | `graphify install` |
|
||||
| CodeBuddy | `graphify install --platform codebuddy` |
|
||||
| Codex | `graphify install --platform codex` |
|
||||
| OpenCode | `graphify install --platform opencode` |
|
||||
| OpenClaw | `graphify install --platform claw` |
|
||||
| Factory Droid | `graphify install --platform droid` |
|
||||
| Trae | `graphify install --platform trae` |
|
||||
| Trae CN | `graphify install --platform trae-cn` |
|
||||
|
||||
Codex 用户还需要在 `~/.codex/config.toml` 的 `[features]` 下打开 `multi_agent = true`,这样才能并行提取。CodeBuddy 使用与 Claude Code 相同的 Agent 工具和 PreToolUse hook 机制。OpenClaw 目前的并行 agent 支持还比较早期,所以使用顺序提取。Trae 使用 Agent 工具进行并行子代理调度,**不支持** PreToolUse hook,因此 AGENTS.md 是其常驻机制。
|
||||
|
||||
然后打开你的 AI 编码助手,输入:
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
### 让助手始终优先使用图谱(推荐)
|
||||
|
||||
图构建完成后,在项目里运行一次:
|
||||
|
||||
| 平台 | 命令 |
|
||||
|------|------|
|
||||
| Claude Code | `graphify claude install` |
|
||||
| CodeBuddy | `graphify codebuddy install` |
|
||||
| Codex | `graphify codex install` |
|
||||
| OpenCode | `graphify opencode install` |
|
||||
| OpenClaw | `graphify claw install` |
|
||||
| Factory Droid | `graphify droid install` |
|
||||
| Trae | `graphify trae install` |
|
||||
| Trae CN | `graphify trae-cn install` |
|
||||
|
||||
**Claude Code** 会做两件事:
|
||||
1. 在 `CLAUDE.md` 中写入一段规则,告诉 Claude 在回答架构问题前先读 `graphify-out/GRAPH_REPORT.md`
|
||||
2. 安装一个 **PreToolUse hook**(写入 `settings.json`),在每次 `Glob` 和 `Grep` 前触发
|
||||
|
||||
如果知识图谱存在,Claude 会先看到:_"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ —— 这样 Claude 会优先按图谱导航,而不是一上来就 grep 整个项目。
|
||||
|
||||
**CodeBuddy** 与 Claude Code 相同,也会做两件事:在 `CODEBUDDY.md` 中写入规则,并安装 **PreToolUse hook**(写入 `.codebuddy/settings.json`),在每次 `Glob` 和 `Grep` 前触发。
|
||||
|
||||
**Codex、OpenCode、OpenClaw、Factory Droid、Trae** 会把同样的规则写进项目根目录的 `AGENTS.md`。这些平台没有 PreToolUse hook,所以 `AGENTS.md` 是它们的常驻机制。
|
||||
|
||||
卸载时使用对应平台的 uninstall 命令即可(例如 `graphify claude uninstall`)。
|
||||
|
||||
**常驻模式和显式触发有什么区别?**
|
||||
|
||||
常驻 hook 会优先暴露 `GRAPH_REPORT.md` —— 这是一页式总结,包含 god nodes、社区结构和意外连接。你的助手在搜索文件前会先读它,因此会按结构导航,而不是按关键字乱搜。这已经能覆盖大部分日常问题。
|
||||
|
||||
`/graphify query`、`/graphify path` 和 `/graphify explain` 会更深入:它们会逐跳遍历底层 `graph.json`,追踪节点之间的精确路径,并展示边级别细节(关系类型、置信度、源位置)。当你想从图谱里精确回答某个问题,而不仅仅是获得整体感知时,就该用这些命令。
|
||||
|
||||
可以这样理解:常驻 hook 是先给助手一张地图,`/graphify` 这几个命令则是让它沿着地图精确导航。
|
||||
|
||||
<details>
|
||||
<summary>手动安装(curl)</summary>
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.claude/skills/graphify
|
||||
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/skill.md \
|
||||
> ~/.claude/skills/graphify/SKILL.md
|
||||
```
|
||||
|
||||
把下面内容加到 `~/.claude/CLAUDE.md`:
|
||||
|
||||
```
|
||||
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
|
||||
When the user types `/graphify`, use the installed graphify skill or instructions before doing anything else.
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
## 用法
|
||||
|
||||
```
|
||||
/graphify # 对当前目录运行
|
||||
/graphify ./raw # 对指定目录运行
|
||||
/graphify ./raw --mode deep # 更激进地抽取 INFERRED 边
|
||||
/graphify ./raw --update # 只重新提取变更文件,并合并到已有图谱
|
||||
/graphify ./raw --cluster-only # 只重新聚类已有图谱,不重新提取
|
||||
/graphify ./raw --no-viz # 跳过 HTML,只生成 report + JSON
|
||||
/graphify ./raw --obsidian # 额外生成 Obsidian vault(可选)
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # 拉取论文、保存并更新图谱
|
||||
/graphify add https://x.com/karpathy/status/... # 拉取推文
|
||||
/graphify add https://... --author "Name" # 标记原作者
|
||||
/graphify add https://... --contributor "Name" # 标记是谁把它加入语料库的
|
||||
|
||||
/graphify query "what connects attention to the optimizer?"
|
||||
/graphify query "what connects attention to the optimizer?" --dfs # 追踪一条具体路径
|
||||
/graphify query "what connects attention to the optimizer?" --budget 1500 # 把预算限制在 N tokens
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
/graphify ./raw --watch # 文件变更时自动同步图谱(代码:立即更新;文档:提醒你)
|
||||
/graphify ./raw --wiki # 构建可供 agent 抓取的 wiki(index.md + 每个 community 一篇文章)
|
||||
/graphify ./raw --svg # 导出 graph.svg
|
||||
/graphify ./raw --graphml # 导出 graph.graphml(Gephi、yEd)
|
||||
/graphify ./raw --neo4j # 生成给 Neo4j 用的 cypher.txt
|
||||
/graphify ./raw --neo4j-push bolt://localhost:7687 # 直接推送到运行中的 Neo4j
|
||||
/graphify ./raw --mcp # 启动 MCP stdio server
|
||||
|
||||
# git hooks - 跨平台,在 commit 和切分支后重建图谱
|
||||
graphify hook install
|
||||
graphify hook uninstall
|
||||
graphify hook status
|
||||
|
||||
# 常驻助手规则 - 按平台区分
|
||||
graphify claude install # CLAUDE.md + PreToolUse hook(Claude Code)
|
||||
graphify claude uninstall
|
||||
graphify codex install # AGENTS.md(Codex)
|
||||
graphify opencode install # AGENTS.md(OpenCode)
|
||||
graphify claw install # AGENTS.md(OpenClaw)
|
||||
graphify droid install # AGENTS.md(Factory Droid)
|
||||
graphify trae install # AGENTS.md(Trae)
|
||||
graphify trae uninstall
|
||||
graphify trae-cn install # AGENTS.md(Trae CN)
|
||||
graphify trae-cn uninstall
|
||||
```
|
||||
|
||||
支持混合文件类型:
|
||||
|
||||
| 类型 | 扩展名 | 提取方式 |
|
||||
|------|--------|----------|
|
||||
| 代码 | `.py .ts .js .go .rs .java .c .cpp .rb .cs .kt .scala .php` | tree-sitter AST + 调用图 + docstring / 注释中的 rationale |
|
||||
| 文档 | `.md .txt .rst` | 通过 Claude 提取概念、关系和设计动机 |
|
||||
| 论文 | `.pdf` | 引文挖掘 + 概念提取 |
|
||||
| 图片 | `.png .jpg .webp .gif` | Claude vision —— 截图、图表、任意语言都可以 |
|
||||
|
||||
## 你会得到什么
|
||||
|
||||
**God nodes** —— 度最高的概念节点(整个系统最容易汇聚到的地方)
|
||||
|
||||
**意外连接** —— 按综合得分排序。代码-论文之间的边会比代码-代码边权重更高。每条结果都会附带一段人话解释。
|
||||
|
||||
**建议提问** —— 图谱特别擅长回答的 4 到 5 个问题。
|
||||
|
||||
**“为什么”** —— docstring、行内注释(`# NOTE:`、`# IMPORTANT:`、`# HACK:`、`# WHY:`)以及文档里的设计动机都会被抽取成 `rationale_for` 节点。不只是知道代码“做了什么”,还能知道“为什么要这么写”。
|
||||
|
||||
**置信度分数** —— 每条 `INFERRED` 边都有 `confidence_score`(0.0-1.0)。你不只知道哪些是猜出来的,还知道模型对这个猜测有多有把握。`EXTRACTED` 边恒为 1.0。
|
||||
|
||||
**语义相似边** —— 跨文件的概念连接,即使结构上没有直接依赖也能建立关联。比如两个函数做的是同一类问题但彼此没有调用,或者某个代码类和某篇论文里的算法概念本质相同。
|
||||
|
||||
**超边(Hyperedges)** —— 用来表达 3 个以上节点的群组关系,这是普通两两边表达不出来的。比如:一组类共同实现一个协议、认证链路里的一组函数、同一篇论文某一节里的多个概念共同组成一个想法。
|
||||
|
||||
**Token 基准** —— 每次运行后都会自动打印。对混合语料(Karpathy 的仓库 + 论文 + 图片),每次查询的 token 消耗可以比直接读原文件少 **71.5 倍**。第一次运行需要先提取并建图,这一步会花 token;后续查询直接读取压缩后的图谱,节省会越来越明显。SHA256 缓存保证重复运行时只重新处理变更文件。
|
||||
|
||||
**自动同步**(`--watch`)—— 在后台终端里跑着,代码库一变化,图谱就会跟着更新。代码文件保存会立刻触发重建(只走 AST,不用 LLM);文档/图片变更则会提醒你跑 `--update` 进行 LLM 再提取。
|
||||
|
||||
**Git hooks**(`graphify hook install`)—— 安装 `post-commit` 和 `post-checkout` hook。每次 commit 后、每次切分支后都会自动重建图谱,不需要额外开一个后台进程。
|
||||
|
||||
**Wiki**(`--wiki`)—— 为每个 community 和 god node 生成类似维基百科的 Markdown 文章,并提供 `index.md` 作为入口。任何 agent 只要读 `index.md`,就能通过普通文件导航整个知识库,而不必直接解析 JSON。
|
||||
|
||||
## Worked examples
|
||||
|
||||
| 语料 | 文件数 | 压缩比 | 输出 |
|
||||
|------|--------|--------|------|
|
||||
| Karpathy 的仓库 + 5 篇论文 + 4 张图片 | 52 | **71.5x** | [`worked/karpathy-repos/`](worked/karpathy-repos/) |
|
||||
| graphify 源码 + Transformer 论文 | 4 | **5.4x** | [`worked/mixed-corpus/`](worked/mixed-corpus/) |
|
||||
| httpx(合成 Python 库) | 6 | ~1x | [`worked/httpx/`](worked/httpx/) |
|
||||
|
||||
Token 压缩效果会随着语料规模增大而更明显。6 个文件本来就塞得进上下文窗口,所以 graphify 在这种场景里的价值更多是结构清晰度,而不是 token 压缩。到了 52 个文件(代码 + 论文 + 图片)这种规模,就能做到 71x+。每个 `worked/` 目录里都带了原始输入和真实输出(`GRAPH_REPORT.md`、`graph.json`),你可以自己跑一遍核对数字。
|
||||
|
||||
## 隐私
|
||||
|
||||
graphify 会把文档、论文和图片的内容发送给你所用 AI 编码助手背后的模型 API 来做语义提取 —— 可能是 Anthropic(Claude Code)、OpenAI(Codex),或者你当前平台使用的其他提供方。代码文件则完全在本地通过 tree-sitter AST 处理,不会把代码内容发出去。项目本身没有任何遥测、使用跟踪或分析。唯一的网络请求就是语义提取阶段调用你平台自己的模型 API,使用的也是你自己的 API key。
|
||||
|
||||
## 技术栈
|
||||
|
||||
NetworkX + Leiden(graspologic)+ tree-sitter + vis.js。语义提取由 Claude(Claude Code)、GPT-4(Codex)或你当前平台所运行的模型完成。不需要 Neo4j,不需要 server,整体是纯本地运行。
|
||||
|
||||
<details>
|
||||
<summary>贡献</summary>
|
||||
|
||||
**Worked examples** 是最能建立信任的贡献方式。对一个真实语料跑 `/graphify`,把输出保存到 `worked/{slug}/`,再写一份诚实的 `review.md`,评价图谱哪些地方做得对、哪些地方做得不对,然后提交 PR。
|
||||
|
||||
**提取 bug** —— 提 issue 时请附上输入文件、对应的缓存项(`graphify-out/cache/`)以及它漏提取或瞎编了什么。
|
||||
|
||||
模块职责和新增语言的方法见 [ARCHITECTURE.md](ARCHITECTURE.md)。
|
||||
|
||||
</details>
|
||||
@@ -0,0 +1,77 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v4" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
</p>
|
||||
|
||||
**AI 程式碼助手的技能。** 在 Claude Code、Codex、OpenCode、Cursor、Gemini CLI、GitHub Copilot CLI、VS Code Copilot Chat、Aider、OpenClaw、Factory Droid、Trae、Hermes、Kiro 或 Google Antigravity 中輸入 `/graphify` — 它會讀取您的檔案、建立知識圖譜,並返回您不知道存在的結構。更快理解程式碼庫。找到架構決策背後的「為什麼」。
|
||||
|
||||
完全多模態。添加程式碼、PDF、Markdown、截圖、圖表、白板照片、其他語言的圖片或視訊和音訊檔案 — graphify 從所有內容中提取概念和關係,並將它們連接成單一圖譜。視訊使用 Whisper 在本地轉錄。透過 tree-sitter AST 支援 25 種程式語言。
|
||||
|
||||
> Andrej Karpathy 維護一個 `/raw` 資料夾,在那裡他放置論文、推文、截圖和筆記。graphify 是這個問題的答案 — 每次查詢比讀取原始檔案少 **71.5 倍** 的 token,在會話之間持久存在。
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html 互動式圖譜 — 在任何瀏覽器中開啟
|
||||
├── GRAPH_REPORT.md 神級節點、令人驚訝的連接、建議問題
|
||||
├── graph.json 持久圖譜 — 幾週後仍可查詢
|
||||
└── cache/ SHA256 快取 — 重複執行只處理已變更的檔案
|
||||
```
|
||||
|
||||
## 運作原理
|
||||
|
||||
graphify 分三個階段工作。首先,確定性 AST 遍歷在不使用 LLM 的情況下從程式碼檔案中提取結構。然後使用 faster-whisper 在本地轉錄視訊和音訊檔案。最後,Claude 子代理並行處理文件、論文、圖片和轉錄文字。結果被合併到 NetworkX 圖譜中,使用 Leiden 進行聚類,並匯出為互動式 HTML、可查詢 JSON 和審計報告。
|
||||
|
||||
每個關係都標記為 `EXTRACTED`、`INFERRED`(帶有置信度分數)或 `AMBIGUOUS`。
|
||||
|
||||
## 安裝
|
||||
|
||||
**需求:** Python 3.10+ 以及以下之一:[Claude Code](https://claude.ai/code)、[Codex](https://openai.com/codex)、[OpenCode](https://opencode.ai)、[Cursor](https://cursor.com) 等。
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# 或使用 pipx
|
||||
pipx install graphifyy && graphify install
|
||||
# 或 pip
|
||||
pip install graphifyy && graphify install
|
||||
```
|
||||
|
||||
> **官方套件:** PyPI 套件名稱為 `graphifyy`。唯一的官方儲存庫是 [safishamsi/graphify](https://github.com/safishamsi/graphify)。
|
||||
|
||||
## 使用方式
|
||||
|
||||
```
|
||||
/graphify .
|
||||
/graphify ./raw --update
|
||||
/graphify query "什麼將 Attention 與 optimizer 連接起來?"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
graphify hook install
|
||||
graphify update ./src
|
||||
```
|
||||
|
||||
## 您會得到什麼
|
||||
|
||||
**神級節點** — 度數最高的概念 · **令人驚訝的連接** — 按分數排名 · **建議問題** · **「為什麼」** — 提取為節點的文件字串和設計理由 · **Token 基準測試** — 在混合語料庫上少 **71.5 倍** 的 token。
|
||||
|
||||
## 隱私
|
||||
|
||||
程式碼檔案透過 tree-sitter AST 在本地處理。視訊使用 faster-whisper 在本地轉錄。無遙測。
|
||||
|
||||
## 基於 graphify 構建 — Penpax
|
||||
|
||||
[**Penpax**](https://safishamsi.github.io/penpax.ai) 是 graphify 之上的企業層。**免費試用即將推出。** [加入等待名單 →](https://safishamsi.github.io/penpax.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -1,4 +1,4 @@
|
||||
"""graphify — extract · build · cluster · analyze · report."""
|
||||
"""graphify - extract · build · cluster · analyze · report."""
|
||||
|
||||
|
||||
def __getattr__(name):
|
||||
@@ -18,6 +18,9 @@ def __getattr__(name):
|
||||
"to_html": ("graphify.export", "to_html"),
|
||||
"to_svg": ("graphify.export", "to_svg"),
|
||||
"to_canvas": ("graphify.export", "to_canvas"),
|
||||
"to_wiki": ("graphify.wiki", "to_wiki"),
|
||||
"reflect": ("graphify.reflect", "reflect"),
|
||||
"save_query_result": ("graphify.ingest", "save_query_result"),
|
||||
}
|
||||
if name in _map:
|
||||
import importlib
|
||||
|
||||
+5134
-37
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,107 @@
|
||||
"""MinHash + band-LSH — datasketch-compatible drop-in (no scipy).
|
||||
|
||||
datasketch.lsh has `from scipy.integrate import quad` at module level.
|
||||
scipy's array_api_compat layer then lazily loads numpy.testing, which calls
|
||||
platform.machine() at import time to set test-skip decorator constants — and
|
||||
that in turn spawns cmd.exe via subprocess, hanging for minutes under EDR
|
||||
software in corporate Windows environments.
|
||||
|
||||
Covers the exact MinHash/MinHashLSH API surface used by dedup.py.
|
||||
Hash family (Mersenne-prime permutations) and LSH band structure are
|
||||
equivalent to datasketch so dedup quality is unchanged.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import hashlib
|
||||
import struct
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
_MP = np.uint64((1 << 61) - 1) # Mersenne prime for the hash family
|
||||
_MH = np.uint64(0xFFFF_FFFF) # mask to 32-bit values
|
||||
|
||||
# One (a, b) coefficient array per num_perm, shared across all instances.
|
||||
_MH_COEFFS: dict[int, tuple[np.ndarray, np.ndarray]] = {}
|
||||
|
||||
|
||||
def _mh_coeffs(num_perm: int) -> tuple[np.ndarray, np.ndarray]:
|
||||
if num_perm not in _MH_COEFFS:
|
||||
rng = np.random.RandomState(1)
|
||||
a = rng.randint(1, int(_MP), num_perm, dtype=np.uint64)
|
||||
b = rng.randint(0, int(_MP), num_perm, dtype=np.uint64)
|
||||
_MH_COEFFS[num_perm] = (a, b)
|
||||
return _MH_COEFFS[num_perm]
|
||||
|
||||
|
||||
class MinHash:
|
||||
"""MinHash sketch — same API as datasketch.MinHash for the subset used here."""
|
||||
|
||||
__slots__ = ("num_perm", "hashvalues", "_a", "_b")
|
||||
|
||||
def __init__(self, num_perm: int = 128) -> None:
|
||||
self.num_perm = num_perm
|
||||
self.hashvalues = np.full(num_perm, int(_MH), dtype=np.uint64)
|
||||
self._a, self._b = _mh_coeffs(num_perm)
|
||||
|
||||
def update(self, v: bytes) -> None:
|
||||
hv = np.uint64(struct.unpack("<I", hashlib.sha1(v).digest()[:4])[0])
|
||||
phv = np.bitwise_and((self._a * hv + self._b) % _MP, _MH)
|
||||
self.hashvalues = np.minimum(self.hashvalues, phv)
|
||||
|
||||
|
||||
def _lsh_integrate(f, lo: float, hi: float, n: int = 128) -> float:
|
||||
"""Numerical integration — replaces scipy.integrate.quad for LSH param search."""
|
||||
h = (hi - lo) / n
|
||||
return h * sum(f(lo + i * h) for i in range(n))
|
||||
|
||||
|
||||
_LSH_PARAMS_CACHE: dict[tuple[float, int], tuple[int, int]] = {}
|
||||
|
||||
|
||||
def _optimal_lsh_params(threshold: float, num_perm: int) -> tuple[int, int]:
|
||||
"""Find (bands, rows) that minimise weighted FP+FN error, without scipy."""
|
||||
key = (threshold, num_perm)
|
||||
if key in _LSH_PARAMS_CACHE:
|
||||
return _LSH_PARAMS_CACHE[key]
|
||||
best_err, best = float("inf"), (1, 1)
|
||||
for b in range(1, num_perm + 1):
|
||||
for r in range(1, num_perm // b + 1):
|
||||
fp = _lsh_integrate(
|
||||
lambda s, _b=float(b), _r=float(r): 1 - (1 - s ** _r) ** _b,
|
||||
0.0, threshold,
|
||||
)
|
||||
fn = _lsh_integrate(
|
||||
lambda s, _b=float(b), _r=float(r): 1 - (1 - (1 - s ** _r) ** _b),
|
||||
threshold, 1.0,
|
||||
)
|
||||
err = 0.5 * fp + 0.5 * fn
|
||||
if err < best_err:
|
||||
best_err, best = err, (b, r)
|
||||
_LSH_PARAMS_CACHE[key] = best
|
||||
return best
|
||||
|
||||
|
||||
class MinHashLSH:
|
||||
"""Band-hashing LSH — same API as datasketch.MinHashLSH for the subset used here."""
|
||||
|
||||
def __init__(self, threshold: float = 0.5, num_perm: int = 128) -> None:
|
||||
self.b, self.r = _optimal_lsh_params(threshold, num_perm)
|
||||
self._tables: list[dict[bytes, list[str]]] = [{} for _ in range(self.b)]
|
||||
self._keys: set[str] = set()
|
||||
|
||||
def insert(self, key: str, minhash: MinHash) -> None:
|
||||
if key in self._keys:
|
||||
raise ValueError(f"Key {key!r} already exists in MinHashLSH")
|
||||
self._keys.add(key)
|
||||
hv = minhash.hashvalues
|
||||
for i, table in enumerate(self._tables):
|
||||
band = hv[i * self.r : (i + 1) * self.r].tobytes()
|
||||
table.setdefault(band, []).append(key)
|
||||
|
||||
def query(self, minhash: MinHash) -> list[str]:
|
||||
hv = minhash.hashvalues
|
||||
candidates: set[str] = set()
|
||||
for i, table in enumerate(self._tables):
|
||||
band = hv[i * self.r : (i + 1) * self.r].tobytes()
|
||||
candidates.update(table.get(band, []))
|
||||
return list(candidates)
|
||||
@@ -0,0 +1,232 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import deque
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
import unicodedata
|
||||
|
||||
import networkx as nx
|
||||
|
||||
|
||||
DEFAULT_AFFECTED_RELATIONS = (
|
||||
"calls",
|
||||
"indirect_call",
|
||||
"references",
|
||||
"imports",
|
||||
"imports_from",
|
||||
"re_exports",
|
||||
"inherits",
|
||||
"extends",
|
||||
"implements",
|
||||
"uses",
|
||||
"mixes_in",
|
||||
"embeds",
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AffectedHit:
|
||||
node_id: str
|
||||
depth: int
|
||||
via_relation: str
|
||||
|
||||
|
||||
def _node_label(graph: nx.Graph, node_id: str) -> str:
|
||||
data = graph.nodes[node_id]
|
||||
return str(data.get("label") or node_id)
|
||||
|
||||
|
||||
def _format_location(data: dict) -> str:
|
||||
source_file = data.get("source_file") or "-"
|
||||
source_location = data.get("source_location")
|
||||
if source_location:
|
||||
return f"{source_file}:{source_location}"
|
||||
return str(source_file)
|
||||
|
||||
|
||||
def _bare_name(label: str) -> str:
|
||||
"""Lowercased label with the callable decoration (trailing "()") removed."""
|
||||
label = _normalize_label(label)
|
||||
return label[:-2] if label.endswith("()") else label
|
||||
|
||||
|
||||
def _normalize_label(label: str) -> str:
|
||||
return unicodedata.normalize("NFC", label).casefold()
|
||||
|
||||
|
||||
def _prefer_file_node(
|
||||
graph: nx.Graph,
|
||||
node_ids: list[str],
|
||||
query: str,
|
||||
) -> str | None:
|
||||
"""Return the file-level node when a source_file query matches many nodes."""
|
||||
query_basename = _normalize_label(Path(query).name)
|
||||
exact_file_nodes = [
|
||||
node_id
|
||||
for node_id in node_ids
|
||||
if str(graph.nodes[node_id].get("source_location", "")) == "L1"
|
||||
and _normalize_label(str(graph.nodes[node_id].get("label", ""))) == query_basename
|
||||
]
|
||||
if len(exact_file_nodes) == 1:
|
||||
return exact_file_nodes[0]
|
||||
|
||||
l1_nodes = [
|
||||
node_id
|
||||
for node_id in node_ids
|
||||
if str(graph.nodes[node_id].get("source_location", "")) == "L1"
|
||||
]
|
||||
if len(l1_nodes) == 1:
|
||||
return l1_nodes[0]
|
||||
|
||||
basename_nodes = [
|
||||
node_id
|
||||
for node_id in node_ids
|
||||
if _normalize_label(str(graph.nodes[node_id].get("label", ""))) == query_basename
|
||||
]
|
||||
if len(basename_nodes) == 1:
|
||||
return basename_nodes[0]
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def resolve_seed(graph: nx.Graph, query: str) -> 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
|
||||
# (otherwise `affected "src/x.ts/"` returned None while `explain` resolved it).
|
||||
query = query.rstrip("/\\") or query
|
||||
if query in graph:
|
||||
return query
|
||||
query_lower = _normalize_label(query)
|
||||
exact_label_matches = [
|
||||
str(node_id)
|
||||
for node_id, data in graph.nodes(data=True)
|
||||
if _normalize_label(str(data.get("label", ""))) == query_lower
|
||||
]
|
||||
if len(exact_label_matches) == 1:
|
||||
return exact_label_matches[0]
|
||||
# Callable labels are decorated ("name()"), so a bare "name" query falls
|
||||
# through exact matching and then ties with any "name*" sibling in the
|
||||
# contains pass. Match on the undecorated name before giving up.
|
||||
query_bare = _bare_name(query_lower)
|
||||
bare_name_matches = [
|
||||
str(node_id)
|
||||
for node_id, data in graph.nodes(data=True)
|
||||
if _bare_name(str(data.get("label", ""))) == query_bare
|
||||
]
|
||||
if len(bare_name_matches) == 1:
|
||||
return bare_name_matches[0]
|
||||
exact_source_matches = [
|
||||
str(node_id)
|
||||
for node_id, data in graph.nodes(data=True)
|
||||
if _normalize_label(str(data.get("source_file", ""))) == query_lower
|
||||
]
|
||||
if len(exact_source_matches) == 1:
|
||||
return exact_source_matches[0]
|
||||
if exact_source_matches:
|
||||
preferred_file_node = _prefer_file_node(graph, exact_source_matches, query)
|
||||
if preferred_file_node is not None:
|
||||
return preferred_file_node
|
||||
contains_matches = [
|
||||
str(node_id)
|
||||
for node_id, data in graph.nodes(data=True)
|
||||
if query_lower in _normalize_label(str(data.get("label", "")))
|
||||
]
|
||||
if len(contains_matches) == 1:
|
||||
return contains_matches[0]
|
||||
return None
|
||||
|
||||
|
||||
def affected_nodes(
|
||||
graph: nx.Graph,
|
||||
seed: str,
|
||||
*,
|
||||
relations: Iterable[str] = DEFAULT_AFFECTED_RELATIONS,
|
||||
depth: int = 2,
|
||||
) -> list[AffectedHit]:
|
||||
relation_set = set(relations)
|
||||
seen = {seed}
|
||||
queue: deque[tuple[str, int]] = deque([(seed, 0)])
|
||||
hits: list[AffectedHit] = []
|
||||
|
||||
while queue:
|
||||
current, current_depth = queue.popleft()
|
||||
if current_depth >= depth:
|
||||
continue
|
||||
if hasattr(graph, "in_edges"):
|
||||
incoming = graph.in_edges(current, data=True)
|
||||
else:
|
||||
incoming = (
|
||||
(source, target, data)
|
||||
for source, target, data in graph.edges(data=True)
|
||||
if target == current
|
||||
)
|
||||
for source, _target, data in incoming:
|
||||
relation = str(data.get("relation", ""))
|
||||
if relation not in relation_set:
|
||||
continue
|
||||
source = str(source)
|
||||
if source in seen:
|
||||
continue
|
||||
seen.add(source)
|
||||
hit = AffectedHit(source, current_depth + 1, relation)
|
||||
hits.append(hit)
|
||||
queue.append((source, current_depth + 1))
|
||||
|
||||
return hits
|
||||
|
||||
|
||||
def format_affected(
|
||||
graph: nx.Graph,
|
||||
query: str,
|
||||
*,
|
||||
relations: Iterable[str] = DEFAULT_AFFECTED_RELATIONS,
|
||||
depth: int = 2,
|
||||
) -> str:
|
||||
relation_list = tuple(relations)
|
||||
seed = resolve_seed(graph, query)
|
||||
if seed is None:
|
||||
return f"No unique node match for {query}"
|
||||
|
||||
hits = affected_nodes(graph, seed, relations=relation_list, depth=depth)
|
||||
lines = [
|
||||
f"Affected nodes for {_node_label(graph, seed)}",
|
||||
f"Relations: {', '.join(relation_list)}",
|
||||
f"Depth: {depth}",
|
||||
]
|
||||
if not hits:
|
||||
lines.append("No affected nodes found.")
|
||||
return "\n".join(lines)
|
||||
|
||||
for hit in hits:
|
||||
data = graph.nodes[hit.node_id]
|
||||
lines.append(
|
||||
f"- {_node_label(graph, hit.node_id)} [{hit.via_relation}] {_format_location(data)}"
|
||||
)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def load_graph(path: Path) -> nx.Graph:
|
||||
import json
|
||||
from networkx.readwrite import json_graph
|
||||
|
||||
try:
|
||||
raw = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError) as exc:
|
||||
raise RuntimeError(
|
||||
f"Cannot read graph file {path}: {exc}. "
|
||||
"Re-run 'graphify extract' to regenerate it."
|
||||
) from exc
|
||||
# Force directed so stored caller→callee direction survives the round-trip;
|
||||
# mirrors serve.py and __main__.py (#1174).
|
||||
raw = {**raw, "directed": True}
|
||||
# Normalize the edge key: graphify's `extract` output uses "edges" while
|
||||
# networkx's node_link_data default is "links". Without this, an edges-keyed
|
||||
# graph.json raises an uncaught KeyError: 'links' here — every other loader
|
||||
# (__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)
|
||||
@@ -0,0 +1,12 @@
|
||||
## graphify
|
||||
|
||||
This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships.
|
||||
|
||||
When the user types `/graphify`, use the installed graphify skill or instructions before doing anything else.
|
||||
|
||||
Rules:
|
||||
- For codebase questions, first run `graphify query "<question>"` when graphify-out/graph.json exists. Use `graphify path "<A>" "<B>"` for relationships and `graphify explain "<concept>"` for focused concepts. These return a scoped subgraph, usually much smaller than GRAPH_REPORT.md or raw grep output.
|
||||
- Dirty graphify-out/ files are expected after hooks or incremental updates; dirty graph files are not a reason to skip graphify. Only skip graphify if the task is about stale or incorrect graph output, or the user explicitly says not to use it.
|
||||
- If graphify-out/wiki/index.md exists, use it for broad navigation instead of raw source browsing.
|
||||
- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context.
|
||||
- After modifying code, run `graphify update .` to keep the graph current (AST-only, no API cost).
|
||||
@@ -0,0 +1,14 @@
|
||||
---
|
||||
trigger: always_on
|
||||
description: Consult the graphify knowledge graph at graphify-out/ for codebase and architecture questions.
|
||||
---
|
||||
|
||||
## graphify
|
||||
|
||||
This project has a graphify knowledge graph at graphify-out/.
|
||||
|
||||
Rules:
|
||||
- For codebase or architecture questions, when `graphify-out/graph.json` exists, first run `graphify query "<question>"` (CLI) or `query_graph` (MCP). Use `graphify path "<A>" "<B>"` / `shortest_path` for relationships and `graphify explain "<concept>"` / `get_node` for focused concepts. These return a scoped subgraph, usually much smaller than `GRAPH_REPORT.md` or raw grep output.
|
||||
- If graphify-out/wiki/index.md exists, navigate it instead of reading raw files
|
||||
- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context
|
||||
- After modifying code files in this session, run `graphify update .` to keep the graph current (AST-only, no API cost)
|
||||
@@ -0,0 +1,9 @@
|
||||
## graphify
|
||||
|
||||
This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships.
|
||||
|
||||
Rules:
|
||||
- For codebase questions, first run `graphify query "<question>"` when graphify-out/graph.json exists. Use `graphify path "<A>" "<B>"` for relationships and `graphify explain "<concept>"` for focused concepts. These return a scoped subgraph, usually much smaller than GRAPH_REPORT.md or raw grep output.
|
||||
- If graphify-out/wiki/index.md exists, use it for broad navigation instead of raw source browsing.
|
||||
- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context.
|
||||
- After modifying code, run `graphify update .` to keep the graph current (AST-only, no API cost).
|
||||
@@ -0,0 +1,9 @@
|
||||
## graphify
|
||||
|
||||
This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships.
|
||||
|
||||
Rules:
|
||||
- For codebase questions, first run `graphify query "<question>"` when graphify-out/graph.json exists. Use `graphify path "<A>" "<B>"` for relationships and `graphify explain "<concept>"` for focused concepts. These return a scoped subgraph, usually much smaller than GRAPH_REPORT.md or raw grep output.
|
||||
- If graphify-out/wiki/index.md exists, use it for broad navigation instead of raw source browsing.
|
||||
- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context.
|
||||
- After modifying code, run `graphify update .` to keep the graph current (AST-only, no API cost).
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
inclusion: always
|
||||
---
|
||||
|
||||
graphify: A knowledge graph of this project lives in `graphify-out/`. For codebase, architecture, or dependency questions, when `graphify-out/graph.json` exists, first run `graphify query "<question>"` (or `graphify path "<A>" "<B>"` / `graphify explain "<concept>"`). These return a scoped subgraph, usually much smaller than `GRAPH_REPORT.md` or raw grep output. Read `GRAPH_REPORT.md` only for broad architecture review or when those commands do not surface enough context.
|
||||
@@ -0,0 +1,17 @@
|
||||
## graphify
|
||||
|
||||
For any question about this repo's architecture, structure, components, or how to add/modify/find
|
||||
code, your first action should be `graphify query "<question>"` when `graphify-out/graph.json`
|
||||
exists. Use `graphify path "<A>" "<B>"` for relationship questions and `graphify explain "<concept>"`
|
||||
for focused-concept questions. These return a scoped subgraph, usually much smaller than the full
|
||||
report or raw grep output.
|
||||
|
||||
Triggers: "how do I…", "where is…", "what does … do", "add/modify a <component>",
|
||||
"explain the architecture", or anything that depends on how files or classes relate.
|
||||
|
||||
If `graphify-out/wiki/index.md` exists, use it for broad navigation. Read `graphify-out/GRAPH_REPORT.md`
|
||||
only for broad architecture review or when query/path/explain do not surface enough context. Only read
|
||||
source files when (a) modifying/debugging specific code, (b) the graph lacks the needed detail, or
|
||||
(c) the graph is missing or stale.
|
||||
|
||||
Type `/graphify` in Copilot Chat to build or update the graph.
|
||||
+353
-50
@@ -1,7 +1,56 @@
|
||||
"""Graph analysis: god nodes (most connected), surprising connections (cross-community), suggested questions."""
|
||||
from __future__ import annotations
|
||||
from pathlib import Path
|
||||
import networkx as nx
|
||||
|
||||
from graphify.build import edge_data
|
||||
|
||||
# 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
|
||||
# even if they weren't filtered at extraction time (#1147).
|
||||
_BUILTIN_NOISE_LABELS = frozenset({
|
||||
"str", "int", "float", "bool", "bytes", "bytearray", "complex", "object",
|
||||
"True", "False",
|
||||
"MagicMock", "Mock", "AsyncMock", "NonCallableMock",
|
||||
"NonCallableMagicMock", "PropertyMock", "patch", "sentinel",
|
||||
# Python stdlib types commonly confused for project symbols
|
||||
"Path", "Any", "Optional", "List", "Dict", "Set", "Tuple", "Union",
|
||||
"Callable", "Type", "ClassVar", "Final", "Literal", "Protocol",
|
||||
"Counter", "defaultdict", "OrderedDict", "datetime", "Enum",
|
||||
"os", "sys", "re", "json", "io", "abc", "typing",
|
||||
})
|
||||
|
||||
# Language families — extensions sharing a runtime can legitimately call each other
|
||||
_LANG_FAMILY: dict[str, str] = {
|
||||
**{e: "python" for e in (".py", ".pyw")},
|
||||
**{e: "js" for e in (".js", ".jsx", ".mjs", ".ejs", ".ts", ".tsx", ".vue", ".svelte")},
|
||||
**{e: "go" for e in (".go",)},
|
||||
**{e: "rust" for e in (".rs",)},
|
||||
**{e: "jvm" for e in (".java", ".kt", ".kts", ".scala")},
|
||||
**{e: "c" for e in (".c", ".h", ".cpp", ".cc", ".cxx", ".hpp")},
|
||||
**{e: "ruby" for e in (".rb",)},
|
||||
**{e: "swift" for e in (".swift",)},
|
||||
**{e: "dotnet" for e in (".cs",)},
|
||||
**{e: "php" for e in (".php",)},
|
||||
**{e: "r" for e in (".r",)},
|
||||
}
|
||||
|
||||
|
||||
def _cross_language(src_a: str, src_b: str) -> bool:
|
||||
"""Return True if two source files belong to different language families."""
|
||||
ext_a = Path(src_a).suffix.lower()
|
||||
ext_b = Path(src_b).suffix.lower()
|
||||
fam_a = _LANG_FAMILY.get(ext_a)
|
||||
fam_b = _LANG_FAMILY.get(ext_b)
|
||||
if fam_a is None or fam_b is None:
|
||||
return False
|
||||
return fam_a != fam_b
|
||||
|
||||
|
||||
def _node_community_map(communities: dict[int, list[str]]) -> dict[str, int]:
|
||||
"""Invert communities dict: node_id -> community_id."""
|
||||
return {n: cid for cid, nodes in communities.items() for n in nodes}
|
||||
|
||||
|
||||
def _is_file_node(G: nx.Graph, node_id: str) -> bool:
|
||||
"""
|
||||
@@ -11,24 +60,45 @@ def _is_file_node(G: nx.Graph, node_id: str) -> bool:
|
||||
These are synthetic nodes created by the AST extractor and should be excluded
|
||||
from god nodes, surprising connections, and knowledge gap reporting.
|
||||
"""
|
||||
label = G.nodes[node_id].get("label", "")
|
||||
attrs = G.nodes[node_id]
|
||||
label = attrs.get("label", "")
|
||||
if not label:
|
||||
return False
|
||||
# File-level hub: label is a filename with a code extension
|
||||
if label.split(".")[-1] in ("py", "ts", "js", "go", "rs", "java", "rb", "cpp", "c", "h"):
|
||||
return True
|
||||
# File-level hub: label matches the actual source filename (not just any label ending in .py)
|
||||
source_file = attrs.get("source_file", "")
|
||||
if source_file:
|
||||
from pathlib import Path as _Path
|
||||
if label == _Path(source_file).name:
|
||||
return True
|
||||
# Method stub: AST extractor labels methods as '.method_name()'
|
||||
if label.startswith(".") and label.endswith("()"):
|
||||
return True
|
||||
# Module-level function stub: labeled 'function_name()' — only has a contains edge
|
||||
# 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:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
_JSON_NOISE_LABELS: frozenset[str] = frozenset({
|
||||
"start", "end", "name", "id", "type", "properties",
|
||||
"value", "key", "data", "items", "title", "description", "version",
|
||||
"dependencies", "devdependencies", "peerdependencies",
|
||||
"optionaldependencies", "bundleddependencies", "bundledependencies",
|
||||
})
|
||||
|
||||
|
||||
def _is_json_key_node(G: nx.Graph, node_id: str) -> bool:
|
||||
attrs = G.nodes[node_id]
|
||||
src = (attrs.get("source_file") or "").lower()
|
||||
if not src.endswith(".json"):
|
||||
return False
|
||||
label = (attrs.get("label") or "").strip().lower()
|
||||
return label in _JSON_NOISE_LABELS
|
||||
|
||||
|
||||
def god_nodes(G: nx.Graph, top_n: int = 10) -> list[dict]:
|
||||
"""Return the top_n most-connected real entities — the core abstractions.
|
||||
"""Return the top_n most-connected real entities - the core abstractions.
|
||||
|
||||
File-level hub nodes are excluded: they accumulate import/contains edges
|
||||
mechanically and don't represent meaningful architectural abstractions.
|
||||
@@ -37,12 +107,14 @@ def god_nodes(G: nx.Graph, top_n: int = 10) -> list[dict]:
|
||||
sorted_nodes = sorted(degree.items(), key=lambda x: x[1], reverse=True)
|
||||
result = []
|
||||
for node_id, deg in sorted_nodes:
|
||||
if _is_file_node(G, node_id) or _is_concept_node(G, node_id):
|
||||
if _is_file_node(G, node_id) or _is_concept_node(G, node_id) or _is_json_key_node(G, node_id):
|
||||
continue
|
||||
if G.nodes[node_id].get("label", "") in _BUILTIN_NOISE_LABELS:
|
||||
continue
|
||||
result.append({
|
||||
"id": node_id,
|
||||
"label": G.nodes[node_id].get("label", node_id),
|
||||
"edges": deg,
|
||||
"degree": deg,
|
||||
})
|
||||
if len(result) >= top_n:
|
||||
break
|
||||
@@ -55,7 +127,7 @@ def surprising_connections(
|
||||
top_n: int = 5,
|
||||
) -> list[dict]:
|
||||
"""
|
||||
Find connections that are genuinely surprising — not obvious from file structure.
|
||||
Find connections that are genuinely surprising - not obvious from file structure.
|
||||
|
||||
Strategy:
|
||||
- Multi-file corpora: cross-file edges between real entities (not concept nodes).
|
||||
@@ -100,21 +172,121 @@ def _is_concept_node(G: nx.Graph, node_id: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
from graphify.detect import CODE_EXTENSIONS, DOC_EXTENSIONS, PAPER_EXTENSIONS, IMAGE_EXTENSIONS
|
||||
|
||||
|
||||
def _file_category(path: str) -> str:
|
||||
ext = ("." + path.rsplit(".", 1)[-1].lower()) if "." in path else ""
|
||||
if ext in CODE_EXTENSIONS:
|
||||
return "code"
|
||||
if ext in PAPER_EXTENSIONS:
|
||||
return "paper"
|
||||
if ext in IMAGE_EXTENSIONS:
|
||||
return "image"
|
||||
return "doc"
|
||||
|
||||
|
||||
def _top_level_dir(path: str) -> str:
|
||||
"""Return the first path component - used to detect cross-repo edges."""
|
||||
return path.split("/")[0] if "/" in path else path
|
||||
|
||||
|
||||
def _surprise_score(
|
||||
G: nx.Graph,
|
||||
u: str,
|
||||
v: str,
|
||||
data: dict,
|
||||
node_community: dict[str, int],
|
||||
u_source: str,
|
||||
v_source: str,
|
||||
degrees: dict[str, int] | None = None,
|
||||
) -> tuple[int, list[str]]:
|
||||
"""Score how surprising a cross-file edge is. Returns (score, reasons)."""
|
||||
score = 0
|
||||
reasons: list[str] = []
|
||||
|
||||
# 1. Confidence weight - uncertain connections are more noteworthy
|
||||
conf = data.get("confidence", "EXTRACTED")
|
||||
relation = data.get("relation", "")
|
||||
conf_bonus = {"AMBIGUOUS": 3, "INFERRED": 2, "EXTRACTED": 1}.get(conf, 1)
|
||||
|
||||
cat_u = _file_category(u_source)
|
||||
cat_v = _file_category(v_source)
|
||||
|
||||
# Suppress all structural bonuses for INFERRED calls/uses that cross language
|
||||
# boundaries or connect code to a doc file. Both cases are resolver pollution:
|
||||
# label-matching fires across language families in monorepos, and code→doc
|
||||
# "calls" edges are extraction artefacts, not real architecture.
|
||||
# Excludes `semantically_similar_to` (genuine cross-boundary insight) and all
|
||||
# AMBIGUOUS/EXTRACTED edges (not from the resolver path).
|
||||
_suppress_structural = (
|
||||
conf == "INFERRED"
|
||||
and relation in ("calls", "uses")
|
||||
and (_cross_language(u_source, v_source) or {cat_u, cat_v} == {"code", "doc"})
|
||||
)
|
||||
if _suppress_structural:
|
||||
conf_bonus = 0
|
||||
|
||||
score += conf_bonus
|
||||
if conf in ("AMBIGUOUS", "INFERRED"):
|
||||
reasons.append(f"{conf.lower()} connection - not explicitly stated in source")
|
||||
|
||||
# 2. Cross file-type bonus - code↔paper or code↔image is non-obvious
|
||||
if cat_u != cat_v and not _suppress_structural:
|
||||
score += 2
|
||||
reasons.append(f"crosses file types ({cat_u} ↔ {cat_v})")
|
||||
|
||||
# 3. Cross-repo bonus - different top-level directory
|
||||
if _top_level_dir(u_source) != _top_level_dir(v_source) and not _suppress_structural:
|
||||
score += 2
|
||||
reasons.append("connects across different repos/directories")
|
||||
|
||||
# 4. Cross-community bonus - Leiden says these are structurally distant
|
||||
cid_u = node_community.get(u)
|
||||
cid_v = node_community.get(v)
|
||||
if cid_u is not None and cid_v is not None and cid_u != cid_v and not _suppress_structural:
|
||||
score += 1
|
||||
reasons.append("bridges separate communities")
|
||||
|
||||
# 4b. Semantic similarity bonus - non-obvious conceptual links score higher
|
||||
if data.get("relation") == "semantically_similar_to":
|
||||
score = int(score * 1.5)
|
||||
reasons.append("semantically similar concepts with no structural link")
|
||||
|
||||
# 5. Peripheral→hub: a low-degree node connecting to a high-degree one
|
||||
deg_u = degrees[u] if degrees is not None else G.degree(u)
|
||||
deg_v = degrees[v] if degrees is not None else G.degree(v)
|
||||
if min(deg_u, deg_v) <= 2 and max(deg_u, deg_v) >= 5:
|
||||
score += 1
|
||||
peripheral = G.nodes[u].get("label", u) if deg_u <= 2 else G.nodes[v].get("label", v)
|
||||
hub = G.nodes[v].get("label", v) if deg_u <= 2 else G.nodes[u].get("label", u)
|
||||
reasons.append(f"peripheral node `{peripheral}` unexpectedly reaches hub `{hub}`")
|
||||
|
||||
return score, reasons
|
||||
|
||||
|
||||
def _cross_file_surprises(G: nx.Graph, communities: dict[int, list[str]], top_n: int) -> list[dict]:
|
||||
"""
|
||||
Cross-file edges between real code/doc entities.
|
||||
Excludes concept nodes, file hub nodes, and plain import edges.
|
||||
Sorted AMBIGUOUS → INFERRED → EXTRACTED.
|
||||
Cross-file edges between real code/doc entities, ranked by a composite
|
||||
surprise score rather than confidence alone.
|
||||
|
||||
Surprise score accounts for:
|
||||
- Confidence (AMBIGUOUS > INFERRED > EXTRACTED)
|
||||
- Cross file-type (code↔paper is more surprising than code↔code)
|
||||
- Cross-repo (different top-level directory)
|
||||
- Cross-community (Leiden says structurally distant)
|
||||
- Peripheral→hub (low-degree node reaching a god node)
|
||||
|
||||
Each result includes a 'why' field explaining what makes it non-obvious.
|
||||
"""
|
||||
surprises = []
|
||||
order = {"AMBIGUOUS": 0, "INFERRED": 1, "EXTRACTED": 2}
|
||||
node_community = _node_community_map(communities)
|
||||
degrees = dict(G.degree())
|
||||
candidates = []
|
||||
|
||||
for u, v, data in G.edges(data=True):
|
||||
# Skip structural scaffolding — not insights
|
||||
relation = data.get("relation", "")
|
||||
if relation in ("imports", "imports_from", "contains", "method"):
|
||||
continue
|
||||
# Skip if either endpoint is a concept or file-level node
|
||||
if _is_concept_node(G, u) or _is_concept_node(G, v):
|
||||
continue
|
||||
if _is_file_node(G, u) or _is_file_node(G, v):
|
||||
@@ -123,28 +295,36 @@ def _cross_file_surprises(G: nx.Graph, communities: dict[int, list[str]], top_n:
|
||||
u_source = G.nodes[u].get("source_file", "")
|
||||
v_source = G.nodes[v].get("source_file", "")
|
||||
|
||||
if u_source and v_source and u_source != v_source:
|
||||
# Respect original edge direction stored in _src/_tgt (if present),
|
||||
# otherwise fall back to u/v which may be in arbitrary order.
|
||||
src_id = data.get("_src", u)
|
||||
tgt_id = data.get("_tgt", v)
|
||||
surprises.append({
|
||||
"source": G.nodes[src_id].get("label", src_id),
|
||||
"target": G.nodes[tgt_id].get("label", tgt_id),
|
||||
"source_files": [
|
||||
G.nodes[src_id].get("source_file", ""),
|
||||
G.nodes[tgt_id].get("source_file", ""),
|
||||
],
|
||||
"confidence": data.get("confidence", "EXTRACTED"),
|
||||
"relation": relation,
|
||||
})
|
||||
if not u_source or not v_source or u_source == v_source:
|
||||
continue
|
||||
|
||||
surprises.sort(key=lambda x: order.get(x["confidence"], 3))
|
||||
if surprises:
|
||||
return surprises[:top_n]
|
||||
score, reasons = _surprise_score(G, u, v, data, node_community, u_source, v_source, degrees)
|
||||
src_id = data.get("_src", u)
|
||||
if src_id not in G.nodes:
|
||||
src_id = u
|
||||
tgt_id = data.get("_tgt", v)
|
||||
if tgt_id not in G.nodes:
|
||||
tgt_id = v
|
||||
candidates.append({
|
||||
"_score": score,
|
||||
"source": G.nodes[src_id].get("label", src_id),
|
||||
"target": G.nodes[tgt_id].get("label", tgt_id),
|
||||
"source_files": [
|
||||
G.nodes[src_id].get("source_file", ""),
|
||||
G.nodes[tgt_id].get("source_file", ""),
|
||||
],
|
||||
"confidence": data.get("confidence", "EXTRACTED"),
|
||||
"relation": relation,
|
||||
"why": "; ".join(reasons) if reasons else "cross-file semantic connection",
|
||||
})
|
||||
|
||||
candidates.sort(key=lambda x: x["_score"], reverse=True)
|
||||
for c in candidates:
|
||||
c.pop("_score")
|
||||
|
||||
if candidates:
|
||||
return candidates[:top_n]
|
||||
|
||||
# Fallback: no semantic cross-file edges found (pure AST corpus).
|
||||
# Surface cross-community bridge edges as structural surprises instead.
|
||||
return _cross_community_surprises(G, communities, top_n)
|
||||
|
||||
|
||||
@@ -155,20 +335,22 @@ def _cross_community_surprises(
|
||||
) -> list[dict]:
|
||||
"""
|
||||
For single-source corpora: find edges that bridge different communities.
|
||||
These are surprising because Leiden grouped everything else tightly —
|
||||
These are surprising because Leiden grouped everything else tightly -
|
||||
these edges cut across the natural structure.
|
||||
|
||||
Falls back to high-betweenness edges if no community info is provided.
|
||||
"""
|
||||
if not communities:
|
||||
# No community info — use edge betweenness centrality
|
||||
# No community info - use edge betweenness centrality
|
||||
if G.number_of_edges() == 0:
|
||||
return []
|
||||
if G.number_of_nodes() > 5000:
|
||||
return []
|
||||
betweenness = nx.edge_betweenness_centrality(G)
|
||||
top_edges = sorted(betweenness.items(), key=lambda x: x[1], reverse=True)[:top_n]
|
||||
result = []
|
||||
for (u, v), score in top_edges:
|
||||
data = G.edges[u, v]
|
||||
data = edge_data(G, u, v)
|
||||
result.append({
|
||||
"source": G.nodes[u].get("label", u),
|
||||
"target": G.nodes[v].get("label", v),
|
||||
@@ -183,7 +365,7 @@ def _cross_community_surprises(
|
||||
return result
|
||||
|
||||
# Build node → community map
|
||||
node_community = {n: cid for cid, nodes in communities.items() for n in nodes}
|
||||
node_community = _node_community_map(communities)
|
||||
|
||||
surprises = []
|
||||
for u, v, data in G.edges(data=True):
|
||||
@@ -197,10 +379,14 @@ def _cross_community_surprises(
|
||||
relation = data.get("relation", "")
|
||||
if relation in ("imports", "imports_from", "contains", "method"):
|
||||
continue
|
||||
# This edge crosses community boundaries — interesting
|
||||
# This edge crosses community boundaries - interesting
|
||||
confidence = data.get("confidence", "EXTRACTED")
|
||||
src_id = data.get("_src", u)
|
||||
if src_id not in G.nodes:
|
||||
src_id = u
|
||||
tgt_id = data.get("_tgt", v)
|
||||
if tgt_id not in G.nodes:
|
||||
tgt_id = v
|
||||
surprises.append({
|
||||
"source": G.nodes[src_id].get("label", src_id),
|
||||
"target": G.nodes[tgt_id].get("label", tgt_id),
|
||||
@@ -218,7 +404,7 @@ def _cross_community_surprises(
|
||||
order = {"AMBIGUOUS": 0, "INFERRED": 1, "EXTRACTED": 2}
|
||||
surprises.sort(key=lambda x: order.get(x["confidence"], 3))
|
||||
|
||||
# Deduplicate by community pair — one representative edge per (A→B) boundary.
|
||||
# Deduplicate by community pair - one representative edge per (A→B) boundary.
|
||||
# Without this, a single high-betweenness god node dominates all results.
|
||||
seen_pairs: set[tuple] = set()
|
||||
deduped = []
|
||||
@@ -241,8 +427,11 @@ def suggest_questions(
|
||||
Based on: AMBIGUOUS edges, bridge nodes, underexplored god nodes, isolated nodes.
|
||||
Each question has a 'type', 'question', and 'why' field.
|
||||
"""
|
||||
if community_labels:
|
||||
community_labels = {int(k) if isinstance(k, str) else k: v for k, v in community_labels.items()}
|
||||
|
||||
questions = []
|
||||
node_community = {n: cid for cid, nodes in communities.items() for n in nodes}
|
||||
node_community = _node_community_map(communities)
|
||||
|
||||
# 1. AMBIGUOUS edges → unresolved relationship questions
|
||||
for u, v, data in G.edges(data=True):
|
||||
@@ -253,12 +442,13 @@ def suggest_questions(
|
||||
questions.append({
|
||||
"type": "ambiguous_edge",
|
||||
"question": f"What is the exact relationship between `{ul}` and `{vl}`?",
|
||||
"why": f"Edge tagged AMBIGUOUS (relation: {relation}) — confidence is low.",
|
||||
"why": f"Edge tagged AMBIGUOUS (relation: {relation}) - confidence is low.",
|
||||
})
|
||||
|
||||
# 2. Bridge nodes (high betweenness) → cross-cutting concern questions
|
||||
if G.number_of_edges() > 0:
|
||||
betweenness = nx.betweenness_centrality(G)
|
||||
k = min(100, G.number_of_nodes()) if G.number_of_nodes() > 1000 else None
|
||||
betweenness = nx.betweenness_centrality(G, k=k, seed=42)
|
||||
# Top bridge nodes that are NOT file-level hubs
|
||||
bridges = sorted(
|
||||
[(n, s) for n, s in betweenness.items()
|
||||
@@ -277,7 +467,7 @@ def suggest_questions(
|
||||
questions.append({
|
||||
"type": "bridge_node",
|
||||
"question": f"Why does `{label}` connect `{comm_label}` to {', '.join(f'`{l}`' for l in other_labels)}?",
|
||||
"why": f"High betweenness centrality ({score:.3f}) — this node is a cross-community bridge.",
|
||||
"why": f"High betweenness centrality ({score:.3f}) - this node is a cross-community bridge.",
|
||||
})
|
||||
|
||||
# 3. God nodes with many INFERRED edges → verification questions
|
||||
@@ -298,13 +488,17 @@ def suggest_questions(
|
||||
others = []
|
||||
for u, v, d in inferred[:2]:
|
||||
src_id = d.get("_src", u)
|
||||
if src_id not in G.nodes:
|
||||
src_id = u
|
||||
tgt_id = d.get("_tgt", v)
|
||||
if tgt_id not in G.nodes:
|
||||
tgt_id = v
|
||||
other_id = tgt_id if src_id == node_id else src_id
|
||||
others.append(G.nodes[other_id].get("label", other_id))
|
||||
questions.append({
|
||||
"type": "verify_inferred",
|
||||
"question": f"Are the {len(inferred)} inferred relationships involving `{label}` (e.g. with `{others[0]}` and `{others[1]}`) actually correct?",
|
||||
"why": f"`{label}` has {len(inferred)} INFERRED edges — model-reasoned connections that need verification.",
|
||||
"why": f"`{label}` has {len(inferred)} INFERRED edges - model-reasoned connections that need verification.",
|
||||
})
|
||||
|
||||
# 4. Isolated or weakly-connected nodes → exploration questions
|
||||
@@ -317,7 +511,7 @@ def suggest_questions(
|
||||
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 - possible documentation gaps or missing edges.",
|
||||
})
|
||||
|
||||
# 5. Low-cohesion communities → structural questions
|
||||
@@ -329,7 +523,7 @@ def suggest_questions(
|
||||
questions.append({
|
||||
"type": "low_cohesion",
|
||||
"question": f"Should `{label}` be split into smaller, more focused modules?",
|
||||
"why": f"Cohesion score {score} — nodes in this community are weakly interconnected.",
|
||||
"why": f"Cohesion score {score} - nodes in this community are weakly interconnected.",
|
||||
})
|
||||
|
||||
if not questions:
|
||||
@@ -375,7 +569,9 @@ def graph_diff(G_old: nx.Graph, G_new: nx.Graph) -> dict:
|
||||
]
|
||||
|
||||
def edge_key(G: nx.Graph, u: str, v: str, data: dict) -> tuple:
|
||||
return (u, v, data.get("relation", ""))
|
||||
if G.is_directed():
|
||||
return (u, v, data.get("relation", ""))
|
||||
return (min(u, v), max(u, v), data.get("relation", ""))
|
||||
|
||||
old_edge_keys = {
|
||||
edge_key(G_old, u, v, d)
|
||||
@@ -427,3 +623,110 @@ def graph_diff(G_old: nx.Graph, G_new: nx.Graph) -> dict:
|
||||
"removed_edges": removed_edges_list,
|
||||
"summary": summary,
|
||||
}
|
||||
|
||||
|
||||
def find_import_cycles(
|
||||
G: nx.Graph,
|
||||
max_cycle_length: int = 5,
|
||||
top_n: int = 20,
|
||||
) -> list[dict]:
|
||||
"""Detect circular import dependencies at the file level.
|
||||
|
||||
Collapses symbol-level nodes to their parent file (using source_file attr
|
||||
or 'contains' edges), builds a directed file-level graph from imports_from
|
||||
edges, then finds simple cycles.
|
||||
|
||||
Args:
|
||||
G: The full knowledge graph (may be undirected or directed).
|
||||
max_cycle_length: Only report cycles with at most this many files.
|
||||
top_n: Maximum number of cycles to return (shortest first).
|
||||
|
||||
Returns:
|
||||
List of cycle records with stable structure:
|
||||
{
|
||||
"cycle": ["a.ts", "b.ts"],
|
||||
"length": 2,
|
||||
"why": "circular dependency"
|
||||
}
|
||||
"""
|
||||
def _endpoint_source_file(node_id: str) -> str:
|
||||
attrs = G.nodes.get(node_id, {})
|
||||
src_file = attrs.get("source_file", "")
|
||||
return src_file if isinstance(src_file, str) else ""
|
||||
|
||||
# Step 1: Build a directed file-level graph from import/re-export edges.
|
||||
# IMPORTANT: resolve endpoints using source_file only; never infer from label/id.
|
||||
file_graph = nx.DiGraph()
|
||||
|
||||
for u, v, data in G.edges(data=True):
|
||||
rel = data.get("relation", "")
|
||||
if rel not in ("imports_from", "re_exports"):
|
||||
continue
|
||||
|
||||
src_file_attr = data.get("source_file", "")
|
||||
if not isinstance(src_file_attr, str) or not src_file_attr:
|
||||
continue
|
||||
|
||||
u_file = _endpoint_source_file(u)
|
||||
v_file = _endpoint_source_file(v)
|
||||
|
||||
# Works for both DiGraph and Graph inputs:
|
||||
# orient edge from edge.source_file endpoint to the opposite endpoint.
|
||||
if u_file == src_file_attr:
|
||||
tgt_file = v_file
|
||||
elif v_file == src_file_attr:
|
||||
tgt_file = u_file
|
||||
else:
|
||||
# Fallback: if source endpoint cannot be matched exactly,
|
||||
# still treat edge.source_file as source and pick the opposite endpoint
|
||||
# only if one endpoint has a real source_file.
|
||||
tgt_file = v_file if v_file and v_file != src_file_attr else u_file
|
||||
|
||||
if not tgt_file:
|
||||
continue
|
||||
|
||||
file_graph.add_edge(src_file_attr, tgt_file)
|
||||
|
||||
if not file_graph.edges():
|
||||
return []
|
||||
|
||||
# Step 2: Find simple cycles, bounded by length.
|
||||
# Pass length_bound so networkx prunes during enumeration rather than
|
||||
# enumerating all elementary cycles and post-filtering — avoids exponential
|
||||
# blowup on dense graphs with many long cycles (#1196).
|
||||
cycles: list[list[str]] = []
|
||||
for cycle in nx.simple_cycles(file_graph, length_bound=max_cycle_length):
|
||||
if len(cycle) <= max_cycle_length:
|
||||
cycles.append(cycle)
|
||||
if len(cycles) >= top_n * 10:
|
||||
# Stop early to avoid combinatorial explosion
|
||||
break
|
||||
|
||||
# Step 3: Sort by length (shortest = tightest coupling), then deduplicate.
|
||||
cycles.sort(key=len)
|
||||
|
||||
# Deduplicate rotations: normalize each cycle by starting from the
|
||||
# lexicographically smallest element.
|
||||
seen: set[tuple[str, ...]] = set()
|
||||
unique_cycles: list[list[str]] = []
|
||||
for cycle in cycles:
|
||||
core = list(cycle)
|
||||
if not core:
|
||||
continue
|
||||
min_idx = core.index(min(core))
|
||||
normalized = tuple(core[min_idx:] + core[:min_idx])
|
||||
if normalized not in seen:
|
||||
seen.add(normalized)
|
||||
unique_cycles.append(list(normalized))
|
||||
if len(unique_cycles) >= top_n:
|
||||
break
|
||||
|
||||
result: list[dict] = []
|
||||
for cycle in unique_cycles:
|
||||
result.append({
|
||||
"cycle": cycle,
|
||||
"length": len(cycle),
|
||||
"why": "circular dependency",
|
||||
})
|
||||
|
||||
return result
|
||||
+39
-8
@@ -1,21 +1,45 @@
|
||||
"""Token-reduction benchmark — measures how much context graphify saves vs naive full-corpus approach."""
|
||||
"""Token-reduction benchmark - measures how much context graphify saves vs naive full-corpus approach."""
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
|
||||
from graphify.build import edge_data
|
||||
from graphify.serve import _query_terms
|
||||
from graphify.paths import default_graph_json as _default_graph_json
|
||||
|
||||
|
||||
_CHARS_PER_TOKEN = 4 # standard approximation
|
||||
|
||||
|
||||
def _safe(unicode_char: str, ascii_fallback: str) -> str:
|
||||
"""Return unicode_char if stdout can encode it, else ascii_fallback.
|
||||
|
||||
Windows consoles often default to cp1252 which cannot encode box-drawing
|
||||
or arrow glyphs; printing them raises UnicodeEncodeError mid-output.
|
||||
"""
|
||||
encoding = getattr(sys.stdout, "encoding", None) or ""
|
||||
try:
|
||||
unicode_char.encode(encoding)
|
||||
return unicode_char
|
||||
except (UnicodeEncodeError, LookupError):
|
||||
return ascii_fallback
|
||||
|
||||
|
||||
def _hr(width: int = 50) -> str:
|
||||
"""Horizontal rule that survives non-UTF-8 stdout (e.g. Windows cp1252 console)."""
|
||||
return _safe("─", "-") * width
|
||||
|
||||
|
||||
def _estimate_tokens(text: str) -> int:
|
||||
return max(1, len(text) // _CHARS_PER_TOKEN)
|
||||
|
||||
|
||||
def _query_subgraph_tokens(G: nx.Graph, question: str, depth: int = 3) -> int:
|
||||
"""Run BFS from best-matching nodes and return estimated tokens in the subgraph context."""
|
||||
terms = [t.lower() for t in question.split() if len(t) > 2]
|
||||
terms = _query_terms(question)
|
||||
scored = []
|
||||
for nid, data in G.nodes(data=True):
|
||||
label = data.get("label", "").lower()
|
||||
@@ -46,7 +70,7 @@ def _query_subgraph_tokens(G: nx.Graph, question: str, depth: int = 3) -> int:
|
||||
lines.append(f"NODE {d.get('label', nid)} src={d.get('source_file', '')} loc={d.get('source_location', '')}")
|
||||
for u, v in edges_seen:
|
||||
if u in visited and v in visited:
|
||||
d = G.edges[u, v]
|
||||
d = edge_data(G, u, v)
|
||||
lines.append(f"EDGE {G.nodes[u].get('label', u)} --{d.get('relation', '')}--> {G.nodes[v].get('label', v)}")
|
||||
|
||||
return _estimate_tokens("\n".join(lines))
|
||||
@@ -62,7 +86,7 @@ _SAMPLE_QUESTIONS = [
|
||||
|
||||
|
||||
def run_benchmark(
|
||||
graph_path: str = ".graphify/graph.json",
|
||||
graph_path: str | None = None,
|
||||
corpus_words: int | None = None,
|
||||
questions: list[str] | None = None,
|
||||
) -> dict:
|
||||
@@ -75,8 +99,14 @@ def run_benchmark(
|
||||
|
||||
Returns dict with: corpus_tokens, avg_query_tokens, reduction_ratio, per_question
|
||||
"""
|
||||
data = json.loads(Path(graph_path).read_text())
|
||||
G = json_graph.node_link_graph(data, edges="links")
|
||||
graph_path = graph_path or _default_graph_json()
|
||||
from graphify.security import check_graph_file_size_cap
|
||||
check_graph_file_size_cap(Path(graph_path))
|
||||
data = json.loads(Path(graph_path).read_text(encoding="utf-8"))
|
||||
try:
|
||||
G = json_graph.node_link_graph(data, edges="links")
|
||||
except TypeError:
|
||||
G = json_graph.node_link_graph(data)
|
||||
|
||||
if corpus_words is None:
|
||||
# Rough estimate: each node label is ~3 words, plus source context
|
||||
@@ -115,8 +145,9 @@ def print_benchmark(result: dict) -> None:
|
||||
return
|
||||
|
||||
print(f"\ngraphify token reduction benchmark")
|
||||
print(f"{'─' * 50}")
|
||||
print(f" Corpus: {result['corpus_words']:,} words → ~{result['corpus_tokens']:,} tokens (naive)")
|
||||
print(_hr(50))
|
||||
arrow = _safe("→", "->")
|
||||
print(f" Corpus: {result['corpus_words']:,} words {arrow} ~{result['corpus_tokens']:,} tokens (naive)")
|
||||
print(f" Graph: {result['nodes']:,} nodes, {result['edges']:,} edges")
|
||||
print(f" Avg query cost: ~{result['avg_query_tokens']:,} tokens")
|
||||
print(f" Reduction: {result['reduction_ratio']}x fewer tokens per query")
|
||||
|
||||
+909
-15
@@ -1,31 +1,925 @@
|
||||
# assemble node+edge dicts into a NetworkX graph, preserving edge direction
|
||||
#
|
||||
# Node deduplication — three layers:
|
||||
#
|
||||
# 1. Within a file (AST): each extractor tracks a `seen_ids` set. A node ID is
|
||||
# emitted at most once per file, so duplicate class/function definitions in
|
||||
# the same source file are collapsed to the first occurrence.
|
||||
#
|
||||
# 2. Between files (build): NetworkX G.add_node() is idempotent — calling it
|
||||
# twice with the same ID overwrites the attributes with the second call's
|
||||
# values. Nodes are added in extraction order (AST first, then semantic),
|
||||
# so if the same entity is extracted by both passes the semantic node
|
||||
# silently overwrites the AST node. This is intentional: semantic nodes
|
||||
# carry richer labels and cross-file context, while AST nodes have precise
|
||||
# source_location. If you need to change the priority, reorder extractions
|
||||
# passed to build().
|
||||
#
|
||||
# 3. Semantic merge (skill): before calling build(), the skill merges cached
|
||||
# and new semantic results using an explicit `seen` set keyed on node["id"],
|
||||
# so duplicates across cache hits and new extractions are resolved there
|
||||
# before any graph construction happens.
|
||||
#
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import unicodedata
|
||||
from pathlib import Path
|
||||
import networkx as nx
|
||||
from .ids import make_id, normalize_id as _normalize_id
|
||||
from .paths import default_graph_json as _default_graph_json
|
||||
from .validate import validate_extraction
|
||||
|
||||
|
||||
def build_from_json(extraction: dict) -> nx.Graph:
|
||||
errors = validate_extraction(extraction)
|
||||
if errors:
|
||||
print(f"[graphify] Extraction warning ({len(errors)} issues): {errors[0]}", file=sys.stderr)
|
||||
G = nx.Graph()
|
||||
# Synonym mapper for known invalid file_type values that LLM subagents commonly
|
||||
# emit. Keeps semantic intent close (markdown→document, tool→code) and falls
|
||||
# back to "concept" for any other invalid value (see #840).
|
||||
_FILE_TYPE_SYNONYMS = {
|
||||
"markdown": "document",
|
||||
"text": "document",
|
||||
"tool": "code",
|
||||
"library": "code",
|
||||
"pattern": "concept",
|
||||
"principle": "concept",
|
||||
"constraint": "concept",
|
||||
"tech": "concept",
|
||||
"technology": "concept",
|
||||
"data-source": "concept",
|
||||
"data_source": "concept",
|
||||
"gotcha": "concept",
|
||||
"framework": "concept",
|
||||
}
|
||||
|
||||
|
||||
# Hyperedge member lists are canonically keyed `nodes` (see graphify/llm.py
|
||||
# extraction spec), but LLM/subagent drift and externally-supplied graph.json
|
||||
# sometimes emit `members` or `node_ids`. _normalize_hyperedge_members folds
|
||||
# those aliases into `nodes` at ingest so every downstream consumer reads one
|
||||
# canonical key — mirroring the `from`/`to` edge-endpoint tolerance below.
|
||||
_HE_MEMBER_ALIASES = ("members", "node_ids")
|
||||
|
||||
|
||||
def _normalize_hyperedge_members(he: object) -> None:
|
||||
"""Canonicalize a hyperedge's member list onto the `nodes` key, in place.
|
||||
|
||||
If `nodes` is already a list it wins (canonical), and only stray alias keys
|
||||
are dropped. Otherwise the first alias (`members`, then `node_ids`) that is a
|
||||
list is moved to `nodes`, deduped preserving order, with a single stderr
|
||||
WARNING naming the hyperedge id and alias used. Leftover alias keys are
|
||||
always removed so downstream code never re-reads them.
|
||||
"""
|
||||
if not isinstance(he, dict):
|
||||
return
|
||||
if not isinstance(he.get("nodes"), list):
|
||||
for alias in _HE_MEMBER_ALIASES:
|
||||
val = he.get(alias)
|
||||
if isinstance(val, list):
|
||||
seen: set = set()
|
||||
deduped: list = []
|
||||
for ref in val:
|
||||
try:
|
||||
is_dupe = ref in seen
|
||||
except TypeError:
|
||||
is_dupe = False # unhashable ref: keep it, validator flags it
|
||||
if is_dupe:
|
||||
continue
|
||||
try:
|
||||
seen.add(ref)
|
||||
except TypeError:
|
||||
pass
|
||||
deduped.append(ref)
|
||||
he["nodes"] = deduped
|
||||
print(
|
||||
f"[graphify] WARNING: hyperedge "
|
||||
f"'{he.get('id', '?')}' uses field '{alias}' instead of "
|
||||
f"'nodes'; normalizing.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
break
|
||||
# Drop any leftover alias keys regardless of which branch ran above.
|
||||
for alias in _HE_MEMBER_ALIASES:
|
||||
he.pop(alias, None)
|
||||
|
||||
|
||||
def _norm_source_file(p: str | None, root: str | None = None) -> str | None:
|
||||
"""Normalize path separators and relativize absolute paths.
|
||||
|
||||
Converts backslashes to forward slashes (Windows compatibility) and, when
|
||||
root is provided, strips the absolute prefix from paths produced by semantic
|
||||
subagents so source_file is always repo-relative (fixes #932).
|
||||
"""
|
||||
if not p:
|
||||
return p
|
||||
p = p.replace("\\", "/")
|
||||
if root and os.path.isabs(p):
|
||||
try:
|
||||
p = Path(p).relative_to(root).as_posix()
|
||||
except ValueError:
|
||||
# Lexical relative_to failed. Retry with both sides fully resolved:
|
||||
# a symlinked scan root (macOS /var -> /private/var, or a symlinked
|
||||
# home/worktree) makes the raw prefixes differ even though they point
|
||||
# at the same dir, which otherwise silently defeats prune/replace
|
||||
# matching. Only the slow path resolves, so the common lexical match
|
||||
# stays filesystem-free.
|
||||
try:
|
||||
p = Path(p).resolve().relative_to(Path(root).resolve()).as_posix()
|
||||
except (ValueError, OSError):
|
||||
pass
|
||||
return p
|
||||
|
||||
|
||||
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).
|
||||
|
||||
Prefers the committed ``graphify-out/.graphify_root`` marker — the authoritative
|
||||
scan root graphify records at build/watch time (#686/#1423) — then falls back to
|
||||
the directory that contains the output dir (``graph.json``'s grandparent, i.e.
|
||||
``<root>/graphify-out/graph.json`` -> ``<root>``). Returns None if neither
|
||||
resolves, in which case normalization is a no-op (prior behavior).
|
||||
"""
|
||||
try:
|
||||
marker = graph_path.parent / ".graphify_root"
|
||||
if marker.exists():
|
||||
recorded = marker.read_text(encoding="utf-8").strip()
|
||||
if recorded:
|
||||
return str(Path(recorded).resolve())
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
return str(graph_path.parent.parent.resolve())
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def edge_data(G: nx.Graph, u: str, v: str) -> dict:
|
||||
"""Return one edge attribute dict for (u, v), tolerating MultiGraph.
|
||||
|
||||
For MultiGraph/MultiDiGraph there can be multiple parallel edges;
|
||||
this returns the first one (sufficient for callers that only need
|
||||
relation/confidence for rendering). Fixes #796.
|
||||
"""
|
||||
raw = G[u][v]
|
||||
if isinstance(G, (nx.MultiGraph, nx.MultiDiGraph)):
|
||||
return next(iter(raw.values()), {})
|
||||
return raw
|
||||
|
||||
|
||||
def edge_datas(G: nx.Graph, u: str, v: str) -> list[dict]:
|
||||
"""Return every edge attribute dict for (u, v); always a list."""
|
||||
raw = G[u][v]
|
||||
if isinstance(G, (nx.MultiGraph, nx.MultiDiGraph)):
|
||||
return list(raw.values())
|
||||
return [raw]
|
||||
|
||||
|
||||
def dedupe_nodes(nodes: list[dict]) -> list[dict]:
|
||||
"""Collapse nodes sharing an ``id``, last-writer-wins on attributes.
|
||||
|
||||
Mirrors what ``build_from_json``'s ``G.add_node`` does implicitly (idempotent;
|
||||
a later node overwrites an earlier one's attributes). The ``--no-cluster``
|
||||
write path dumps the raw node list without building a graph, so same-id nodes
|
||||
— e.g. a Swift ``type=module`` anchor emitted once per importing file (#1327)
|
||||
— would otherwise appear as duplicates. Insertion order follows each id's
|
||||
first appearance; the retained dict is the last one seen.
|
||||
"""
|
||||
by_id: dict = {}
|
||||
for n in nodes:
|
||||
nid = n.get("id")
|
||||
if nid is None:
|
||||
continue
|
||||
by_id[nid] = n
|
||||
return list(by_id.values())
|
||||
|
||||
|
||||
def dedupe_edges(edges: list[dict]) -> list[dict]:
|
||||
"""Collapse exact parallel edges by ``(source, target, relation)``, keeping the
|
||||
first occurrence.
|
||||
|
||||
The clustered build path runs edges through a NetworkX ``DiGraph``, which
|
||||
collapses parallel edges automatically. The ``--no-cluster`` and incremental
|
||||
``update`` write paths bypass NetworkX and concatenate edge lists raw, so
|
||||
duplicates accumulate and edge counts become non-deterministic across build
|
||||
modes / repeated updates (#1317). Deduping on the connectivity identity is
|
||||
zero-signal-loss and restores idempotency. Callers that intentionally keep
|
||||
parallel edges (multigraph output) must not use this.
|
||||
"""
|
||||
seen: set[tuple] = set()
|
||||
out: list[dict] = []
|
||||
for e in edges:
|
||||
key = (e.get("source"), e.get("target"), e.get("relation"))
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
out.append(e)
|
||||
return out
|
||||
|
||||
|
||||
def _old_file_stems(rel: Path) -> list[str]:
|
||||
"""Pre-migration stem forms a semantic fragment may have used for ``rel``.
|
||||
|
||||
Ordered longest-first so prefix stripping is greedy and unambiguous:
|
||||
- one-parent form: ``parent.stem`` (the old _file_stem rule, #550-era)
|
||||
- zero-parent form: ``stem`` (the old llm.py prompt rule, #1509)
|
||||
"""
|
||||
forms: list[str] = []
|
||||
parent = rel.parent.name
|
||||
if parent and parent not in (".", ""):
|
||||
forms.append(make_id(f"{parent}.{rel.stem}"))
|
||||
forms.append(make_id(rel.stem))
|
||||
# Dedupe while preserving order (top-level files collapse both forms).
|
||||
seen: set[str] = set()
|
||||
return [f for f in forms if f and not (f in seen or seen.add(f))]
|
||||
|
||||
|
||||
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
|
||||
reconciles with the AST node instead of spawning a ghost (#1504/#1509).
|
||||
|
||||
Drift-proof by construction: the new id is computed from ``source_file`` in
|
||||
code, never trusted from the fragment's own ``id`` string. AST-origin nodes
|
||||
are skipped (they are already canonical via the extract() post-pass)."""
|
||||
from graphify.extractors.base import _file_stem # local: avoid import cost at module load
|
||||
|
||||
remap: dict[str, str] = {}
|
||||
for node in nodes:
|
||||
if not isinstance(node, dict):
|
||||
continue
|
||||
if node.get("_origin") == "ast":
|
||||
continue
|
||||
nid = node.get("id")
|
||||
sf = node.get("source_file")
|
||||
if not nid or not isinstance(nid, str) or not sf:
|
||||
continue
|
||||
sf_norm = _norm_source_file(str(sf), root) or str(sf)
|
||||
rel = Path(sf_norm)
|
||||
if rel.is_absolute():
|
||||
continue # can't relativize (no/failed root) — leave id untouched
|
||||
new_stem = make_id(_file_stem(rel))
|
||||
if not new_stem:
|
||||
continue
|
||||
norm_nid = _normalize_id(nid)
|
||||
new_id: str | None = None
|
||||
for old_stem in _old_file_stems(rel):
|
||||
if old_stem == new_stem:
|
||||
continue # already canonical for this form
|
||||
if norm_nid == old_stem:
|
||||
new_id = new_stem # the file node itself
|
||||
break
|
||||
prefix = old_stem + "_"
|
||||
if norm_nid.startswith(prefix):
|
||||
entity = norm_nid[len(prefix):]
|
||||
new_id = make_id(new_stem, entity)
|
||||
break
|
||||
if new_id and new_id != nid:
|
||||
remap[nid] = new_id
|
||||
return remap
|
||||
|
||||
|
||||
def graph_has_legacy_ids(nodes: list, root: str | Path | None = None, sample: int = 300) -> 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.
|
||||
|
||||
Heuristic and cheap: only **file-level** nodes (source_location ``L1``) are
|
||||
inspected, because their ID is unambiguously the file stem. Symbol nodes are
|
||||
skipped — some extractors scope a symbol by package/directory (Go's
|
||||
``_make_id(pkg_dir, name)`` → ``sub_thing``), which can coincide with an old
|
||||
file-stem form and would otherwise false-positive. Returns True as soon as one
|
||||
file node's ID matches an OLD stem form but not the canonical full-path form."""
|
||||
from graphify.extractors.base import _file_stem
|
||||
_r = str(root) if root is not None else None
|
||||
checked = 0
|
||||
for node in nodes:
|
||||
if not isinstance(node, dict):
|
||||
continue
|
||||
if str(node.get("source_location") or "") != "L1":
|
||||
continue # only file-level nodes carry an unambiguous file-stem ID
|
||||
nid = node.get("id")
|
||||
sf = node.get("source_file")
|
||||
if not nid or not isinstance(nid, str) or not sf:
|
||||
continue
|
||||
rel = Path(_norm_source_file(str(sf), _r) or str(sf))
|
||||
if rel.is_absolute():
|
||||
continue
|
||||
new_stem = make_id(_file_stem(rel))
|
||||
if not new_stem:
|
||||
continue
|
||||
norm = _normalize_id(nid)
|
||||
if norm == new_stem or norm.startswith(new_stem + "_"):
|
||||
checked += 1
|
||||
else:
|
||||
for old in _old_file_stems(rel):
|
||||
if old != new_stem and (norm == old or norm.startswith(old + "_")):
|
||||
return True
|
||||
checked += 1
|
||||
if checked >= sample:
|
||||
break
|
||||
return False
|
||||
|
||||
|
||||
def build_from_json(extraction: dict, *, directed: bool = False, root: str | Path | None = None) -> nx.Graph:
|
||||
"""Build a NetworkX graph from an extraction dict.
|
||||
|
||||
directed=True produces a DiGraph that preserves edge direction (source→target).
|
||||
directed=False (default) produces an undirected Graph for backward compatibility.
|
||||
root: if given, absolute source_file paths from semantic subagents are made
|
||||
relative to root so all nodes share a consistent path key (#932).
|
||||
"""
|
||||
_root = str(Path(root).resolve()) if root else None
|
||||
# NetworkX <= 3.1 serialised edges as "links"; remap to "edges" for compatibility.
|
||||
if "edges" not in extraction and "links" in extraction:
|
||||
extraction = dict(extraction, edges=extraction["links"])
|
||||
|
||||
# Canonicalize legacy node/edge schema before validation.
|
||||
for node in extraction.get("nodes", []):
|
||||
if not isinstance(node, dict):
|
||||
continue
|
||||
if "source" in node and "source_file" not in node:
|
||||
# Count edges that reference this node so the warning is actionable (#479)
|
||||
node_id = node.get("id", "?")
|
||||
affected_edges = sum(
|
||||
1 for e in extraction.get("edges", [])
|
||||
if e.get("source") == node_id or e.get("target") == node_id
|
||||
)
|
||||
print(
|
||||
f"[graphify] WARNING: node '{node_id}' uses field 'source' instead of "
|
||||
f"'source_file' — {affected_edges} edge(s) may be misrouted. "
|
||||
f"Rename the field to 'source_file' to silence this warning.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
node["source_file"] = node.pop("source")
|
||||
# Default missing/None file_type to "concept" so legacy graph.json
|
||||
# entries (and stub nodes preserved by `_rebuild_code` from older
|
||||
# graphify versions that didn't always populate file_type) don't
|
||||
# trigger spurious "invalid file_type 'None'" validator warnings (#660).
|
||||
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"}:
|
||||
node["file_type"] = _FILE_TYPE_SYNONYMS.get(ft, "concept")
|
||||
|
||||
# Canonicalize hyperedge member lists (#1561): producers sometimes key the
|
||||
# member list `members`/`node_ids` instead of `nodes`. Fold aliases onto
|
||||
# `nodes` here — BEFORE validation and the semantic-rekey loop below — so
|
||||
# every downstream consumer (rekey, source_file relativize, to_json) reads
|
||||
# one canonical key, the same way edge endpoints alias from/to at build.
|
||||
for he in extraction.get("hyperedges", []) or []:
|
||||
_normalize_hyperedge_members(he)
|
||||
|
||||
errors = validate_extraction(extraction)
|
||||
# Dangling edges (stdlib/external imports) are expected - only warn about real schema errors.
|
||||
real_errors = [e for e in errors if "does not match any node id" not in e]
|
||||
if real_errors:
|
||||
print(f"[graphify] Extraction warning ({len(real_errors)} issues): {real_errors[0]}", file=sys.stderr)
|
||||
# Deterministic semantic re-key (#1504/#1509): the node-ID stem is now the
|
||||
# full repo-relative path (docs/v1/api/README.md -> docs_v1_api_readme), but
|
||||
# the semantic cache is UNVERSIONED, so a cached/LLM fragment can still carry
|
||||
# an OLD short id whose stem was just the immediate parent dir (api_readme),
|
||||
# or a prompt-drifting id with zero parent dirs (readme). Rather than trust
|
||||
# LLM prose to emit the right stem, we re-derive every non-AST node's id from
|
||||
# its own source_file in code, so a drifted fragment physically reconciles
|
||||
# with the AST node instead of spawning a ghost / a re-bill. AST-origin nodes
|
||||
# already carry canonical ids (the extract() id-remap post-pass guarantees it)
|
||||
# and are left untouched.
|
||||
_rekey: dict[str, str] = _semantic_id_remap(extraction.get("nodes", []), _root)
|
||||
if _rekey:
|
||||
for node in extraction.get("nodes", []):
|
||||
if isinstance(node, dict) and node.get("id") in _rekey:
|
||||
node["id"] = _rekey[node["id"]]
|
||||
for edge in extraction.get("edges", []):
|
||||
if not isinstance(edge, dict):
|
||||
continue
|
||||
if edge.get("source") in _rekey:
|
||||
edge["source"] = _rekey[edge["source"]]
|
||||
if edge.get("target") in _rekey:
|
||||
edge["target"] = _rekey[edge["target"]]
|
||||
for he in extraction.get("hyperedges", []) or []:
|
||||
if isinstance(he, dict) and isinstance(he.get("nodes"), list):
|
||||
he["nodes"] = [_rekey.get(n, n) for n in he["nodes"]]
|
||||
|
||||
G: nx.Graph = nx.DiGraph() if directed else nx.Graph()
|
||||
for node in extraction.get("nodes", []):
|
||||
# Skip dict nodes with a missing or non-hashable id (e.g. a list emitted
|
||||
# by a buggy LLM extraction) so NetworkX add_node never raises
|
||||
# TypeError: unhashable type. Non-dict nodes are deliberately left to
|
||||
# raise as before, so callers that probe build for shape errors (e.g.
|
||||
# the multigraph diagnostic) still observe the malformed shape.
|
||||
if isinstance(node, dict):
|
||||
if "id" not in node:
|
||||
continue
|
||||
try:
|
||||
hash(node["id"])
|
||||
except TypeError:
|
||||
print(
|
||||
f"[graphify] WARNING: skipping node with non-hashable id "
|
||||
f"{node['id']!r} (must be a string).",
|
||||
file=sys.stderr,
|
||||
)
|
||||
continue
|
||||
if "source_file" in node:
|
||||
node["source_file"] = _norm_source_file(node["source_file"], _root)
|
||||
G.add_node(node["id"], **{k: v for k, v in node.items() if k != "id"})
|
||||
for edge in extraction.get("edges", []):
|
||||
node_set = set(G.nodes())
|
||||
|
||||
# #1145 (extended): merge LLM ghost-duplicate nodes into AST canonical nodes.
|
||||
# Original bug: AST uses parent-qualified IDs (mingpt_bpe_get_pairs) while LLM
|
||||
# uses bare-stem IDs (bpe_get_pairs) — different IDs, same symbol.
|
||||
# Original fix only caught LLM nodes with source_location=None; LLM now
|
||||
# populates source_location, so those ghosts survived. Extended fix: use
|
||||
# _origin=="ast" as the canonical signal. AST nodes always win; any non-AST
|
||||
# node sharing (basename, label) with an AST node is a ghost.
|
||||
_loc_nodes: dict[tuple[str, str], str] = {} # (basename, label) -> canonical node id
|
||||
_loc_collisions: set[tuple[str, str]] = set() # keys shared by 2+ AST nodes
|
||||
_noloc_nodes: dict[tuple[str, str], str] = {} # (basename, label) -> ghost node id
|
||||
|
||||
# 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
|
||||
# directories, e.g. render in two index.ts), the key is ambiguous: merging a
|
||||
# ghost would pick an arbitrary winner via set-iteration order (#1257). Track
|
||||
# those keys so Pass 2 skips them — same conservatism as
|
||||
# _rewire_unique_stub_nodes, which only merges when exactly one real def exists.
|
||||
for nid in node_set:
|
||||
attrs = G.nodes[nid]
|
||||
label = str(attrs.get("label", "")).strip()
|
||||
sf = str(attrs.get("source_file", ""))
|
||||
basename = Path(sf).name if sf else ""
|
||||
if not label or not basename:
|
||||
continue
|
||||
is_ast = attrs.get("_origin") == "ast"
|
||||
if attrs.get("source_location") or is_ast:
|
||||
key = (basename, label)
|
||||
if is_ast:
|
||||
# Two AST nodes on the same key is an ambiguous collision.
|
||||
if key in _loc_nodes and G.nodes[_loc_nodes[key]].get("_origin") == "ast":
|
||||
_loc_collisions.add(key)
|
||||
# AST-origin nodes always overwrite a prior non-AST entry.
|
||||
_loc_nodes[key] = nid
|
||||
elif key not in _loc_nodes:
|
||||
_loc_nodes[key] = nid
|
||||
|
||||
# Pass 2: find ghosts — non-AST nodes that have an AST canonical twin.
|
||||
for nid in node_set:
|
||||
attrs = G.nodes[nid]
|
||||
if attrs.get("_origin") == "ast":
|
||||
continue # AST nodes are never ghosts
|
||||
label = str(attrs.get("label", "")).strip()
|
||||
sf = str(attrs.get("source_file", ""))
|
||||
basename = Path(sf).name if sf else ""
|
||||
if not label or not basename:
|
||||
continue
|
||||
key = (basename, label)
|
||||
if key in _loc_collisions:
|
||||
continue # ambiguous key: no safe canonical winner, leave ghost intact
|
||||
if key in _loc_nodes and _loc_nodes[key] != nid:
|
||||
_noloc_nodes[key] = nid
|
||||
# For every ghost that has an AST counterpart, record a remap.
|
||||
_ghost_remap: dict[str, str] = {} # ghost_id -> canonical_id
|
||||
for key, sem_id in _noloc_nodes.items():
|
||||
ast_id = _loc_nodes.get(key)
|
||||
if ast_id is not None:
|
||||
_ghost_remap[sem_id] = ast_id
|
||||
# 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)
|
||||
|
||||
# Normalized ID map: lets edges survive when the LLM generates IDs with
|
||||
# slightly different casing or punctuation than the AST extractor.
|
||||
# e.g. "Session_ValidateToken" maps to "session_validatetoken".
|
||||
norm_to_id: dict[str, str] = {_normalize_id(nid): nid for nid in node_set}
|
||||
# Also map ghost IDs to their canonical AST replacements.
|
||||
for ghost_id, canonical_id in _ghost_remap.items():
|
||||
norm_to_id[_normalize_id(ghost_id)] = canonical_id
|
||||
norm_to_id[ghost_id] = canonical_id
|
||||
# Pre-migration alias index (#1504): register each canonical node's OLD-stem id
|
||||
# forms as aliases so a stale-id edge endpoint coming from an un-re-keyed
|
||||
# fragment (e.g. an incremental update whose fragment references a symbol in a
|
||||
# file that was NOT re-extracted) still resolves to the migrated node instead
|
||||
# of dangling. Only fills gaps — never overrides a real node id.
|
||||
from graphify.extractors.base import _file_stem as _fs
|
||||
for nid in node_set:
|
||||
attrs = G.nodes[nid]
|
||||
sf = attrs.get("source_file")
|
||||
if not sf:
|
||||
continue
|
||||
rel = Path(str(sf))
|
||||
if rel.is_absolute():
|
||||
continue
|
||||
new_stem = make_id(_fs(rel))
|
||||
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
|
||||
alias = old_stem + suffix
|
||||
norm_to_id.setdefault(_normalize_id(alias), nid)
|
||||
norm_to_id.setdefault(alias, nid)
|
||||
# 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.
|
||||
for edge in sorted(
|
||||
extraction.get("edges", []),
|
||||
key=lambda e: (
|
||||
str(e.get("source", e.get("from", ""))),
|
||||
str(e.get("target", e.get("to", ""))),
|
||||
str(e.get("relation", "")),
|
||||
),
|
||||
):
|
||||
if "source" not in edge and "from" in edge:
|
||||
edge["source"] = edge["from"]
|
||||
if "target" not in edge and "to" in edge:
|
||||
edge["target"] = edge["to"]
|
||||
if "source" not in edge or "target" not in edge:
|
||||
continue
|
||||
src, tgt = edge["source"], edge["target"]
|
||||
# Skip edges with non-hashable endpoints (e.g. a list emitted by a buggy
|
||||
# LLM extraction) so the `not in node_set` membership test below never
|
||||
# raises TypeError: unhashable type. The validator already reported these.
|
||||
try:
|
||||
hash(src)
|
||||
hash(tgt)
|
||||
except TypeError:
|
||||
print(
|
||||
f"[graphify] WARNING: skipping edge with non-hashable endpoint "
|
||||
f"(source={src!r}, target={tgt!r}).",
|
||||
file=sys.stderr,
|
||||
)
|
||||
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)
|
||||
if tgt not in node_set:
|
||||
tgt = norm_to_id.get(_normalize_id(tgt), tgt)
|
||||
if src not in node_set or tgt not in node_set:
|
||||
continue # skip edges to external/stdlib nodes - expected, not an error
|
||||
attrs = {k: v for k, v in edge.items() if k not in ("source", "target")}
|
||||
# Preserve original edge direction — undirected graphs lose it otherwise,
|
||||
# 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).
|
||||
if not attrs.get("source_file"):
|
||||
attrs["source_file"] = (
|
||||
G.nodes[src].get("source_file")
|
||||
or G.nodes[tgt].get("source_file")
|
||||
or ""
|
||||
)
|
||||
if "source_file" in attrs:
|
||||
attrs["source_file"] = _norm_source_file(attrs["source_file"], _root)
|
||||
# Drop cross-language INFERRED `calls` edges — same short names (render,
|
||||
# parse, etc.) appear across language boundaries in multi-language chunks,
|
||||
# producing phantom edges that don't represent real call relationships.
|
||||
if attrs.get("relation") == "calls" and attrs.get("confidence") == "INFERRED":
|
||||
_LANG_FAMILY: dict[str, str] = {
|
||||
".py": "py", ".pyi": "py",
|
||||
".js": "js", ".mjs": "js", ".cjs": "js", ".jsx": "js",
|
||||
".ts": "js", ".tsx": "js",
|
||||
".go": "go", ".rs": "rs",
|
||||
".java": "jvm", ".kt": "jvm", ".scala": "jvm", ".groovy": "jvm",
|
||||
# C, C++, and ObjC interoperate within one compilation unit: a method
|
||||
# declared in a shared `.h` is defined/called from a `.c`/`.cpp`/`.m`
|
||||
# sibling, so a cross-file INFERRED call from impl to its header decl
|
||||
# is legitimate, not a phantom name-collision across languages. Treat
|
||||
# the whole C family as one so the receiver-typed C++/ObjC member-call
|
||||
# resolvers' header-targeting edges survive build (#1547/#1556).
|
||||
".c": "c", ".h": "c", ".cc": "c", ".cpp": "c", ".hpp": "c",
|
||||
".cxx": "c", ".hh": "c", ".hxx": "c",
|
||||
".cu": "c", ".cuh": "c", ".metal": "c", ".m": "c", ".mm": "c",
|
||||
".rb": "rb", ".php": "php", ".cs": "cs", ".swift": "swift", ".lua": "lua",
|
||||
}
|
||||
src_ext = Path(G.nodes[src].get("source_file") or "").suffix.lower()
|
||||
tgt_ext = Path(G.nodes[tgt].get("source_file") or "").suffix.lower()
|
||||
if src_ext and tgt_ext and _LANG_FAMILY.get(src_ext) != _LANG_FAMILY.get(tgt_ext):
|
||||
continue
|
||||
# Preserve original edge direction - undirected graphs lose it otherwise,
|
||||
# causing display functions to show edges backwards.
|
||||
attrs["_src"] = edge["source"]
|
||||
attrs["_tgt"] = edge["target"]
|
||||
G.add_edge(edge["source"], edge["target"], **attrs)
|
||||
attrs["_src"] = src
|
||||
attrs["_tgt"] = tgt
|
||||
# When the graph is undirected and the same node pair appears twice with
|
||||
# the same relation but opposite directions (e.g. a `calls` b and b `calls` a),
|
||||
# nx.Graph collapses them into one edge. The deterministic sort above means
|
||||
# the lexicographically-later direction would systematically overwrite the
|
||||
# earlier one's _src/_tgt, silently flipping the surviving edge's caller
|
||||
# and callee. First-seen direction wins instead — drop the redundant
|
||||
# reverse-direction duplicate so the original direction is preserved (#1061).
|
||||
if not G.is_directed() and G.has_edge(src, tgt):
|
||||
existing = edge_data(G, src, tgt)
|
||||
if existing.get("relation") == attrs.get("relation") and (
|
||||
existing.get("_src") == tgt and existing.get("_tgt") == src
|
||||
):
|
||||
continue
|
||||
G.add_edge(src, tgt, **attrs)
|
||||
hyperedges = extraction.get("hyperedges", [])
|
||||
if hyperedges:
|
||||
# Relativize hyperedge source_file the same way nodes and edges are
|
||||
# (above), so to_json — which has no root and writes G.graph["hyperedges"]
|
||||
# verbatim — never leaks an absolute path from a semantic subagent (#1418).
|
||||
for he in hyperedges:
|
||||
if isinstance(he, dict) and he.get("source_file"):
|
||||
he["source_file"] = _norm_source_file(he["source_file"], _root)
|
||||
G.graph["hyperedges"] = hyperedges
|
||||
return G
|
||||
|
||||
|
||||
def build(extractions: list[dict]) -> nx.Graph:
|
||||
"""Merge multiple extraction results into one graph."""
|
||||
G = nx.Graph()
|
||||
def build(
|
||||
extractions: list[dict],
|
||||
*,
|
||||
directed: bool = False,
|
||||
dedup: bool = True,
|
||||
dedup_llm_backend: str | None = None,
|
||||
root: str | Path | None = None,
|
||||
) -> nx.Graph:
|
||||
"""Merge multiple extraction results into one graph.
|
||||
|
||||
directed=True produces a DiGraph that preserves edge direction (source→target).
|
||||
directed=False (default) produces an undirected Graph for backward compatibility.
|
||||
dedup=True (default) runs entity deduplication before building the graph.
|
||||
dedup_llm_backend: if set (e.g. "gemini", "claude", or "kimi"), uses LLM to resolve
|
||||
ambiguous pairs in the 75–92 Jaro-Winkler score zone.
|
||||
root: if given, absolute source_file paths are made relative to root (#932).
|
||||
|
||||
Extractions are merged in order. For nodes with the same ID, the last
|
||||
extraction's attributes win (NetworkX add_node overwrites). Pass AST
|
||||
results before semantic results so semantic labels take precedence, or
|
||||
reverse the order if you prefer AST source_location precision to win.
|
||||
"""
|
||||
from graphify.dedup import deduplicate_entities
|
||||
combined: dict = {"nodes": [], "edges": [], "hyperedges": [], "input_tokens": 0, "output_tokens": 0}
|
||||
for ext in extractions:
|
||||
sub = build_from_json(ext)
|
||||
G.update(sub)
|
||||
combined["nodes"].extend(ext.get("nodes", []))
|
||||
combined["edges"].extend(ext.get("edges", []))
|
||||
combined["hyperedges"].extend(ext.get("hyperedges", []))
|
||||
combined["input_tokens"] += ext.get("input_tokens", 0)
|
||||
combined["output_tokens"] += ext.get("output_tokens", 0)
|
||||
if dedup and combined["nodes"]:
|
||||
combined["nodes"], combined["edges"] = deduplicate_entities(
|
||||
combined["nodes"], combined["edges"], communities={},
|
||||
dedup_llm_backend=dedup_llm_backend,
|
||||
)
|
||||
return build_from_json(combined, directed=directed, root=root)
|
||||
|
||||
|
||||
def _norm_label(label: str | None) -> str:
|
||||
"""Canonical dedup key — Unicode-aware, preserves CJK/word characters."""
|
||||
if not isinstance(label, str):
|
||||
label = "" if label is None else str(label)
|
||||
label = unicodedata.normalize("NFKC", label)
|
||||
return re.sub(r"[\W_ ]+", " ", label.casefold(), flags=re.UNICODE).strip()
|
||||
|
||||
|
||||
def deduplicate_by_label(nodes: list[dict], edges: list[dict]) -> tuple[list[dict], list[dict]]:
|
||||
"""Merge nodes that share a normalised label, rewriting edge references.
|
||||
|
||||
Prefers IDs without chunk suffixes (_c\\d+) and shorter IDs when tied.
|
||||
Drops self-loops created by the merge.
|
||||
|
||||
Dormant: this is NOT wired into ``build()`` — the active dedup path is
|
||||
``deduplicate_entities`` (imported and called in ``build``), which supersedes
|
||||
it. The previous "Called in build() automatically" note was never true. It
|
||||
also merges by label alone with no ``file_type`` guard, so it must not be
|
||||
enabled for code nodes: same-label symbols from different files/packages
|
||||
(e.g. two ``Account`` types) would collapse into one — the cross-file
|
||||
conflation ``deduplicate_entities`` deliberately avoids for code (#1205).
|
||||
"""
|
||||
_CHUNK_SUFFIX = re.compile(r"_c\d+$")
|
||||
canonical: dict[str, dict] = {} # norm_label -> surviving node
|
||||
remap: dict[str, str] = {} # old_id -> surviving_id
|
||||
|
||||
for node in nodes:
|
||||
key = _norm_label(node.get("label", node.get("id", "")))
|
||||
if not key:
|
||||
continue
|
||||
existing = canonical.get(key)
|
||||
if existing is None:
|
||||
canonical[key] = node
|
||||
else:
|
||||
has_suffix = bool(_CHUNK_SUFFIX.search(node["id"]))
|
||||
existing_has_suffix = bool(_CHUNK_SUFFIX.search(existing["id"]))
|
||||
if has_suffix and not existing_has_suffix:
|
||||
remap[node["id"]] = existing["id"]
|
||||
elif existing_has_suffix and not has_suffix:
|
||||
remap[existing["id"]] = node["id"]
|
||||
canonical[key] = node
|
||||
elif len(node["id"]) < len(existing["id"]):
|
||||
remap[existing["id"]] = node["id"]
|
||||
canonical[key] = node
|
||||
else:
|
||||
remap[node["id"]] = existing["id"]
|
||||
|
||||
if not remap:
|
||||
return nodes, edges
|
||||
|
||||
print(f"[graphify] Deduplicated {len(remap)} duplicate node(s) by label.", file=sys.stderr)
|
||||
deduped_nodes = list(canonical.values())
|
||||
deduped_edges = []
|
||||
for edge in edges:
|
||||
e = dict(edge)
|
||||
e["source"] = remap.get(e["source"], e["source"])
|
||||
e["target"] = remap.get(e["target"], e["target"])
|
||||
if e["source"] != e["target"]:
|
||||
deduped_edges.append(e)
|
||||
return deduped_nodes, deduped_edges
|
||||
|
||||
|
||||
def build_merge(
|
||||
new_chunks: list[dict],
|
||||
graph_path: str | Path | None = None,
|
||||
prune_sources: list[str] | None = None,
|
||||
*,
|
||||
directed: bool = False,
|
||||
dedup: bool = True,
|
||||
dedup_llm_backend: str | None = None,
|
||||
root: str | Path | None = None,
|
||||
) -> nx.Graph:
|
||||
"""Load existing graph.json, merge new chunks into it, and save back.
|
||||
|
||||
Re-extracted files REPLACE their prior contribution: any source_file present
|
||||
in new_chunks is dropped from the loaded graph before merging, so a changed
|
||||
file's stale nodes/edges don't accumulate. Files absent from new_chunks are
|
||||
preserved unchanged; deleted files are removed via prune_sources.
|
||||
Safe to call repeatedly.
|
||||
root: if given, absolute source_file paths in new_chunks are made relative (#932).
|
||||
"""
|
||||
graph_path = Path(graph_path if graph_path is not None else _default_graph_json())
|
||||
if graph_path.exists():
|
||||
# Read JSON directly instead of going through node_link_graph().
|
||||
# The latter rebuilds an undirected nx.Graph and then enumerating
|
||||
# edges() yields endpoints based on node insertion order, which
|
||||
# silently flips directional edges (e.g. `calls`) when the callee
|
||||
# was inserted before the caller. The _src/_tgt direction-preserving
|
||||
# attrs are popped before saving in export.py, so going through the
|
||||
# NetworkX round-trip loses direction permanently (#760).
|
||||
from graphify.security import check_graph_file_size_cap
|
||||
check_graph_file_size_cap(graph_path)
|
||||
try:
|
||||
data = json.loads(graph_path.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError) as exc:
|
||||
raise RuntimeError(
|
||||
f"Cannot read {graph_path} for incremental merge: {exc}. "
|
||||
"Delete the file and run a full rebuild."
|
||||
) from exc
|
||||
links_key = "links" if "links" in data else "edges"
|
||||
existing_nodes = list(data.get("nodes", []))
|
||||
existing_edges = list(data.get(links_key, []))
|
||||
existing_hyperedges = list(data.get("hyperedges", []))
|
||||
had_graph = True
|
||||
else:
|
||||
existing_nodes = []
|
||||
existing_edges = []
|
||||
existing_hyperedges = []
|
||||
had_graph = False
|
||||
|
||||
# Effective root for relativizing absolute source_file / prune paths back to the
|
||||
# stored relative source_file keys. When the caller passes root we use it;
|
||||
# otherwise fall back to the graph's recorded scan root, so absolute
|
||||
# prune_sources and new-chunk paths still match even when a caller omits root
|
||||
# (#1571 — the skill's --update runbook calls build_merge without root, so
|
||||
# absolute deleted-file paths never matched the relative node keys and their
|
||||
# nodes survived as ghosts).
|
||||
_eff_root = (
|
||||
str(Path(root).resolve()) if root is not None
|
||||
else _infer_merge_root(graph_path)
|
||||
)
|
||||
|
||||
# Re-extracted files REPLACE their prior contribution. Every source_file
|
||||
# present in new_chunks is dropped from the loaded base before merging, so a
|
||||
# CHANGED file's stale nodes/edges don't accumulate across incremental
|
||||
# updates. Without this, build() merges old+new for the same file and only
|
||||
# exact-duplicate edges collapse — edges/nodes that disappeared from the new
|
||||
# version survive forever. Brand-new files aren't in base, so this is a no-op
|
||||
# for them; genuinely deleted files are still handled via prune_sources.
|
||||
# Matched in both raw and _norm_source_file form because new_chunks may carry
|
||||
# absolute win32 paths while the stored graph keeps relative posix (#1007).
|
||||
_replace_root = _eff_root
|
||||
new_sources: set[str] = set()
|
||||
for ch in new_chunks:
|
||||
for n in ch.get("nodes", []):
|
||||
sf = n.get("source_file")
|
||||
if not sf:
|
||||
continue
|
||||
new_sources.add(sf)
|
||||
norm = _norm_source_file(sf, _replace_root)
|
||||
if norm:
|
||||
new_sources.add(norm)
|
||||
if new_sources:
|
||||
def _kept(item: dict) -> bool:
|
||||
sf = item.get("source_file")
|
||||
return sf not in new_sources and _norm_source_file(sf, _replace_root) not in new_sources
|
||||
existing_nodes = [n for n in existing_nodes if _kept(n)]
|
||||
existing_edges = [e for e in existing_edges if _kept(e)]
|
||||
|
||||
base = [{"nodes": existing_nodes, "edges": existing_edges}] if had_graph else []
|
||||
|
||||
all_chunks = base + list(new_chunks)
|
||||
G = build(all_chunks, directed=directed, dedup=dedup, dedup_llm_backend=dedup_llm_backend, root=root)
|
||||
|
||||
# Prune set for deleted source files — both the raw form (matches nodes that
|
||||
# kept absolute source_file) and the normalised relative form (matches nodes
|
||||
# relativised by _norm_source_file at build time). .resolve() (via _eff_root)
|
||||
# handles symlinked roots and ".." / "./" segments so Path.relative_to()
|
||||
# succeeds even when the scan root is a symlink. (#1007, #1571)
|
||||
prune_set: set[str] = set()
|
||||
for p in (prune_sources or []):
|
||||
if not p:
|
||||
continue
|
||||
prune_set.add(p)
|
||||
norm = _norm_source_file(p, _eff_root)
|
||||
if norm:
|
||||
prune_set.add(norm)
|
||||
|
||||
# Carry forward hyperedges from files that were neither re-extracted nor
|
||||
# deleted (#1574). build() only sees the new chunks' hyperedges, so without
|
||||
# this every --update collapses the graph's hyperedge set down to just the
|
||||
# changed files'. Re-extracted files' prior hyperedges are dropped (their new
|
||||
# version is already in G — replace-per-source, like nodes/edges); deleted
|
||||
# files' are dropped via prune_set. id-dedup (attach_hyperedges) so a carried
|
||||
# hyperedge never duplicates one the new chunks re-emitted. Mirrors watch.py,
|
||||
# which already preserves existing hyperedges across a rebuild.
|
||||
if existing_hyperedges:
|
||||
carried = []
|
||||
for he in existing_hyperedges:
|
||||
if not isinstance(he, dict):
|
||||
continue
|
||||
sf = he.get("source_file")
|
||||
norm = _norm_source_file(sf, _eff_root)
|
||||
if sf in new_sources or norm in new_sources:
|
||||
continue # re-extracted — replaced by the new chunk's version
|
||||
if sf in prune_set or norm in prune_set:
|
||||
continue # deleted — pruned
|
||||
carried.append(he)
|
||||
if carried:
|
||||
from graphify.export import attach_hyperedges
|
||||
attach_hyperedges(G, carried)
|
||||
|
||||
# Prune nodes and edges from deleted source files
|
||||
if prune_sources:
|
||||
to_remove = [
|
||||
n for n, d in G.nodes(data=True)
|
||||
if d.get("source_file") in prune_set
|
||||
]
|
||||
G.remove_nodes_from(to_remove)
|
||||
n_files = len(prune_sources)
|
||||
n_nodes = len(to_remove)
|
||||
if n_nodes:
|
||||
print(
|
||||
f"[graphify] Pruned {n_nodes} node(s) from {n_files} deleted source file(s).",
|
||||
file=sys.stderr,
|
||||
)
|
||||
|
||||
edges_to_remove = [
|
||||
(u, v) for u, v, d in G.edges(data=True)
|
||||
if d.get("source_file") in prune_set
|
||||
]
|
||||
if edges_to_remove:
|
||||
G.remove_edges_from(edges_to_remove)
|
||||
print(
|
||||
f"[graphify] Pruned {len(edges_to_remove)} edge(s) from deleted source file(s).",
|
||||
file=sys.stderr,
|
||||
)
|
||||
|
||||
if not n_nodes and not edges_to_remove:
|
||||
print(
|
||||
f"[graphify] {n_files} source file(s) deleted since last run — "
|
||||
f"no matching nodes or edges in graph, already clean.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
|
||||
# Safety check: refuse to shrink the graph silently (#479)
|
||||
# Skip when dedup or prune_sources is active — shrinkage is intentional there.
|
||||
if graph_path.exists() and not dedup and not prune_sources:
|
||||
existing_n = len(existing_nodes)
|
||||
new_n = G.number_of_nodes()
|
||||
if new_n < existing_n:
|
||||
raise ValueError(
|
||||
f"graphify: build_merge would shrink graph from {existing_n} → {new_n} nodes. "
|
||||
f"Pass prune_sources explicitly if you intend to remove nodes."
|
||||
)
|
||||
|
||||
return G
|
||||
|
||||
|
||||
def prefix_graph_for_global(G: nx.Graph, repo_tag: str) -> nx.Graph:
|
||||
"""Return a copy of G with all node IDs prefixed with repo_tag::.
|
||||
|
||||
Labels are preserved unchanged (for display). A 'local_id' attribute
|
||||
is added to each node so the original ID can be recovered. Edges are
|
||||
rewritten to match the new prefixed IDs. The 'repo' attribute is set
|
||||
on every node.
|
||||
"""
|
||||
relabel = {n: f"{repo_tag}::{n}" for n in G.nodes}
|
||||
H = nx.relabel_nodes(G, relabel, copy=True)
|
||||
for node, data in H.nodes(data=True):
|
||||
data["repo"] = repo_tag
|
||||
data.setdefault("local_id", node.split("::", 1)[1])
|
||||
return H
|
||||
|
||||
|
||||
def prune_repo_from_graph(G: nx.Graph, repo_tag: str) -> int:
|
||||
"""Remove all nodes tagged with repo_tag from G in-place. Returns count removed."""
|
||||
to_remove = [n for n, d in G.nodes(data=True) if d.get("repo") == repo_tag]
|
||||
G.remove_nodes_from(to_remove)
|
||||
return len(to_remove)
|
||||
+434
-38
@@ -1,105 +1,495 @@
|
||||
# per-file extraction cache — skip unchanged files on re-run
|
||||
# per-file extraction cache - skip unchanged files on re-run
|
||||
from __future__ import annotations
|
||||
|
||||
import atexit
|
||||
import hashlib
|
||||
import json
|
||||
import shutil
|
||||
import os
|
||||
import re
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
# Output directory name — override with GRAPHIFY_OUT env var for worktrees or
|
||||
# shared-output setups. Accepts a relative name ("graphify-out-feature") or an
|
||||
# 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
|
||||
|
||||
def file_hash(path: Path) -> str:
|
||||
"""SHA256 of file contents, hex digest."""
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
# AST cache entries are the output of graphify's own extractor code, so they
|
||||
# are only valid for the version that wrote them: keying purely on file
|
||||
# content means extractor fixes shipped in a new release keep serving stale
|
||||
# pre-fix results. The AST cache is therefore namespaced by package version
|
||||
# (cache/ast/v{version}/), with entries from other versions removed on first
|
||||
# use. The semantic cache is deliberately NOT versioned — its entries are
|
||||
# produced by the LLM from file contents, and invalidating them on every
|
||||
# release would re-bill extraction for unchanged files.
|
||||
try:
|
||||
from importlib.metadata import version as _pkg_version
|
||||
|
||||
_EXTRACTOR_VERSION = _pkg_version("graphifyy")
|
||||
except Exception:
|
||||
_EXTRACTOR_VERSION = "unknown"
|
||||
|
||||
# Version dirs already swept this process — cleanup runs once per (base, version).
|
||||
_cleaned_ast_dirs: set[str] = set()
|
||||
|
||||
|
||||
def cache_dir(root: Path = Path(".")) -> Path:
|
||||
"""Returns .graphify/cache/ — creates it if needed."""
|
||||
d = Path(root) / ".graphify" / "cache"
|
||||
def _cleanup_stale_ast_entries(ast_base: Path, current_dir: Path) -> None:
|
||||
"""Remove AST cache entries left behind by other graphify versions.
|
||||
|
||||
Sweeps sibling ``v*/`` directories and unversioned ``*.json`` entries
|
||||
(the pre-versioning layout) under ``cache/ast/``. Best-effort: failures
|
||||
are ignored, stragglers are retried on the next run.
|
||||
"""
|
||||
key = str(current_dir)
|
||||
if key in _cleaned_ast_dirs:
|
||||
return
|
||||
_cleaned_ast_dirs.add(key)
|
||||
if not ast_base.is_dir():
|
||||
return
|
||||
import shutil
|
||||
|
||||
for child in ast_base.iterdir():
|
||||
if child == current_dir:
|
||||
continue
|
||||
try:
|
||||
if child.is_dir() and child.name.startswith("v"):
|
||||
shutil.rmtree(child, ignore_errors=True)
|
||||
elif child.suffix == ".json":
|
||||
child.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
# A frontmatter delimiter is a whole line of exactly three dashes (optional
|
||||
# trailing whitespace). Substring checks like startswith("---") /
|
||||
# find("\n---") also match `----` thematic breaks and `--- text` prose,
|
||||
# silently dropping everything above them from the hash (#1259).
|
||||
_FRONTMATTER_DELIM = re.compile(r"^---[ \t]*\r?$", re.MULTILINE)
|
||||
|
||||
|
||||
def _body_content(content: bytes) -> bytes:
|
||||
"""Strip YAML frontmatter from Markdown content, returning only the body."""
|
||||
text = content.decode(errors="replace")
|
||||
opener = _FRONTMATTER_DELIM.match(text)
|
||||
if opener is None:
|
||||
return content
|
||||
closer = _FRONTMATTER_DELIM.search(text, opener.end())
|
||||
if closer is None:
|
||||
return content
|
||||
# Slice right after the closing `---` (not after its line) so the output
|
||||
# stays byte-identical with the historical implementation for well-formed
|
||||
# frontmatter -- existing semantic-cache hashes must not churn.
|
||||
return text[closer.start() + 3:].encode()
|
||||
|
||||
|
||||
# Stat-based index: maps absolute path → {size, mtime_ns, hash}.
|
||||
# Loaded once per process, flushed via atexit. Skips full file reads when
|
||||
# size+mtime_ns are unchanged — same trade-off as make(1).
|
||||
# Correctness risks: `touch` causes a harmless extra re-hash; same-size edits
|
||||
# within NFS second-resolution mtime have a 1-second window (same as make).
|
||||
# Use `graphify extract --force` to bypass when needed.
|
||||
_stat_index: dict[str, dict] = {}
|
||||
_stat_index_root: Path | None = None
|
||||
_stat_index_dirty: bool = False
|
||||
|
||||
|
||||
def _stat_index_file(root: Path) -> Path:
|
||||
_out = Path(_GRAPHIFY_OUT)
|
||||
base = _out if _out.is_absolute() else Path(root).resolve() / _out
|
||||
return base / "cache" / "stat-index.json"
|
||||
|
||||
|
||||
def _ensure_stat_index(root: Path) -> None:
|
||||
global _stat_index, _stat_index_root, _stat_index_dirty
|
||||
if _stat_index_root is not None:
|
||||
return
|
||||
_stat_index_root = Path(root).resolve()
|
||||
p = _stat_index_file(_stat_index_root)
|
||||
if p.exists():
|
||||
try:
|
||||
_stat_index = json.loads(p.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError):
|
||||
_stat_index = {}
|
||||
else:
|
||||
_stat_index = {}
|
||||
atexit.register(_flush_stat_index)
|
||||
|
||||
|
||||
def _flush_stat_index() -> None:
|
||||
global _stat_index_dirty, _stat_index_root
|
||||
if not _stat_index_dirty or _stat_index_root is None:
|
||||
return
|
||||
p = _stat_index_file(_stat_index_root)
|
||||
try:
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd, tmp = tempfile.mkstemp(dir=p.parent, prefix="stat-index.", suffix=".tmp")
|
||||
try:
|
||||
os.write(fd, json.dumps(_stat_index, separators=(",", ":")).encode())
|
||||
os.close(fd)
|
||||
os.replace(tmp, p)
|
||||
except Exception:
|
||||
try:
|
||||
os.close(fd)
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
os.unlink(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
except OSError:
|
||||
pass
|
||||
_stat_index_dirty = False
|
||||
|
||||
|
||||
def _normalize_path(path: Path) -> Path:
|
||||
"""Normalize path for consistent cache keys across Windows path spellings."""
|
||||
import sys
|
||||
if sys.platform != "win32":
|
||||
return path
|
||||
s = str(path)
|
||||
if s.startswith("\\\\?\\"):
|
||||
s = s[4:] # strip extended-length prefix \\?\
|
||||
return Path(os.path.normcase(s))
|
||||
|
||||
|
||||
def file_hash(path: Path, root: Path = Path(".")) -> str:
|
||||
"""SHA256 of file contents + path relative to root.
|
||||
|
||||
Uses a stat-based fastpath (size + mtime_ns) to skip full reads when the
|
||||
file hasn't changed. Falls through to full SHA256 on first encounter or
|
||||
when stat changes. Index is flushed atomically at process exit.
|
||||
|
||||
Using a relative path (not absolute) makes cache entries portable across
|
||||
machines and checkout directories, so shared caches and CI work correctly.
|
||||
Falls back to the resolved absolute path if the file is outside root.
|
||||
|
||||
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.
|
||||
"""
|
||||
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}")
|
||||
|
||||
_ensure_stat_index(root)
|
||||
abs_key = str(p.resolve())
|
||||
st: "os.stat_result | None" = None
|
||||
try:
|
||||
st = p.stat()
|
||||
entry = _stat_index.get(abs_key)
|
||||
if (entry
|
||||
and entry.get("size") == st.st_size
|
||||
and entry.get("mtime_ns") == st.st_mtime_ns):
|
||||
return entry["hash"]
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
raw = p.read_bytes()
|
||||
content = _body_content(raw) if p.suffix.lower() == ".md" else raw
|
||||
h = hashlib.sha256()
|
||||
h.update(content)
|
||||
h.update(b"\x00")
|
||||
try:
|
||||
rel = p.resolve().relative_to(Path(root).resolve())
|
||||
h.update(rel.as_posix().lower().encode())
|
||||
except ValueError:
|
||||
h.update(p.resolve().as_posix().lower().encode())
|
||||
digest = h.hexdigest()
|
||||
|
||||
if st is not None:
|
||||
_stat_index[abs_key] = {"size": st.st_size, "mtime_ns": st.st_mtime_ns, "hash": digest}
|
||||
_stat_index_dirty = True
|
||||
|
||||
return digest
|
||||
|
||||
|
||||
def _relativize_source_files_in(payload: dict, root: Path) -> None:
|
||||
"""Mutate ``payload`` to rewrite absolute ``source_file`` fields as
|
||||
forward-slash relative paths from ``root``.
|
||||
|
||||
Mirror of :func:`graphify.watch._relativize_source_files` so cached
|
||||
extraction fragments persist in portable form (#777). Already-relative
|
||||
fields and out-of-root paths pass through unchanged.
|
||||
|
||||
Only ``root`` is resolved — ``source_file`` itself is relativized
|
||||
symbolically so in-root symlinks keep their original name rather than
|
||||
pointing at the resolved target. Same reasoning as
|
||||
:func:`graphify.detect._to_relative_for_storage`.
|
||||
"""
|
||||
try:
|
||||
root_resolved = Path(root).resolve()
|
||||
except OSError:
|
||||
return
|
||||
for bucket in ("nodes", "edges", "hyperedges"):
|
||||
for item in payload.get(bucket, []):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
source = item.get("source_file")
|
||||
if not source:
|
||||
continue
|
||||
sp = Path(source)
|
||||
if not sp.is_absolute():
|
||||
continue
|
||||
try:
|
||||
rel = os.path.relpath(sp, root_resolved)
|
||||
except (ValueError, OSError):
|
||||
continue # out-of-root (e.g. Windows cross-drive)
|
||||
if rel == ".." or rel.startswith(".." + os.sep) or rel.startswith("../"):
|
||||
continue # escaped root — keep absolute
|
||||
item["source_file"] = rel.replace(os.sep, "/")
|
||||
|
||||
|
||||
def _absolutize_source_files_in(payload: dict, root: Path) -> None:
|
||||
"""Inverse of :func:`_relativize_source_files_in`.
|
||||
|
||||
Re-anchor relative ``source_file`` fields against ``root`` so callers
|
||||
that load a cached fragment see the same absolute-path shape that a
|
||||
fresh in-process extraction would produce. Legacy cache entries with
|
||||
absolute ``source_file`` values pass through unchanged.
|
||||
"""
|
||||
try:
|
||||
root_resolved = Path(root).resolve()
|
||||
except OSError:
|
||||
return
|
||||
for bucket in ("nodes", "edges", "hyperedges"):
|
||||
for item in payload.get(bucket, []):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
source = item.get("source_file")
|
||||
if not source:
|
||||
continue
|
||||
sp = Path(source)
|
||||
if sp.is_absolute():
|
||||
continue
|
||||
try:
|
||||
item["source_file"] = str(root_resolved / sp)
|
||||
except (TypeError, OSError):
|
||||
continue
|
||||
|
||||
|
||||
def cache_dir(root: Path = Path("."), kind: str = "ast") -> Path:
|
||||
"""Returns the cache directory for ``kind`` - creates it if needed.
|
||||
|
||||
kind is "ast" or "semantic". Separate subdirectories prevent semantic cache
|
||||
entries from overwriting AST cache entries for the same source_file (#582).
|
||||
|
||||
AST entries live in graphify-out/cache/ast/v{version}/ — namespaced by
|
||||
graphify version because they depend on extractor code, not just file
|
||||
contents. Semantic entries live unversioned in graphify-out/cache/semantic/
|
||||
(re-extraction costs LLM calls).
|
||||
"""
|
||||
_out = Path(_GRAPHIFY_OUT)
|
||||
base = _out if _out.is_absolute() else Path(root).resolve() / _out
|
||||
d = base / "cache" / kind
|
||||
if kind == "ast":
|
||||
d = d / f"v{_EXTRACTOR_VERSION}"
|
||||
_cleanup_stale_ast_entries(d.parent, d)
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
def load_cached(path: Path, root: Path = Path(".")) -> dict | None:
|
||||
def load_cached(path: Path, root: Path = Path("."), kind: str = "ast") -> dict | None:
|
||||
"""Return cached extraction for this file if hash matches, else None.
|
||||
|
||||
Cache key: SHA256 of file contents.
|
||||
Cache value: stored as .graphify/cache/{hash}.json
|
||||
Cache value: stored as graphify-out/cache/{kind}/{hash}.json (AST entries
|
||||
under the per-version subdirectory, see :func:`cache_dir`).
|
||||
|
||||
AST entries written by other graphify versions — including the legacy
|
||||
flat cache/ layout (pre-0.5.3) and the unversioned cache/ast/ layout —
|
||||
are deliberately not consulted: they were produced by a different
|
||||
extractor and may be stale.
|
||||
Returns None if no cache entry or file has changed.
|
||||
"""
|
||||
try:
|
||||
h = file_hash(path)
|
||||
h = file_hash(path, root)
|
||||
except OSError:
|
||||
return None
|
||||
entry = cache_dir(root) / f"{h}.json"
|
||||
if not entry.exists():
|
||||
return None
|
||||
try:
|
||||
return json.loads(entry.read_text())
|
||||
except (json.JSONDecodeError, OSError):
|
||||
return None
|
||||
entry = cache_dir(root, kind) / f"{h}.json"
|
||||
if entry.exists():
|
||||
try:
|
||||
result = json.loads(entry.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError):
|
||||
return None
|
||||
# Re-anchor relative source_file fields so callers see the same
|
||||
# absolute-path shape that a fresh in-process extraction produces
|
||||
# (#777). Legacy entries with absolute source_file pass through.
|
||||
if isinstance(result, dict):
|
||||
_absolutize_source_files_in(result, root)
|
||||
return result
|
||||
return None
|
||||
|
||||
|
||||
def save_cached(path: Path, result: dict, root: Path = Path(".")) -> None:
|
||||
def save_cached(path: Path, result: dict, root: Path = Path("."), kind: str = "ast") -> None:
|
||||
"""Save extraction result for this file.
|
||||
|
||||
Stores as .graphify/cache/{hash}.json where hash = SHA256 of current file contents.
|
||||
Stores as graphify-out/cache/{kind}/{hash}.json where hash = SHA256 of current file contents.
|
||||
result should be a dict with 'nodes' and 'edges' lists.
|
||||
|
||||
No-ops if `path` is not a regular file. Subagent-produced semantic fragments
|
||||
occasionally carry a directory path in `source_file`; skipping them prevents
|
||||
IsADirectoryError from aborting the whole batch.
|
||||
"""
|
||||
h = file_hash(path)
|
||||
entry = cache_dir(root) / f"{h}.json"
|
||||
entry.write_text(json.dumps(result))
|
||||
p = Path(path)
|
||||
if not p.is_file():
|
||||
return
|
||||
# Relativize source_file fields against ``root`` before write so the
|
||||
# cache file on disk is portable across machines and checkout
|
||||
# directories (#777). The cache key is content-hashed so lookup is
|
||||
# already path-independent; this fixes the embedded path leak.
|
||||
#
|
||||
# Serialize a relativized copy rather than mutating the caller's dict —
|
||||
# downstream pipeline steps (notably extract.py's AST prefix remap, which
|
||||
# looks up Path(source_file).resolve() in a prefix table) depend on the
|
||||
# source_file field's original absolute form. Mutating the input here would
|
||||
# silently break those remaps on the first extraction pass.
|
||||
on_disk = result
|
||||
if isinstance(result, dict) and any(result.get(k) for k in ("nodes", "edges", "hyperedges")):
|
||||
import copy as _copy
|
||||
on_disk = _copy.deepcopy(result)
|
||||
_relativize_source_files_in(on_disk, root)
|
||||
h = file_hash(p, root)
|
||||
target_dir = cache_dir(root, kind)
|
||||
entry = 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())
|
||||
os.close(fd)
|
||||
try:
|
||||
os.replace(tmp_path, entry)
|
||||
except PermissionError:
|
||||
# Windows: os.replace can fail with WinError 5 if the target is
|
||||
# briefly locked. Fall back to copy-then-delete.
|
||||
import shutil
|
||||
shutil.copy2(tmp_path, entry)
|
||||
os.unlink(tmp_path)
|
||||
except Exception:
|
||||
try:
|
||||
os.close(fd)
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
os.unlink(tmp_path)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
def cached_files(root: Path = Path(".")) -> set[str]:
|
||||
"""Return set of file paths that have a valid cache entry (hash still matches)."""
|
||||
d = cache_dir(root)
|
||||
return {p.stem for p in d.glob("*.json")}
|
||||
"""Return set of file hashes that have a valid cache entry (any kind)."""
|
||||
base = Path(root).resolve() / _GRAPHIFY_OUT / "cache"
|
||||
hashes: set[str] = set()
|
||||
# Legacy flat entries
|
||||
if base.is_dir():
|
||||
hashes.update(p.stem for p in base.glob("*.json"))
|
||||
# Namespaced entries (ast/ recursively, covering per-version subdirs)
|
||||
for kind, pattern in (("ast", "**/*.json"), ("semantic", "*.json")):
|
||||
d = base / kind
|
||||
if d.is_dir():
|
||||
hashes.update(p.stem for p in d.glob(pattern))
|
||||
return hashes
|
||||
|
||||
|
||||
def clear_cache(root: Path = Path(".")) -> None:
|
||||
"""Delete all .graphify/cache/*.json files."""
|
||||
d = cache_dir(root)
|
||||
for f in d.glob("*.json"):
|
||||
f.unlink()
|
||||
"""Delete all cache entries (ast/, semantic/, and legacy flat entries)."""
|
||||
base = Path(root).resolve() / _GRAPHIFY_OUT / "cache"
|
||||
# Legacy flat entries
|
||||
if base.is_dir():
|
||||
for f in base.glob("*.json"):
|
||||
f.unlink()
|
||||
# Namespaced entries (ast/ recursively, covering per-version subdirs)
|
||||
for kind, pattern in (("ast", "**/*.json"), ("semantic", "*.json")):
|
||||
d = base / kind
|
||||
if d.is_dir():
|
||||
for f in d.glob(pattern):
|
||||
f.unlink()
|
||||
|
||||
|
||||
def prune_semantic_cache(root: Path, live_hashes: set[str]) -> int:
|
||||
"""Remove orphaned semantic cache entries, returning the count pruned.
|
||||
|
||||
The semantic cache is content-hash-keyed (``{file_hash}.json`` under
|
||||
``cache/semantic/``) and deliberately UNVERSIONED — entries are produced by
|
||||
the LLM from file contents, so invalidating them on every release would
|
||||
re-bill extraction. Because it is unversioned it is also never swept by the
|
||||
AST version-cleanup, so every content change or file deletion leaves a
|
||||
permanent orphan entry that accumulates unbounded.
|
||||
|
||||
This sweeps ``cache/semantic/*.json`` and deletes any entry whose stem (the
|
||||
content hash) is not in ``live_hashes`` — the hashes of the current live
|
||||
document set. ``*.tmp`` atomic-write temporaries are skipped, and only this
|
||||
directory is touched (never ``cache/ast/**`` or anything else). The
|
||||
unversioned design is preserved: we prune by liveness, not by version.
|
||||
|
||||
Best-effort, mirroring :func:`_cleanup_stale_ast_entries`: each unlink is
|
||||
wrapped in ``try/except OSError`` and a failure is ignored. The worst-case
|
||||
failure mode is benign — a surviving orphan costs only one re-extraction of
|
||||
one doc on a future run, never incorrect output.
|
||||
"""
|
||||
_out = Path(_GRAPHIFY_OUT)
|
||||
base = _out if _out.is_absolute() else Path(root).resolve() / _out
|
||||
semantic_dir = base / "cache" / "semantic"
|
||||
if not semantic_dir.is_dir():
|
||||
return 0
|
||||
pruned = 0
|
||||
for entry in semantic_dir.glob("*.json"):
|
||||
if entry.stem in live_hashes:
|
||||
continue
|
||||
try:
|
||||
entry.unlink()
|
||||
pruned += 1
|
||||
except OSError:
|
||||
pass
|
||||
return pruned
|
||||
|
||||
|
||||
def check_semantic_cache(
|
||||
files: list[str],
|
||||
root: Path = Path("."),
|
||||
) -> tuple[list[dict], list[dict], list[str]]:
|
||||
) -> tuple[list[dict], list[dict], list[dict], list[str]]:
|
||||
"""Check semantic extraction cache for a list of absolute file paths.
|
||||
|
||||
Returns (cached_nodes, cached_edges, uncached_files).
|
||||
Returns (cached_nodes, cached_edges, cached_hyperedges, uncached_files).
|
||||
Uncached files need Claude extraction; cached files are merged directly.
|
||||
"""
|
||||
cached_nodes: list[dict] = []
|
||||
cached_edges: list[dict] = []
|
||||
cached_hyperedges: list[dict] = []
|
||||
uncached: list[str] = []
|
||||
|
||||
for fpath in files:
|
||||
result = load_cached(Path(fpath), root)
|
||||
p = Path(fpath)
|
||||
if not p.is_absolute():
|
||||
p = Path(root) / p
|
||||
result = load_cached(p, root, kind="semantic")
|
||||
if result is not None:
|
||||
cached_nodes.extend(result.get("nodes", []))
|
||||
cached_edges.extend(result.get("edges", []))
|
||||
cached_hyperedges.extend(result.get("hyperedges", []))
|
||||
else:
|
||||
uncached.append(fpath)
|
||||
|
||||
return cached_nodes, cached_edges, uncached
|
||||
return cached_nodes, cached_edges, cached_hyperedges, uncached
|
||||
|
||||
|
||||
def save_semantic_cache(
|
||||
nodes: list[dict],
|
||||
edges: list[dict],
|
||||
hyperedges: list[dict] | None = None,
|
||||
root: Path = Path("."),
|
||||
) -> int:
|
||||
"""Save semantic extraction results to cache, keyed by source_file.
|
||||
|
||||
Groups nodes and edges by source_file, then saves one cache entry per file.
|
||||
Groups nodes and edges by source_file, then saves one cache entry per file
|
||||
under cache/semantic/ (separate from AST entries in cache/ast/) to prevent
|
||||
hash-key collisions (#582).
|
||||
Returns the number of files cached.
|
||||
"""
|
||||
from collections import defaultdict
|
||||
|
||||
by_file: dict[str, dict] = defaultdict(lambda: {"nodes": [], "edges": []})
|
||||
by_file: dict[str, dict] = defaultdict(lambda: {"nodes": [], "edges": [], "hyperedges": []})
|
||||
for n in nodes:
|
||||
src = n.get("source_file", "")
|
||||
if src:
|
||||
@@ -108,11 +498,17 @@ def save_semantic_cache(
|
||||
src = e.get("source_file", "")
|
||||
if src:
|
||||
by_file[src]["edges"].append(e)
|
||||
for h in (hyperedges or []):
|
||||
src = h.get("source_file", "")
|
||||
if src:
|
||||
by_file[src]["hyperedges"].append(h)
|
||||
|
||||
saved = 0
|
||||
for fpath, result in by_file.items():
|
||||
p = Path(fpath)
|
||||
if p.exists():
|
||||
save_cached(p, result, root)
|
||||
if not p.is_absolute():
|
||||
p = Path(root) / p
|
||||
if p.is_file():
|
||||
save_cached(p, result, root, kind="semantic")
|
||||
saved += 1
|
||||
return saved
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,98 @@
|
||||
"""Cargo manifest introspection for workspace-internal crate dependencies."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
_CONFIDENCE_EXTRACTED = "EXTRACTED"
|
||||
|
||||
|
||||
def _load_toml(path: Path) -> dict[str, Any]:
|
||||
try:
|
||||
import tomllib # type: ignore[import-not-found]
|
||||
except ModuleNotFoundError:
|
||||
try:
|
||||
import tomli as tomllib # type: ignore[import-not-found,no-redef]
|
||||
except ModuleNotFoundError:
|
||||
raise ImportError(
|
||||
"--cargo on Python 3.10 needs tomli. Install with: pip install tomli"
|
||||
) from None
|
||||
|
||||
with path.open("rb") as manifest:
|
||||
return tomllib.load(manifest)
|
||||
|
||||
|
||||
def _member_manifest_paths(root: Path, root_data: dict[str, Any]) -> list[Path]:
|
||||
paths: list[Path] = []
|
||||
if isinstance(root_data.get("package"), dict):
|
||||
paths.append(root / "Cargo.toml")
|
||||
|
||||
workspace = root_data.get("workspace")
|
||||
members = workspace.get("members", []) if isinstance(workspace, dict) else []
|
||||
if not isinstance(members, list):
|
||||
return paths
|
||||
|
||||
for pattern in members:
|
||||
if not isinstance(pattern, str):
|
||||
continue
|
||||
for member in sorted(root.glob(pattern)):
|
||||
manifest = member / "Cargo.toml"
|
||||
if manifest.is_file() and manifest not in paths:
|
||||
paths.append(manifest)
|
||||
return paths
|
||||
|
||||
|
||||
def introspect_cargo(root: str | Path) -> dict[str, Any]:
|
||||
"""Return crate nodes and internal dependency edges from Cargo manifests."""
|
||||
root_path = Path(root).resolve()
|
||||
root_manifest = root_path / "Cargo.toml"
|
||||
root_data = _load_toml(root_manifest)
|
||||
|
||||
manifests = _member_manifest_paths(root_path, root_data)
|
||||
crates: dict[str, tuple[str, Path, dict[str, Any]]] = {}
|
||||
|
||||
for manifest in manifests:
|
||||
data = root_data if manifest == root_manifest else _load_toml(manifest)
|
||||
package = data.get("package")
|
||||
if not isinstance(package, dict):
|
||||
continue
|
||||
name = package.get("name")
|
||||
if isinstance(name, str):
|
||||
crates[name] = (f"crate:{name}", manifest, data)
|
||||
|
||||
nodes = [
|
||||
{
|
||||
"id": crate_id,
|
||||
"label": name,
|
||||
"source_file": manifest.relative_to(root_path).as_posix(),
|
||||
"source_location": "L1",
|
||||
}
|
||||
for name, (crate_id, manifest, _data) in sorted(crates.items())
|
||||
]
|
||||
|
||||
edges: list[dict[str, Any]] = []
|
||||
for source_name, (source_id, manifest, data) in sorted(crates.items()):
|
||||
dependencies = data.get("dependencies", {})
|
||||
if not isinstance(dependencies, dict):
|
||||
continue
|
||||
source_file = manifest.relative_to(root_path).as_posix()
|
||||
for dependency_name in sorted(dependencies):
|
||||
target = crates.get(dependency_name)
|
||||
if target is None:
|
||||
continue
|
||||
edges.append(
|
||||
{
|
||||
"source": source_id,
|
||||
"target": target[0],
|
||||
"relation": "crate_depends_on",
|
||||
"context": "cargo_dependency",
|
||||
"weight": 1.0,
|
||||
"confidence": _CONFIDENCE_EXTRACTED,
|
||||
"source_file": source_file,
|
||||
"source_location": "L1",
|
||||
}
|
||||
)
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
+244
-28
@@ -1,51 +1,184 @@
|
||||
"""Leiden community detection on NetworkX graphs. Splits oversized communities. Returns cohesion scores."""
|
||||
"""Community detection on NetworkX graphs. Uses Leiden (graspologic) if available, falls back to Louvain (networkx). Splits oversized communities. Returns cohesion scores."""
|
||||
from __future__ import annotations
|
||||
import contextlib
|
||||
import inspect
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
import networkx as nx
|
||||
|
||||
|
||||
def build_graph(nodes: list[dict], edges: list[dict]) -> nx.Graph:
|
||||
"""Build a NetworkX graph from graphify node/edge dicts.
|
||||
def _suppress_output():
|
||||
"""Context manager to suppress stdout/stderr during library calls.
|
||||
|
||||
Preserves original edge direction as _src/_tgt attributes so that
|
||||
display functions can show relationships in the correct direction,
|
||||
even though the graph is undirected for structural analysis.
|
||||
graspologic's leiden() emits ANSI escape sequences (progress bars,
|
||||
colored warnings) that corrupt PowerShell 5.1's scroll buffer on
|
||||
Windows (see issue #19). Redirecting stdout/stderr to devnull during
|
||||
the call prevents this without losing any graphify output.
|
||||
"""
|
||||
G = nx.Graph()
|
||||
for n in nodes:
|
||||
G.add_node(n["id"], **{k: v for k, v in n.items() if k != "id"})
|
||||
for e in edges:
|
||||
attrs = {k: v for k, v in e.items() if k not in ("source", "target")}
|
||||
attrs["_src"] = e["source"]
|
||||
attrs["_tgt"] = e["target"]
|
||||
G.add_edge(e["source"], e["target"], **attrs)
|
||||
return G
|
||||
return contextlib.redirect_stdout(io.StringIO())
|
||||
|
||||
|
||||
def _partition(G: nx.Graph, resolution: float = 1.0) -> dict[str, int]:
|
||||
"""Run community detection. Returns {node_id: community_id}.
|
||||
|
||||
Tries Leiden (graspologic) first — best quality.
|
||||
Falls back to Louvain (built into networkx) if graspologic is not installed.
|
||||
|
||||
resolution > 1.0 → more, smaller communities.
|
||||
resolution < 1.0 → fewer, larger communities.
|
||||
|
||||
Output from graspologic is suppressed to prevent ANSI escape codes
|
||||
from corrupting terminal scroll buffers on Windows PowerShell 5.1.
|
||||
"""
|
||||
stable = nx.Graph()
|
||||
stable.add_nodes_from(sorted(G.nodes(), key=str))
|
||||
edge_rows = sorted(
|
||||
G.edges(data=True),
|
||||
key=lambda row: (
|
||||
str(row[0]),
|
||||
str(row[1]),
|
||||
json.dumps(row[2], sort_keys=True, ensure_ascii=False, default=str),
|
||||
),
|
||||
)
|
||||
for src, tgt, attrs in edge_rows:
|
||||
stable.add_edge(src, tgt, **attrs)
|
||||
|
||||
try:
|
||||
from graspologic.partition import leiden
|
||||
lsig = inspect.signature(leiden).parameters
|
||||
kwargs: dict = {}
|
||||
if "random_seed" in lsig:
|
||||
kwargs["random_seed"] = 42
|
||||
if "trials" in lsig:
|
||||
kwargs["trials"] = 1
|
||||
if "resolution" in lsig:
|
||||
kwargs["resolution"] = resolution
|
||||
# Suppress graspologic output to prevent ANSI escape codes from
|
||||
# corrupting PowerShell 5.1 scroll buffer (issue #19)
|
||||
old_stderr = sys.stderr
|
||||
try:
|
||||
sys.stderr = io.StringIO()
|
||||
with _suppress_output():
|
||||
result = leiden(stable, **kwargs)
|
||||
finally:
|
||||
sys.stderr = old_stderr
|
||||
return result
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
# Fallback: networkx louvain (available since networkx 2.7).
|
||||
# Inspect kwargs to stay compatible across NetworkX versions — max_level
|
||||
# was added in a later release and prevents hangs on large sparse graphs.
|
||||
kwargs: dict = {"seed": 42, "threshold": 1e-4, "resolution": resolution}
|
||||
if "max_level" in inspect.signature(nx.community.louvain_communities).parameters:
|
||||
kwargs["max_level"] = 10
|
||||
communities = nx.community.louvain_communities(stable, **kwargs)
|
||||
return {node: cid for cid, nodes in enumerate(communities) for node in nodes}
|
||||
|
||||
|
||||
_MAX_COMMUNITY_FRACTION = 0.25 # communities larger than 25% of graph get split
|
||||
_MIN_SPLIT_SIZE = 10 # only split if community has at least this many nodes
|
||||
_COHESION_SPLIT_THRESHOLD = 0.05 # re-split communities with cohesion below this
|
||||
_COHESION_SPLIT_MIN_SIZE = 50 # only cohesion-split if community has at least this many nodes
|
||||
|
||||
|
||||
def cluster(G: nx.Graph) -> dict[int, list[str]]:
|
||||
def label_communities_by_hub(
|
||||
G: nx.Graph, communities: dict[int, list[str]]
|
||||
) -> dict[int, str]:
|
||||
"""Deterministic, LLM-free community labels: name each community after its
|
||||
highest-degree member — the structural hub — so a report reads ``auth`` /
|
||||
``log_action`` instead of ``Community 70``. Degree is measured on the full graph
|
||||
``G``; ties break by node id for run-to-run stability. A community whose members
|
||||
are all absent from ``G`` falls back to ``Community {cid}``.
|
||||
|
||||
Used as the default (no-backend) labeler; an LLM naming pass, when configured,
|
||||
overrides these with richer names.
|
||||
"""
|
||||
labels: dict[int, str] = {}
|
||||
for cid, members in communities.items():
|
||||
present = [n for n in members if n in G]
|
||||
if not present:
|
||||
labels[cid] = f"Community {cid}"
|
||||
continue
|
||||
# highest degree wins; ties broken by node id (ascending) for determinism
|
||||
hub = min(present, key=lambda n: (-G.degree(n), str(n)))
|
||||
name = str(G.nodes[hub].get("label") or hub).strip()
|
||||
if name.endswith("()"):
|
||||
name = name[:-2]
|
||||
labels[cid] = name or f"Community {cid}"
|
||||
return labels
|
||||
|
||||
|
||||
def community_member_sigs(communities: dict[int, list[str]]) -> dict[int, str]:
|
||||
"""Per-community membership fingerprints: ``{cid: sha256(sorted member ids)}``.
|
||||
|
||||
Persisted next to ``.graphify_labels.json`` so a later ``cluster-only`` can tell
|
||||
which communities actually changed since labeling. A cid whose members no longer
|
||||
hash the same is a different community — reusing its old (LLM) label there is the
|
||||
"stale label after re-scoping" bug this guards against. Deterministic; independent
|
||||
of cid index, node order, and machine.
|
||||
"""
|
||||
import hashlib
|
||||
|
||||
sigs: dict[int, str] = {}
|
||||
for cid, members in communities.items():
|
||||
h = hashlib.sha256()
|
||||
for nid in sorted(str(n) for n in members):
|
||||
h.update(nid.encode("utf-8", "replace"))
|
||||
h.update(b"\x00")
|
||||
sigs[cid] = h.hexdigest()[:16]
|
||||
return sigs
|
||||
|
||||
|
||||
def cluster(
|
||||
G: nx.Graph,
|
||||
resolution: float = 1.0,
|
||||
exclude_hubs_percentile: float | None = None,
|
||||
) -> dict[int, list[str]]:
|
||||
"""Run Leiden community detection. Returns {community_id: [node_ids]}.
|
||||
|
||||
Community IDs are stable across runs: 0 = largest community after splitting.
|
||||
Oversized communities (> 25% of graph nodes, min 10) are split by running
|
||||
a second Leiden pass on the subgraph.
|
||||
|
||||
Accepts directed or undirected graphs. DiGraphs are converted to undirected
|
||||
internally since Louvain/Leiden require undirected input.
|
||||
|
||||
resolution: passed to Leiden/Louvain. >1.0 = more smaller communities,
|
||||
<1.0 = fewer larger communities. Default 1.0.
|
||||
exclude_hubs_percentile: if set (0-100), nodes whose degree exceeds this
|
||||
percentile are excluded from partitioning and reattached to their
|
||||
majority-vote neighbour community afterwards. Useful for staging/utility
|
||||
super-hubs that inflate god-node rankings (#919).
|
||||
"""
|
||||
if G.number_of_nodes() == 0:
|
||||
return {}
|
||||
if G.is_directed():
|
||||
G = G.to_undirected()
|
||||
if G.number_of_edges() == 0:
|
||||
return {i: [n] for i, n in enumerate(sorted(G.nodes))}
|
||||
|
||||
from graspologic.partition import leiden # lazy — avoids 15s numba JIT on import
|
||||
# Compute hub exclusion set before removing anything so degree is based on full graph
|
||||
hub_nodes: set[str] = set()
|
||||
if exclude_hubs_percentile is not None:
|
||||
degrees = sorted(d for _, d in G.degree())
|
||||
if degrees:
|
||||
idx = max(0, int(len(degrees) * exclude_hubs_percentile / 100) - 1)
|
||||
threshold = degrees[idx]
|
||||
hub_nodes = {n for n, d in G.degree() if d > threshold}
|
||||
|
||||
# Leiden warns and drops isolates — handle them separately
|
||||
isolates = [n for n in G.nodes() if G.degree(n) == 0]
|
||||
connected_nodes = [n for n in G.nodes() if G.degree(n) > 0]
|
||||
# Leiden warns and drops isolates - handle them separately
|
||||
# Also exclude hub nodes from partitioning so they don't pull unrelated
|
||||
# subsystems into the same community
|
||||
excluded = hub_nodes
|
||||
isolates = [n for n in G.nodes() if G.degree(n) == 0 and n not in excluded]
|
||||
connected_nodes = [n for n in G.nodes() if G.degree(n) > 0 and n not in excluded]
|
||||
connected = G.subgraph(connected_nodes)
|
||||
|
||||
raw: dict[int, list[str]] = {}
|
||||
if connected.number_of_nodes() > 0:
|
||||
partition: dict[str, int] = leiden(connected)
|
||||
partition = _partition(connected, resolution=resolution)
|
||||
for node, cid in partition.items():
|
||||
raw.setdefault(cid, []).append(node)
|
||||
|
||||
@@ -55,6 +188,24 @@ def cluster(G: nx.Graph) -> dict[int, list[str]]:
|
||||
raw[next_cid] = [node]
|
||||
next_cid += 1
|
||||
|
||||
# Reattach excluded hubs by majority-vote neighbour community
|
||||
if hub_nodes:
|
||||
node_community: dict[str, int] = {n: cid for cid, nodes in raw.items() for n in nodes}
|
||||
for hub in sorted(hub_nodes):
|
||||
votes: dict[int, int] = {}
|
||||
for nb in G.neighbors(hub):
|
||||
cid = node_community.get(nb)
|
||||
if cid is not None:
|
||||
votes[cid] = votes.get(cid, 0) + 1
|
||||
if votes:
|
||||
best = min(votes, key=lambda c: (-votes[c], c))
|
||||
raw.setdefault(best, []).append(hub)
|
||||
node_community[hub] = best
|
||||
else:
|
||||
raw[next_cid] = [hub]
|
||||
node_community[hub] = next_cid
|
||||
next_cid += 1
|
||||
|
||||
# Split oversized communities
|
||||
max_size = max(_MIN_SPLIT_SIZE, int(G.number_of_nodes() * _MAX_COMMUNITY_FRACTION))
|
||||
final_communities: list[list[str]] = []
|
||||
@@ -64,8 +215,24 @@ def cluster(G: nx.Graph) -> dict[int, list[str]]:
|
||||
else:
|
||||
final_communities.append(nodes)
|
||||
|
||||
# Re-index by size descending for deterministic ordering
|
||||
final_communities.sort(key=len, reverse=True)
|
||||
# Second pass: re-split low-cohesion communities caused by doc-hub nodes
|
||||
# that bridge otherwise-unrelated subsystems (e.g. CLAUDE.md connected to everything).
|
||||
second_pass: list[list[str]] = []
|
||||
for nodes in final_communities:
|
||||
if len(nodes) >= _COHESION_SPLIT_MIN_SIZE and cohesion_score(G, nodes) < _COHESION_SPLIT_THRESHOLD:
|
||||
splits = _split_community(G, nodes)
|
||||
second_pass.extend(splits if len(splits) > 1 else [nodes])
|
||||
else:
|
||||
second_pass.append(nodes)
|
||||
final_communities = second_pass
|
||||
|
||||
# Re-index by size descending. The tuple(sorted(nodes)) tiebreak makes this a
|
||||
# TOTAL order, so an identical grouping always gets identical community IDs.
|
||||
# Without it, the hundreds of equal-sized small communities are ordered by the
|
||||
# partitioner's (not seed-stable) enumeration order, so their integer IDs
|
||||
# permute run-to-run - which reads as massive "community churn" in a per-node
|
||||
# cid diff even though the actual grouping is reproducible (#1090 follow-up).
|
||||
final_communities.sort(key=lambda nodes: (-len(nodes), tuple(sorted(map(str, nodes)))))
|
||||
return {i: sorted(nodes) for i, nodes in enumerate(final_communities)}
|
||||
|
||||
|
||||
@@ -73,16 +240,14 @@ def _split_community(G: nx.Graph, nodes: list[str]) -> list[list[str]]:
|
||||
"""Run a second Leiden pass on a community subgraph to split it further."""
|
||||
subgraph = G.subgraph(nodes)
|
||||
if subgraph.number_of_edges() == 0:
|
||||
# No edges — split into individual nodes
|
||||
# No edges - split into individual nodes
|
||||
return [[n] for n in sorted(nodes)]
|
||||
try:
|
||||
from graspologic.partition import leiden
|
||||
sub_partition: dict[str, int] = leiden(subgraph)
|
||||
sub_partition = _partition(subgraph)
|
||||
sub_communities: dict[int, list[str]] = {}
|
||||
for node, cid in sub_partition.items():
|
||||
sub_communities.setdefault(cid, []).append(node)
|
||||
if len(sub_communities) <= 1:
|
||||
# Leiden couldn't split it — return as-is
|
||||
return [sorted(nodes)]
|
||||
return [sorted(v) for v in sub_communities.values()]
|
||||
except Exception:
|
||||
@@ -97,8 +262,59 @@ def cohesion_score(G: nx.Graph, community_nodes: list[str]) -> float:
|
||||
subgraph = G.subgraph(community_nodes)
|
||||
actual = subgraph.number_of_edges()
|
||||
possible = n * (n - 1) / 2
|
||||
return round(actual / possible, 2) if possible > 0 else 0.0
|
||||
return actual / possible if possible > 0 else 0.0
|
||||
|
||||
|
||||
def score_all(G: nx.Graph, communities: dict[int, list[str]]) -> dict[int, float]:
|
||||
return {cid: cohesion_score(G, nodes) for cid, nodes in communities.items()}
|
||||
|
||||
|
||||
def remap_communities_to_previous(
|
||||
communities: dict[int, list[str]],
|
||||
previous_node_community: dict[str, int],
|
||||
) -> dict[int, list[str]]:
|
||||
"""Remap community IDs to maximize overlap with a previous assignment.
|
||||
|
||||
Uses greedy one-to-one matching by intersection size, then assigns fresh IDs
|
||||
to unmatched communities in deterministic order (size desc, lexical tie-break).
|
||||
"""
|
||||
if not communities:
|
||||
return {}
|
||||
|
||||
new_sets = {cid: set(nodes) for cid, nodes in communities.items()}
|
||||
old_sets: dict[int, set[str]] = {}
|
||||
for node, old_cid in previous_node_community.items():
|
||||
old_sets.setdefault(old_cid, set()).add(node)
|
||||
|
||||
overlaps: list[tuple[int, int, int]] = []
|
||||
for old_cid, old_nodes in old_sets.items():
|
||||
for new_cid, new_nodes in new_sets.items():
|
||||
overlap = len(old_nodes & new_nodes)
|
||||
if overlap > 0:
|
||||
overlaps.append((overlap, old_cid, new_cid))
|
||||
overlaps.sort(key=lambda x: (-x[0], x[1], x[2]))
|
||||
|
||||
new_to_final: dict[int, int] = {}
|
||||
used_old_ids: set[int] = set()
|
||||
matched_new_ids: set[int] = set()
|
||||
for _overlap, old_cid, new_cid in overlaps:
|
||||
if old_cid in used_old_ids or new_cid in matched_new_ids:
|
||||
continue
|
||||
new_to_final[new_cid] = old_cid
|
||||
used_old_ids.add(old_cid)
|
||||
matched_new_ids.add(new_cid)
|
||||
|
||||
unmatched = [cid for cid in communities if cid not in matched_new_ids]
|
||||
unmatched.sort(key=lambda cid: (-len(communities[cid]), tuple(sorted(communities[cid]))))
|
||||
next_id = 0
|
||||
for new_cid in unmatched:
|
||||
while next_id in used_old_ids:
|
||||
next_id += 1
|
||||
new_to_final[new_cid] = next_id
|
||||
used_old_ids.add(next_id)
|
||||
next_id += 1
|
||||
|
||||
remapped: dict[int, list[str]] = {}
|
||||
for new_cid, nodes in communities.items():
|
||||
remapped[new_to_final[new_cid]] = sorted(nodes)
|
||||
return dict(sorted(remapped.items(), key=lambda kv: kv[0]))
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
description: Build or query a graphify knowledge graph
|
||||
---
|
||||
|
||||
Invoke the `graphify` skill immediately.
|
||||
|
||||
Pass the full `/graphify` argument string through unchanged.
|
||||
If no arguments were supplied, treat the target path as `.`.
|
||||
|
||||
Examples:
|
||||
- `/graphify`
|
||||
- `/graphify src --update`
|
||||
- `/graphify query "what connects auth to billing?"`
|
||||
|
||||
Do not answer from raw files before handing off to the `graphify` skill.
|
||||
@@ -0,0 +1,568 @@
|
||||
"""Entity deduplication pipeline for graphify knowledge graphs.
|
||||
|
||||
Pipeline: exact normalization → entropy gate → MinHash/LSH blocking →
|
||||
Jaro-Winkler verification → same-community boost → union-find merge.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import math
|
||||
import re
|
||||
import sys
|
||||
import unicodedata
|
||||
from collections import defaultdict
|
||||
|
||||
from graphify._minhash import MinHash, MinHashLSH
|
||||
from rapidfuzz.distance import Jaro, JaroWinkler
|
||||
|
||||
|
||||
# ── helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
def _norm(label: str | None) -> str:
|
||||
"""Lowercase + collapse non-alphanumeric runs to space (Unicode-aware)."""
|
||||
if not isinstance(label, str):
|
||||
label = "" if label is None else str(label)
|
||||
label = unicodedata.normalize("NFKC", label)
|
||||
return re.sub(r"[\W_]+", " ", label.casefold(), flags=re.UNICODE).strip()
|
||||
|
||||
|
||||
def _entropy(label: str) -> float:
|
||||
"""Shannon entropy in bits/char of the normalised label."""
|
||||
s = _norm(label)
|
||||
if not s:
|
||||
return 0.0
|
||||
freq: dict[str, int] = defaultdict(int)
|
||||
for ch in s:
|
||||
freq[ch] += 1
|
||||
n = len(s)
|
||||
return -sum((c / n) * math.log2(c / n) for c in freq.values())
|
||||
|
||||
|
||||
def _shingles(text: str, k: int = 3) -> set[str]:
|
||||
"""Return k-gram character shingles of text."""
|
||||
if len(text) < k:
|
||||
return {text}
|
||||
return {text[i : i + k] for i in range(len(text) - k + 1)}
|
||||
|
||||
|
||||
def _make_minhash(text: str, num_perm: int = 128) -> MinHash:
|
||||
# Strip spaces so "graph extractor" and "graphextractor" share shingles
|
||||
m = MinHash(num_perm=num_perm)
|
||||
for shingle in _shingles(text.replace(" ", "")):
|
||||
m.update(shingle.encode("utf-8"))
|
||||
return m
|
||||
|
||||
|
||||
# Matches labels whose trailing token is a version/variant suffix:
|
||||
# digits optionally followed by letters (chip SKUs: ASR1603, M1, Cortex-A55)
|
||||
# or 2+ letters (codename revisions: cranelr vs cranel).
|
||||
# Requires the stem to end in a letter so plain words don't accidentally match.
|
||||
_VARIANT_SUFFIX = re.compile(r"^(.*[a-z])([0-9]+[a-z]*|[a-z]{2,})$")
|
||||
|
||||
|
||||
def _is_variant_pair(a: str, b: str) -> bool:
|
||||
"""True if a and b are sibling model/SKU variants (same stem, different suffix).
|
||||
|
||||
Only applied to short labels (< 12 chars); long labels go through JW normally.
|
||||
"""
|
||||
if a == b:
|
||||
return False
|
||||
if max(len(a), len(b)) >= 12:
|
||||
return False
|
||||
ma, mb = _VARIANT_SUFFIX.match(a), _VARIANT_SUFFIX.match(b)
|
||||
if not (ma and mb):
|
||||
return False
|
||||
return ma.group(1) == mb.group(1) and ma.group(2) != mb.group(2)
|
||||
|
||||
|
||||
def _short_label_blocked(a: str, b: str, jw_score: float) -> bool:
|
||||
"""Block fuzzy merge for short labels unless it's a same-length single-char substitution.
|
||||
|
||||
Insertions/deletions on short strings (cranel/cranelr, M1/M1 Pro) produce
|
||||
high Jaro-Winkler scores due to the prefix bonus but are almost never true
|
||||
duplicates — they're abbreviations or variants.
|
||||
"""
|
||||
if max(len(a), len(b)) >= 12:
|
||||
return False
|
||||
from rapidfuzz.distance import DamerauLevenshtein
|
||||
# Allow only same-length single-char substitutions (true typos like "Extractor"/"Extractar").
|
||||
# Block length-differing pairs regardless of score.
|
||||
if jw_score >= 97.0 and len(a) == len(b) and DamerauLevenshtein.distance(a, b) <= 1:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
_DIGIT_RUN = re.compile(r"\d+")
|
||||
|
||||
|
||||
def _numeric_tokens_differ(a: str, b: str) -> bool:
|
||||
"""True when two labels carry different embedded numbers (#1284).
|
||||
|
||||
Long labels that differ only in their digit runs ("ADR 0011 §D5" vs
|
||||
"ADR 0013 D4", "3.1 Product Goals" vs "1.1 Product Goals", "block3" vs
|
||||
"block13", "40%+ retention" vs "<20% retention") are numbered/versioned
|
||||
siblings, not duplicates -- but the long shared boilerplate keeps
|
||||
Jaro-Winkler above _MERGE_THRESHOLD, and _is_variant_pair only covers
|
||||
short trailing suffixes. Digit runs are compared as multisets with
|
||||
leading zeros stripped, so zero-padding ("09" vs "9") does not count as
|
||||
a difference. (String comparison, not int(): a pathological label with a
|
||||
>4300-digit run would crash int() on Python's conversion limit.) Labels
|
||||
with identical numbers, or none at all, are unaffected.
|
||||
"""
|
||||
if a == b:
|
||||
return False
|
||||
return sorted(t.lstrip("0") or "0" for t in _DIGIT_RUN.findall(a)) != \
|
||||
sorted(t.lstrip("0") or "0" for t in _DIGIT_RUN.findall(b))
|
||||
|
||||
|
||||
# file_type values whose identity is anchored to their source location, not
|
||||
# their label text. Like code (#1205), these must not be label-merged across
|
||||
# files: rationale = module/class docstrings, document = headings/positional
|
||||
# content. `concept` is intentionally excluded -- it is the type meant to unify
|
||||
# across files (protected from over-merge by the numeric/Jaro guards instead).
|
||||
_FILE_ANCHORED_NONCODE = frozenset({"rationale", "document"})
|
||||
|
||||
|
||||
def _crossfile_fileanchored_blocked(node: dict, neighbor: dict) -> bool:
|
||||
"""Block label-based merging of file-anchored non-code nodes across files (#1284).
|
||||
|
||||
rationale/document nodes are docstring- and heading-derived and as
|
||||
file-anchored as the code they describe (#1205's reasoning, one layer up):
|
||||
parallel modules carry near-identical boilerplate ("Django app config for
|
||||
apps.<name>. No business logic here...") that differs by one word and sails
|
||||
past the JW threshold. Same-file duplicates of these types may still merge.
|
||||
"""
|
||||
if (node.get("file_type") not in _FILE_ANCHORED_NONCODE
|
||||
and neighbor.get("file_type") not in _FILE_ANCHORED_NONCODE):
|
||||
return False
|
||||
return (node.get("source_file") or "") != (neighbor.get("source_file") or "")
|
||||
|
||||
|
||||
# ── union-find ────────────────────────────────────────────────────────────────
|
||||
|
||||
class _UF:
|
||||
def __init__(self) -> None:
|
||||
self._parent: dict[str, str] = {}
|
||||
|
||||
def find(self, x: str) -> str:
|
||||
self._parent.setdefault(x, x)
|
||||
while self._parent[x] != x:
|
||||
self._parent[x] = self._parent[self._parent[x]]
|
||||
x = self._parent[x]
|
||||
return x
|
||||
|
||||
def union(self, x: str, y: str) -> None:
|
||||
self._parent.setdefault(x, x)
|
||||
self._parent.setdefault(y, y)
|
||||
rx, ry = self.find(x), self.find(y)
|
||||
if rx != ry:
|
||||
self._parent[ry] = rx
|
||||
|
||||
def components(self) -> dict[str, list[str]]:
|
||||
groups: dict[str, list[str]] = defaultdict(list)
|
||||
for x in self._parent:
|
||||
groups[self.find(x)].append(x)
|
||||
return dict(groups)
|
||||
|
||||
|
||||
# ── constants ─────────────────────────────────────────────────────────────────
|
||||
|
||||
_ENTROPY_THRESHOLD = 2.5
|
||||
_LSH_THRESHOLD = 0.7
|
||||
_MERGE_THRESHOLD = 92.0 # rapidfuzz normalized_similarity * 100
|
||||
_COMMUNITY_BOOST = 5.0 # score bonus when both nodes share community
|
||||
_NUM_PERM = 128
|
||||
_CHUNK_SUFFIX = re.compile(r"_c\d+$")
|
||||
|
||||
|
||||
def _is_code(node: dict) -> bool:
|
||||
"""True for AST-extracted code symbols.
|
||||
|
||||
Code-node identity is the node ID (which already encodes the fully
|
||||
qualified path: module/class/symbol). The label is only a display name
|
||||
(e.g. a bare ``.draw()`` method name, or a function name shared by two
|
||||
parallel backends), so label-based merging conflates distinct symbols
|
||||
(#1205). Genuine duplicates — the same symbol re-extracted — share an ID
|
||||
and are already collapsed by the exact-ID ``seen_ids`` pre-dedup above,
|
||||
so code never needs label-based merging.
|
||||
"""
|
||||
return node.get("file_type") == "code"
|
||||
|
||||
|
||||
# ── main entry point ──────────────────────────────────────────────────────────
|
||||
|
||||
def deduplicate_entities(
|
||||
nodes: list[dict],
|
||||
edges: list[dict],
|
||||
*,
|
||||
communities: dict[str, int],
|
||||
dedup_llm_backend: str | None = None,
|
||||
) -> tuple[list[dict], list[dict]]:
|
||||
"""Deduplicate near-identical entities in a knowledge graph.
|
||||
|
||||
Args:
|
||||
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())
|
||||
dedup_llm_backend: if set, use LLM to resolve ambiguous pairs
|
||||
|
||||
Returns:
|
||||
(deduped_nodes, deduped_edges) with edges rewired to survivors
|
||||
"""
|
||||
# Guard: cross-project dedup is not supported — nodes from different repos
|
||||
# share label names by coincidence and must never be merged by string similarity.
|
||||
# If you need to dedup a global graph, run deduplicate_entities per-repo first.
|
||||
repos_seen = {n.get("repo") for n in nodes if n.get("repo")}
|
||||
if len(repos_seen) > 1:
|
||||
raise ValueError(
|
||||
f"deduplicate_entities: nodes span multiple repos {sorted(repos_seen)!r}. "
|
||||
f"Cross-project dedup is disabled — run dedup per-repo before merging."
|
||||
)
|
||||
|
||||
if len(nodes) <= 1:
|
||||
return nodes, edges
|
||||
|
||||
# Pre-deduplicate: keep first occurrence of each id.
|
||||
# Warn when two nodes share an ID but originate from different source files —
|
||||
# this indicates a cross-chunk ID collision (#1504) where silent data loss occurs.
|
||||
seen_ids: dict[str, dict] = {}
|
||||
for node in nodes:
|
||||
nid = node.get("id", "")
|
||||
if not nid:
|
||||
continue
|
||||
if nid not in seen_ids:
|
||||
seen_ids[nid] = node
|
||||
else:
|
||||
existing_sf = seen_ids[nid].get("source_file") or ""
|
||||
new_sf = node.get("source_file") or ""
|
||||
if existing_sf != new_sf:
|
||||
print(
|
||||
f"[graphify] WARNING: node '{nid}' from '{new_sf}' collides with "
|
||||
f"node from '{existing_sf}' — the second node will be dropped. "
|
||||
f"This is a cross-chunk ID collision caused by two files with the "
|
||||
f"same name in different directories. To avoid data loss, run "
|
||||
f"'graphify extract' per subfolder and merge with "
|
||||
f"'graphify merge-graphs'.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
unique_nodes = list(seen_ids.values())
|
||||
|
||||
if len(unique_nodes) <= 1:
|
||||
return unique_nodes, edges
|
||||
|
||||
# ── pass 1: exact normalization ───────────────────────────────────────────
|
||||
norm_to_nodes: dict[str, list[dict]] = defaultdict(list)
|
||||
for node in unique_nodes:
|
||||
# Code symbols are keyed by ID, never by label — skip them entirely so
|
||||
# distinct same-named symbols are never merged by string similarity (#1205).
|
||||
if _is_code(node):
|
||||
continue
|
||||
key = _norm(node.get("label", node.get("id", "")))
|
||||
if key:
|
||||
norm_to_nodes[key].append(node)
|
||||
|
||||
uf = _UF()
|
||||
exact_merges = 0
|
||||
for key, group in norm_to_nodes.items():
|
||||
if len(group) <= 1:
|
||||
continue
|
||||
# Partition by source_file — only merge within the same file in Pass 1.
|
||||
# Cross-file matches fall through to Pass 2 fuzzy matching.
|
||||
by_file: dict[str, list[dict]] = defaultdict(list)
|
||||
for node in group:
|
||||
sf = node.get("source_file") or ""
|
||||
by_file[sf].append(node)
|
||||
for sf, file_group in by_file.items():
|
||||
if not sf:
|
||||
# No source_file — cannot prove same symbol; skip to avoid
|
||||
# collapsing distinct nodes that happen to share a label (#1178).
|
||||
continue
|
||||
if len(file_group) > 1:
|
||||
winner = _pick_winner(file_group)
|
||||
for node in file_group:
|
||||
uf.union(winner["id"], node["id"])
|
||||
exact_merges += len(file_group) - 1
|
||||
|
||||
# ── pass 2: MinHash/LSH + Jaro-Winkler (high-entropy nodes only) ─────────
|
||||
candidates: list[dict] = []
|
||||
seen_norms: set[str] = set()
|
||||
for node in unique_nodes:
|
||||
# Code symbols are excluded from fuzzy matching too: two functions with
|
||||
# similar long names in different files (parallel backends, sibling
|
||||
# classes) must not be fuzzy-merged, and a code↔concept fuzzy match must
|
||||
# not transitively union two distinct code symbols via a concept (#1205).
|
||||
if _is_code(node):
|
||||
continue
|
||||
key = _norm(node.get("label", node.get("id", "")))
|
||||
if key and key not in seen_norms:
|
||||
seen_norms.add(key)
|
||||
if _entropy(node.get("label", "")) >= _ENTROPY_THRESHOLD:
|
||||
candidates.append(node)
|
||||
|
||||
fuzzy_merges = 0
|
||||
if len(candidates) >= 2:
|
||||
lsh = MinHashLSH(threshold=_LSH_THRESHOLD, num_perm=_NUM_PERM)
|
||||
minhashes: dict[str, MinHash] = {}
|
||||
# Pre-build O(1) lookup structures so the query loop below doesn't scan
|
||||
# the candidates list linearly for every LSH neighbor (was O(n²×B)).
|
||||
candidates_by_id: dict[str, dict] = {}
|
||||
norm_cache: dict[str, str] = {}
|
||||
|
||||
for node in candidates:
|
||||
node_id = node["id"]
|
||||
candidates_by_id[node_id] = node
|
||||
nl = _norm(node.get("label", node.get("id", "")))
|
||||
norm_cache[node_id] = nl
|
||||
m = _make_minhash(nl)
|
||||
minhashes[node_id] = m
|
||||
try:
|
||||
lsh.insert(node_id, m)
|
||||
except ValueError:
|
||||
pass # duplicate key in LSH — already inserted
|
||||
|
||||
for node in candidates:
|
||||
node_id = node["id"]
|
||||
norm_label = norm_cache[node_id]
|
||||
neighbors = lsh.query(minhashes[node_id])
|
||||
|
||||
for neighbor_id in neighbors:
|
||||
if neighbor_id == node_id:
|
||||
continue
|
||||
if uf.find(node_id) == uf.find(neighbor_id):
|
||||
continue
|
||||
|
||||
neighbor = candidates_by_id.get(neighbor_id)
|
||||
if neighbor is None:
|
||||
continue
|
||||
|
||||
neighbor_norm = norm_cache.get(neighbor_id) or _norm(neighbor.get("label", neighbor.get("id", "")))
|
||||
# Cross-file long labels score on plain Jaro (no prefix bonus).
|
||||
# Jaro-Winkler's leading-prefix bonus lifts pairs that share a
|
||||
# prefix but diverge in a distinguishing token ("testing-library
|
||||
# jest-native" vs "react-native") past threshold, fabricating
|
||||
# destructive cross-file merges; on Jaro alone they fall short
|
||||
# while true cross-file duplicates still clear it (#1243). Same-file
|
||||
# near-duplicates keep Jaro-Winkler (low-risk, and a mid-string
|
||||
# stopword insertion needs the prefix bonus to merge); short labels
|
||||
# keep Jaro-Winkler too (gated by _short_label_blocked).
|
||||
_xfile = (node.get("source_file") or "") != (neighbor.get("source_file") or "")
|
||||
if _xfile and max(len(norm_label), len(neighbor_norm)) >= 12:
|
||||
score = Jaro.normalized_similarity(norm_label, neighbor_norm) * 100
|
||||
else:
|
||||
score = JaroWinkler.normalized_similarity(norm_label, neighbor_norm) * 100
|
||||
|
||||
if _is_variant_pair(norm_label, neighbor_norm):
|
||||
continue
|
||||
if _short_label_blocked(norm_label, neighbor_norm, score):
|
||||
continue
|
||||
# Prefix-extension pairs (getActiveSession / getActiveSessions,
|
||||
# parseConfig / parseConfigFile) are almost never duplicates —
|
||||
# one is a strict suffix-extension of the other. Block the merge
|
||||
# regardless of JW score (#1201).
|
||||
_lo, _hi = sorted((norm_label, neighbor_norm), key=len)
|
||||
if _hi.startswith(_lo) and _hi != _lo:
|
||||
continue
|
||||
# Numbered/versioned siblings and cross-file file-anchored
|
||||
# boilerplate (rationale/document) are decisively distinct
|
||||
# regardless of score (#1284).
|
||||
if _numeric_tokens_differ(norm_label, neighbor_norm):
|
||||
continue
|
||||
if _crossfile_fileanchored_blocked(node, neighbor):
|
||||
continue
|
||||
|
||||
c1 = communities.get(node_id)
|
||||
c2 = communities.get(neighbor_id)
|
||||
if (c1 is not None and c2 is not None and c1 == c2
|
||||
and min(len(norm_label), len(neighbor_norm)) >= 12):
|
||||
score += _COMMUNITY_BOOST
|
||||
|
||||
if score >= _MERGE_THRESHOLD:
|
||||
# Identical labels across different source files almost always
|
||||
# means same-named-but-different symbols (trait impls, wrapper
|
||||
# methods, common type names). Mirror Pass 1's source_file
|
||||
# partition for this sub-case. (#1046, leaks #895's fix)
|
||||
if norm_label == neighbor_norm:
|
||||
sf_a = node.get("source_file") or ""
|
||||
sf_b = neighbor.get("source_file") or ""
|
||||
if sf_a != sf_b:
|
||||
continue
|
||||
# Pick the winner from the verified pair only. Selecting it
|
||||
# from the union of both normalized-label groups pulls
|
||||
# never-compared nodes (same label, different source_file)
|
||||
# into the merge, bypassing the #1046/#1178 guards.
|
||||
winner = _pick_winner([node, neighbor])
|
||||
uf.union(winner["id"], node_id)
|
||||
uf.union(winner["id"], neighbor_id)
|
||||
fuzzy_merges += 1
|
||||
|
||||
# ── pass 3: LLM tiebreaker for ambiguous pairs (opt-in) ──────────────────
|
||||
if dedup_llm_backend is not None:
|
||||
_llm_tiebreak(candidates, uf, communities, backend=dedup_llm_backend)
|
||||
|
||||
# ── build remap table from union-find components ──────────────────────────
|
||||
components = uf.components()
|
||||
remap: dict[str, str] = {}
|
||||
|
||||
for root, members in components.items():
|
||||
if len(members) == 1:
|
||||
continue
|
||||
group_nodes = [n for n in unique_nodes if n["id"] in members]
|
||||
winner = _pick_winner(group_nodes) if group_nodes else {"id": root}
|
||||
winner_id = winner["id"]
|
||||
for member in members:
|
||||
if member != winner_id:
|
||||
remap[member] = winner_id
|
||||
|
||||
# ── apply remap ───────────────────────────────────────────────────────────
|
||||
if not remap:
|
||||
return unique_nodes, edges
|
||||
|
||||
total = len(remap)
|
||||
msg = f"[graphify] Deduplicated {total} node(s)"
|
||||
if exact_merges:
|
||||
msg += f" ({exact_merges} exact"
|
||||
if fuzzy_merges:
|
||||
msg += f", {fuzzy_merges} fuzzy"
|
||||
msg += ")"
|
||||
print(msg + ".", flush=True)
|
||||
|
||||
deduped_nodes = [n for n in unique_nodes if n["id"] not in remap]
|
||||
deduped_edges = []
|
||||
for edge in edges:
|
||||
e = dict(edge)
|
||||
# Tolerate "from"/"to" keys from LLM backends that don't follow the
|
||||
# schema exactly — build_from_json normalises later but dedup runs
|
||||
# first so bracket access would KeyError here (#803).
|
||||
# Use explicit key presence check (not `or`) so empty-string src/tgt
|
||||
# aren't silently replaced by the fallback key.
|
||||
src = e["source"] if "source" in e else e.get("from")
|
||||
tgt = e["target"] if "target" in e else e.get("to")
|
||||
if src is None or tgt is None:
|
||||
continue
|
||||
e["source"] = remap.get(src, src)
|
||||
e["target"] = remap.get(tgt, tgt)
|
||||
# Remove legacy keys so they don't leak into edge attrs in graph.json.
|
||||
e.pop("from", None)
|
||||
e.pop("to", None)
|
||||
if e["source"] != e["target"]:
|
||||
deduped_edges.append(e)
|
||||
|
||||
return deduped_nodes, deduped_edges
|
||||
|
||||
|
||||
def _pick_winner(nodes: list[dict]) -> dict:
|
||||
"""Pick the canonical survivor: prefer no chunk suffix, then shorter ID."""
|
||||
if not nodes:
|
||||
raise ValueError("Cannot pick winner from empty list")
|
||||
|
||||
def _score(n: dict) -> tuple[int, int]:
|
||||
has_suffix = bool(_CHUNK_SUFFIX.search(n["id"]))
|
||||
return (1 if has_suffix else 0, len(n["id"]))
|
||||
|
||||
return min(nodes, key=_score)
|
||||
|
||||
|
||||
def _llm_tiebreak(
|
||||
candidates: list[dict],
|
||||
uf: _UF,
|
||||
communities: dict[str, int],
|
||||
*,
|
||||
backend: str,
|
||||
batch_size: int = 30,
|
||||
low: float = 75.0,
|
||||
high: float = 92.0,
|
||||
) -> None:
|
||||
"""Batch-resolve ambiguous pairs (score in [low, high)) via LLM."""
|
||||
try:
|
||||
from graphify.llm import BACKENDS, _format_backend_env_keys, _get_backend_api_key
|
||||
if backend not in BACKENDS:
|
||||
print(f"[graphify] --dedup-llm: unknown backend {backend!r}, skipping LLM tiebreaker.", flush=True)
|
||||
return
|
||||
if not _get_backend_api_key(backend):
|
||||
env_keys = _format_backend_env_keys(backend)
|
||||
print(f"[graphify] --dedup-llm: {env_keys} not set, skipping LLM tiebreaker.", flush=True)
|
||||
return
|
||||
except ImportError:
|
||||
return
|
||||
|
||||
ambiguous: list[tuple[dict, dict, float]] = []
|
||||
for i, node in enumerate(candidates):
|
||||
norm_i = _norm(node.get("label", node.get("id", "")))
|
||||
for j in range(i + 1, len(candidates)):
|
||||
neighbor = candidates[j]
|
||||
if uf.find(node["id"]) == uf.find(neighbor["id"]):
|
||||
continue
|
||||
norm_j = _norm(neighbor.get("label", neighbor.get("id", "")))
|
||||
# Mirror pass 2: plain Jaro for cross-file long labels (#1243).
|
||||
_xfile = (node.get("source_file") or "") != (neighbor.get("source_file") or "")
|
||||
if _xfile and max(len(norm_i), len(norm_j)) >= 12:
|
||||
score = Jaro.normalized_similarity(norm_i, norm_j) * 100
|
||||
else:
|
||||
score = JaroWinkler.normalized_similarity(norm_i, norm_j) * 100
|
||||
if _is_variant_pair(norm_i, norm_j):
|
||||
continue
|
||||
if _short_label_blocked(norm_i, norm_j, score):
|
||||
continue
|
||||
_lo, _hi = sorted((norm_i, norm_j), key=len)
|
||||
if _hi.startswith(_lo) and _hi != _lo:
|
||||
continue
|
||||
# Mirror pass 2: decisively-distinct pairs never reach the LLM (#1284).
|
||||
if _numeric_tokens_differ(norm_i, norm_j):
|
||||
continue
|
||||
if _crossfile_fileanchored_blocked(node, neighbor):
|
||||
continue
|
||||
c1 = communities.get(node["id"])
|
||||
c2 = communities.get(neighbor["id"])
|
||||
if (c1 is not None and c2 is not None and c1 == c2
|
||||
and min(len(norm_i), len(norm_j)) >= 12):
|
||||
score += _COMMUNITY_BOOST
|
||||
if low <= score < high:
|
||||
ambiguous.append((node, neighbor, score))
|
||||
|
||||
if not ambiguous:
|
||||
return
|
||||
|
||||
try:
|
||||
from graphify.llm import _call_llm
|
||||
except ImportError as exc:
|
||||
# F-038: previously this silent fallback hid the fact that `_call_llm`
|
||||
# didn't exist in `graphify.llm` at all, so `--dedup-llm` was a no-op.
|
||||
# Surface the import failure so future regressions are visible.
|
||||
print(
|
||||
f"[graphify] --dedup-llm: cannot import _call_llm ({exc}); skipping LLM tiebreaker.",
|
||||
flush=True,
|
||||
)
|
||||
return
|
||||
|
||||
for batch_start in range(0, len(ambiguous), batch_size):
|
||||
batch = ambiguous[batch_start : batch_start + batch_size]
|
||||
pairs_text = "\n".join(
|
||||
f"{i+1}. \"{a['label']}\" vs \"{b['label']}\""
|
||||
for i, (a, b, _) in enumerate(batch)
|
||||
)
|
||||
prompt = (
|
||||
"For each pair below, answer only 'yes' or 'no': are they the same real-world concept?\n\n"
|
||||
f"{pairs_text}\n\n"
|
||||
"Reply with one line per pair: '1. yes', '2. no', etc."
|
||||
)
|
||||
try:
|
||||
response = _call_llm(prompt, backend=backend, max_tokens=200)
|
||||
lines = response.strip().splitlines()
|
||||
for line in lines:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
parts = line.split(".", 1)
|
||||
if len(parts) != 2:
|
||||
continue
|
||||
try:
|
||||
idx = int(parts[0].strip()) - 1
|
||||
except ValueError:
|
||||
continue
|
||||
if 0 <= idx < len(batch):
|
||||
answer = parts[1].strip().lower()
|
||||
if answer.startswith("yes"):
|
||||
a, b, _ = batch[idx]
|
||||
winner = _pick_winner([a, b])
|
||||
uf.union(winner["id"], a["id"])
|
||||
uf.union(winner["id"], b["id"])
|
||||
except Exception as exc:
|
||||
print(f"[graphify] --dedup-llm batch failed: {exc}", flush=True)
|
||||
+1216
-50
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,396 @@
|
||||
"""Read-only diagnostics for MultiDiGraph readiness."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from collections import Counter, defaultdict
|
||||
from copy import deepcopy
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import networkx as nx
|
||||
|
||||
|
||||
_SUPPRESSION_DECL_RE = re.compile(r"^\s*(?P<name>seen_[A-Za-z0-9_]+)\s*[:=]")
|
||||
_TYPE_TUPLE_RE = re.compile(r"set\[tuple\[(?P<inside>[^\]]+)\]\]")
|
||||
|
||||
|
||||
def _safe_text(value: Any) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
if isinstance(value, (str, int, float, bool)):
|
||||
return str(value)
|
||||
return json.dumps(value, sort_keys=True, default=str, ensure_ascii=False)
|
||||
|
||||
|
||||
def _edge_list(extraction: dict[str, Any]) -> list[Any]:
|
||||
edges = extraction.get("edges")
|
||||
if edges is None:
|
||||
edges = extraction.get("links")
|
||||
return edges if isinstance(edges, list) else []
|
||||
|
||||
|
||||
def _node_ids(extraction: dict[str, Any]) -> set[str]:
|
||||
nodes = extraction.get("nodes", [])
|
||||
if not isinstance(nodes, list):
|
||||
return set()
|
||||
return {
|
||||
str(node["id"])
|
||||
for node in nodes
|
||||
if isinstance(node, dict) and "id" in node and node.get("id") is not None
|
||||
}
|
||||
|
||||
|
||||
def _canonical_edge(edge: Any) -> dict[str, str]:
|
||||
if not isinstance(edge, dict):
|
||||
return {
|
||||
"source": "",
|
||||
"target": "",
|
||||
"relation": "",
|
||||
"confidence": "",
|
||||
"source_file": "",
|
||||
"source_location": "",
|
||||
"context": "",
|
||||
"_invalid": "non_object_edge",
|
||||
}
|
||||
source = edge.get("source", edge.get("from"))
|
||||
target = edge.get("target", edge.get("to"))
|
||||
return {
|
||||
"source": _safe_text(source),
|
||||
"target": _safe_text(target),
|
||||
"relation": _safe_text(edge.get("relation")),
|
||||
"confidence": _safe_text(edge.get("confidence")),
|
||||
"source_file": _safe_text(edge.get("source_file")),
|
||||
"source_location": _safe_text(edge.get("source_location")),
|
||||
"context": _safe_text(edge.get("context")),
|
||||
"_invalid": "",
|
||||
}
|
||||
|
||||
|
||||
def _exact_signature(edge: Any) -> str:
|
||||
if not isinstance(edge, dict):
|
||||
return "<non-object>"
|
||||
normalized = dict(edge)
|
||||
if "source" not in normalized and "from" in normalized:
|
||||
normalized["source"] = normalized["from"]
|
||||
if "target" not in normalized and "to" in normalized:
|
||||
normalized["target"] = normalized["to"]
|
||||
normalized.pop("from", None)
|
||||
normalized.pop("to", None)
|
||||
return json.dumps(
|
||||
normalized,
|
||||
sort_keys=True,
|
||||
default=str,
|
||||
ensure_ascii=False,
|
||||
separators=(",", ":"),
|
||||
)
|
||||
|
||||
|
||||
def _count_extra(counter: Counter[Any]) -> int:
|
||||
return sum(count - 1 for count in counter.values() if count > 1)
|
||||
|
||||
|
||||
def _variant_group_count(
|
||||
grouped_edges: dict[tuple[str, str], list[dict[str, str]]],
|
||||
field: str,
|
||||
*,
|
||||
relation_sensitive: bool = False,
|
||||
) -> int:
|
||||
groups = 0
|
||||
for edges in grouped_edges.values():
|
||||
if relation_sensitive:
|
||||
by_relation: dict[str, set[str]] = defaultdict(set)
|
||||
for edge in edges:
|
||||
by_relation[edge["relation"]].add(edge[field])
|
||||
groups += sum(1 for values in by_relation.values() if len(values) > 1)
|
||||
elif len({edge[field] for edge in edges}) > 1:
|
||||
groups += 1
|
||||
return groups
|
||||
|
||||
|
||||
def _tuple_arity_from_annotation(line: str) -> int:
|
||||
match = _TYPE_TUPLE_RE.search(line)
|
||||
if not match:
|
||||
return 0
|
||||
inside = match.group("inside").strip()
|
||||
if not inside:
|
||||
return 0
|
||||
return inside.count(",") + 1
|
||||
|
||||
|
||||
def scan_producer_suppression_sites(path: str | Path) -> dict[str, Any]:
|
||||
"""Find likely `seen_*` producer-suppression sets in an extractor file."""
|
||||
source_path = Path(path)
|
||||
if not source_path.exists():
|
||||
return {
|
||||
"path": str(source_path),
|
||||
"total_sites": 0,
|
||||
"sites": [],
|
||||
"error": "file not found",
|
||||
}
|
||||
|
||||
sites: list[dict[str, Any]] = []
|
||||
lines = source_path.read_text(encoding="utf-8").splitlines()
|
||||
for lineno, line in enumerate(lines, start=1):
|
||||
match = _SUPPRESSION_DECL_RE.match(line)
|
||||
if not match:
|
||||
continue
|
||||
sites.append(
|
||||
{
|
||||
"line": lineno,
|
||||
"name": match.group("name"),
|
||||
"tuple_arity": _tuple_arity_from_annotation(line),
|
||||
"sample": line.strip()[:120],
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"path": str(source_path),
|
||||
"total_sites": len(sites),
|
||||
"sites": sites,
|
||||
"error": "",
|
||||
}
|
||||
|
||||
|
||||
def diagnose_extraction(
|
||||
extraction: dict[str, Any],
|
||||
*,
|
||||
directed: bool = True,
|
||||
root: str | Path | None = None,
|
||||
max_examples: int = 5,
|
||||
extract_path: str | Path | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Summarize same-endpoint edge-collapse risk for one JSON graph/extraction dict."""
|
||||
from graphify.build import build_from_json
|
||||
|
||||
node_ids = _node_ids(extraction)
|
||||
raw_edges = _edge_list(extraction)
|
||||
canonical_edges = [_canonical_edge(edge) for edge in raw_edges]
|
||||
|
||||
exact_counts: Counter[str] = Counter(_exact_signature(edge) for edge in raw_edges)
|
||||
directed_pairs: Counter[tuple[str, str]] = Counter()
|
||||
undirected_pairs: Counter[tuple[str, str]] = Counter()
|
||||
grouped: dict[tuple[str, str], list[dict[str, str]]] = defaultdict(list)
|
||||
|
||||
non_object_edges = 0
|
||||
missing_endpoint_edges = 0
|
||||
dangling_endpoint_edges = 0
|
||||
self_loop_edges = 0
|
||||
valid_candidate_edges = 0
|
||||
|
||||
for edge in canonical_edges:
|
||||
if edge["_invalid"]:
|
||||
non_object_edges += 1
|
||||
continue
|
||||
source = edge["source"]
|
||||
target = edge["target"]
|
||||
if not source or not target:
|
||||
missing_endpoint_edges += 1
|
||||
continue
|
||||
if source not in node_ids or target not in node_ids:
|
||||
dangling_endpoint_edges += 1
|
||||
continue
|
||||
if source == target:
|
||||
self_loop_edges += 1
|
||||
valid_candidate_edges += 1
|
||||
directed_pair = (source, target)
|
||||
undirected_pair = (source, target) if source <= target else (target, source)
|
||||
directed_pairs[directed_pair] += 1
|
||||
undirected_pairs[undirected_pair] += 1
|
||||
grouped[directed_pair].append(edge)
|
||||
|
||||
examples: list[dict[str, Any]] = []
|
||||
if max_examples > 0:
|
||||
for (source, target), count in directed_pairs.most_common():
|
||||
if count < 2:
|
||||
continue
|
||||
edges = grouped[(source, target)]
|
||||
examples.append(
|
||||
{
|
||||
"source": source,
|
||||
"target": target,
|
||||
"edge_count": count,
|
||||
"relations": sorted({edge["relation"] for edge in edges}),
|
||||
"source_files": sorted({edge["source_file"] for edge in edges}),
|
||||
"source_locations": sorted({edge["source_location"] for edge in edges}),
|
||||
"contexts": sorted({edge["context"] for edge in edges}),
|
||||
}
|
||||
)
|
||||
if len(examples) >= max_examples:
|
||||
break
|
||||
|
||||
build_error = ""
|
||||
graph_type = ""
|
||||
post_build_edge_count: int | None = None
|
||||
post_build_node_count: int | None = None
|
||||
try:
|
||||
graph_input = deepcopy(extraction)
|
||||
graph: nx.Graph = build_from_json(graph_input, directed=directed, root=root)
|
||||
graph_type = type(graph).__name__
|
||||
post_build_edge_count = graph.number_of_edges()
|
||||
post_build_node_count = graph.number_of_nodes()
|
||||
except Exception as exc:
|
||||
build_error = f"{type(exc).__name__}: {exc}"
|
||||
|
||||
suppression_path = (
|
||||
Path(extract_path) if extract_path else Path(__file__).with_name("extract.py")
|
||||
)
|
||||
|
||||
return {
|
||||
"node_count": len(node_ids),
|
||||
"raw_edge_count": len(raw_edges),
|
||||
"non_object_edges": non_object_edges,
|
||||
"missing_endpoint_edges": missing_endpoint_edges,
|
||||
"dangling_endpoint_edges": dangling_endpoint_edges,
|
||||
"self_loop_edges": self_loop_edges,
|
||||
"valid_candidate_edges": valid_candidate_edges,
|
||||
"exact_duplicate_edges": _count_extra(exact_counts),
|
||||
"directed_unique_endpoint_pairs": len(directed_pairs),
|
||||
"directed_same_endpoint_collapsed_edges": _count_extra(directed_pairs),
|
||||
"undirected_unique_endpoint_pairs": len(undirected_pairs),
|
||||
"undirected_same_endpoint_collapsed_edges": _count_extra(undirected_pairs),
|
||||
"same_endpoint_group_count": sum(1 for count in directed_pairs.values() if count > 1),
|
||||
"relation_variant_groups": _variant_group_count(grouped, "relation"),
|
||||
"source_file_variant_groups": _variant_group_count(
|
||||
grouped, "source_file", relation_sensitive=True
|
||||
),
|
||||
"source_location_variant_groups": _variant_group_count(
|
||||
grouped, "source_location", relation_sensitive=True
|
||||
),
|
||||
"context_variant_groups": _variant_group_count(grouped, "context", relation_sensitive=True),
|
||||
"post_build_graph_type": graph_type,
|
||||
"post_build_node_count": post_build_node_count,
|
||||
"post_build_edge_count": post_build_edge_count,
|
||||
"post_build_error": build_error,
|
||||
"producer_suppression": scan_producer_suppression_sites(suppression_path),
|
||||
"examples": examples,
|
||||
}
|
||||
|
||||
|
||||
def _read_json_file(path: str | Path) -> dict[str, Any]:
|
||||
"""Read a JSON graph after applying Graphify's graph-load size cap."""
|
||||
from graphify.security import check_graph_file_size_cap
|
||||
|
||||
json_path = Path(path)
|
||||
check_graph_file_size_cap(json_path)
|
||||
try:
|
||||
data = json.loads(json_path.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError) as exc:
|
||||
raise RuntimeError(
|
||||
f"Cannot parse {json_path}: {exc}. "
|
||||
"The file may be corrupted — re-run 'graphify extract'."
|
||||
) from exc
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("diagnostic input must be a JSON object")
|
||||
return data
|
||||
|
||||
|
||||
def diagnose_file(
|
||||
path: str | Path,
|
||||
*,
|
||||
directed: bool | None = None,
|
||||
root: str | Path | None = None,
|
||||
max_examples: int = 5,
|
||||
extract_path: str | Path | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Diagnose a graph/extraction JSON file without mutating it.
|
||||
|
||||
When `directed` is None, the JSON's "directed" flag is honored. Raw
|
||||
extraction JSON that has no "directed" flag defaults to directed analysis.
|
||||
"""
|
||||
data = _read_json_file(path)
|
||||
if directed is None:
|
||||
raw_directed = data.get("directed")
|
||||
effective_directed = raw_directed if isinstance(raw_directed, bool) else True
|
||||
else:
|
||||
effective_directed = directed
|
||||
|
||||
summary = diagnose_extraction(
|
||||
data,
|
||||
directed=effective_directed,
|
||||
root=root,
|
||||
max_examples=max_examples,
|
||||
extract_path=extract_path,
|
||||
)
|
||||
summary["input_path"] = str(path)
|
||||
summary["effective_directed"] = effective_directed
|
||||
return summary
|
||||
|
||||
|
||||
def format_diagnostic_json(summary: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"schema_version": 1,
|
||||
"summary": {
|
||||
key: value
|
||||
for key, value in summary.items()
|
||||
if key not in {"examples", "producer_suppression"}
|
||||
},
|
||||
"examples": summary.get("examples", []),
|
||||
"producer_suppression": summary.get("producer_suppression", {}),
|
||||
"notes": [
|
||||
"Diagnostics are read-only.",
|
||||
"A normal graph.json is already post-build and cannot recover raw producer edges.",
|
||||
"Producer suppression sites are heuristic source-code evidence.",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def format_diagnostic_report(summary: dict[str, Any]) -> str:
|
||||
suppression = summary.get("producer_suppression", {})
|
||||
lines = [
|
||||
"[graphify] MultiDiGraph edge-collapse diagnostic",
|
||||
f"input: {summary.get('input_path', '<in-memory>')}",
|
||||
"input_stage: provided JSON (normal graph.json is post-build)",
|
||||
f"effective_directed: {summary.get('effective_directed', '<direct-call>')}",
|
||||
f"nodes: {summary['node_count']}",
|
||||
f"raw_edges: {summary['raw_edge_count']}",
|
||||
f"valid_candidate_edges: {summary['valid_candidate_edges']}",
|
||||
f"missing_endpoint_edges: {summary['missing_endpoint_edges']}",
|
||||
f"dangling_endpoint_edges: {summary['dangling_endpoint_edges']}",
|
||||
f"self_loop_edges: {summary['self_loop_edges']}",
|
||||
f"exact_duplicate_edges: {summary['exact_duplicate_edges']}",
|
||||
f"directed_unique_endpoint_pairs: {summary['directed_unique_endpoint_pairs']}",
|
||||
(
|
||||
"directed_same_endpoint_collapsed_edges: "
|
||||
f"{summary['directed_same_endpoint_collapsed_edges']}"
|
||||
),
|
||||
f"undirected_unique_endpoint_pairs: {summary['undirected_unique_endpoint_pairs']}",
|
||||
(
|
||||
"undirected_same_endpoint_collapsed_edges: "
|
||||
f"{summary['undirected_same_endpoint_collapsed_edges']}"
|
||||
),
|
||||
f"same_endpoint_group_count: {summary['same_endpoint_group_count']}",
|
||||
f"relation_variant_groups: {summary['relation_variant_groups']}",
|
||||
f"source_file_variant_groups: {summary['source_file_variant_groups']}",
|
||||
f"source_location_variant_groups: {summary['source_location_variant_groups']}",
|
||||
f"context_variant_groups: {summary['context_variant_groups']}",
|
||||
f"post_build_graph_type: {summary['post_build_graph_type']}",
|
||||
f"post_build_edges: {summary['post_build_edge_count']}",
|
||||
f"producer_suppression_sites: {suppression.get('total_sites', 0)}",
|
||||
]
|
||||
if summary.get("post_build_error"):
|
||||
lines.append(f"post_build_error: {summary['post_build_error']}")
|
||||
if suppression.get("error"):
|
||||
lines.append(f"producer_suppression_error: {suppression['error']}")
|
||||
if suppression.get("sites"):
|
||||
lines.append("producer_suppression_examples:")
|
||||
for site in suppression["sites"][:8]:
|
||||
lines.append(
|
||||
f" - L{site['line']} {site['name']} arity={site['tuple_arity'] or 'unknown'}"
|
||||
)
|
||||
if summary.get("examples"):
|
||||
lines.append("examples:")
|
||||
for example in summary["examples"]:
|
||||
lines.append(
|
||||
" - "
|
||||
f"{example['source']} -> {example['target']} "
|
||||
f"edges={example['edge_count']} "
|
||||
f"relations={example['relations']} "
|
||||
f"locations={example['source_locations']} "
|
||||
f"contexts={example['contexts']}"
|
||||
)
|
||||
lines.append(
|
||||
"note: normal graph.json is post-build; raw producer loss must be measured earlier."
|
||||
)
|
||||
return "\n".join(lines)
|
||||
+1158
-150
File diff suppressed because it is too large.
Load diff
+15188
-1668
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,93 @@
|
||||
# Migrating a language extractor out of extract.py
|
||||
|
||||
`graphify/extract.py` is being split into this package, one language per PR
|
||||
(upstream issue #1212). This is the playbook for porting ONE language. It is
|
||||
written so an AI agent can execute it in a single session.
|
||||
|
||||
## Status
|
||||
|
||||
| module | migrated |
|
||||
|---|---|
|
||||
| blade | yes |
|
||||
| zig | yes |
|
||||
| elixir | yes |
|
||||
| razor | yes |
|
||||
| (40 more in extract.py) | no |
|
||||
|
||||
Note: config-driven extractors (python, js, java, c, cpp, ruby, csharp,
|
||||
kotlin, scala, php, lua, swift, groovy) depend on the shared
|
||||
`_extract_generic` core (~1,300 lines). Do NOT port them one-by-one; the core
|
||||
must move first as its own coordinated batch. Pick a bespoke extractor.
|
||||
|
||||
## Invariants (non-negotiable)
|
||||
|
||||
1. **Verbatim moves only.** No renames, no docstring edits, no reformatting,
|
||||
no added annotations, no "improvements". Verify: save the block before
|
||||
cutting and confirm the pasted block is byte-identical.
|
||||
2. **One language per PR.** Small diffs keep review trivial and avoid
|
||||
conflicts with other in-flight ports.
|
||||
3. **Facade re-export is mandatory.** `extract.py` must keep exporting every
|
||||
moved name (`from graphify.extractors.<mod> import extract_<lang> # noqa: F401`
|
||||
in the marked migration block, kept alphabetical). Existing importers
|
||||
(`__main__.py`, `watch.py`, `pg_introspect.py`, tests) must not change.
|
||||
4. **Never import from `graphify.extract` inside this package.** Import
|
||||
direction is strictly extract.py -> extractors/. If you need a helper that
|
||||
lives in extract.py, classify it (below) and move it.
|
||||
5. **Zero test edits** outside `tests/test_extractors_registry.py`. The
|
||||
untouched language tests passing IS the proof of behavior preservation.
|
||||
|
||||
## Helper classification
|
||||
|
||||
For every `_name` your function references that is defined OUTSIDE it:
|
||||
|
||||
- run `grep -c '_name' graphify/extract.py` AFTER your candidate move;
|
||||
- remaining uses > 0 -> **shared**: move it to `base.py` and add it to the
|
||||
facade re-import in extract.py;
|
||||
- remaining uses = 0 -> **private**: move it into your language module.
|
||||
|
||||
Closures, constants, and `import` statements defined INSIDE your function
|
||||
move with it for free — leave them exactly where they are. Only add a
|
||||
module-header import for names the pasted code references at module scope
|
||||
that are not satisfied internally, and verify each header import is used.
|
||||
|
||||
## Pre-flight
|
||||
|
||||
1. Check upstream for conflicts: open PRs/issues mentioning your language,
|
||||
and churn: `git log --oneline --since="3 months ago" upstream/<default> | grep -i <lang>`.
|
||||
High churn -> pick another language.
|
||||
2. Confirm your extractor is bespoke (its `extract_<lang>` is a full function,
|
||||
not a 5-line `_extract_generic(path, LanguageConfig(...))` wrapper).
|
||||
3. Check whether tests/ exercises your language's behavior (grep for
|
||||
`test_<lang>`). If it has no behavioral tests, the byte-identity check in
|
||||
step 3 below is the ENTIRE proof of preservation — include the
|
||||
`git diff --color-moved` evidence in your PR description.
|
||||
|
||||
## Steps
|
||||
|
||||
1. Append a failing test to `tests/test_extractors_registry.py`:
|
||||
module import + facade identity + registry identity (copy an existing
|
||||
`test_<lang>_migrated` as the template).
|
||||
2. `grep -n 'def extract_<lang>' graphify/extract.py`; the span ends at the
|
||||
line before the next top-level statement (`^def ` or `^_CONST`). Beware
|
||||
neighbors: top-level constants AFTER your function may belong to the NEXT
|
||||
function (e.g. `_CONFIG_JSON_*` sit after where extract_razor used to be
|
||||
but were never razor's).
|
||||
3. Save the span to a temp file. Create `graphify/extractors/<lang>.py` with
|
||||
module docstring (`"""<Lang> extractor. Moved verbatim from graphify/extract.py."""`),
|
||||
`from __future__ import annotations`, minimal stdlib imports, base imports,
|
||||
then paste the function. Verify byte-identity against the temp file.
|
||||
4. Delete the span from extract.py, leaving exactly two blank lines between
|
||||
the now-adjacent top-level definitions; add the facade re-import; add the
|
||||
registry entry in `__init__.py` (alphabetical); update the Status table
|
||||
above.
|
||||
5. `uv run pytest -q` -> 0 failures, no test file changed except the registry
|
||||
test. If ImportError/NameError: a helper was misclassified — go to
|
||||
Helper classification.
|
||||
6. One commit: `refactor(extract): move extract_<lang> to extractors/<lang>.py (verbatim)`.
|
||||
|
||||
## What NOT to do
|
||||
|
||||
- Do not rewire dispatch, add classes, or add lazy imports — mechanism layers
|
||||
come later, by separate agreement (see #1212 discussion).
|
||||
- Do not port two languages in one PR "while you're at it".
|
||||
- Do not touch `__main__.py`.
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Per-language extractors, incrementally migrated out of graphify/extract.py.
|
||||
|
||||
Dispatch still flows through graphify.extract (the facade re-exports every
|
||||
moved name), so importing from graphify.extract keeps working unchanged.
|
||||
LANGUAGE_EXTRACTORS is the registry seed; wiring dispatch through it is a
|
||||
later, separate step. See MIGRATION.md for how to port another language.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
from graphify.extractors.blade import extract_blade
|
||||
from graphify.extractors.elixir import extract_elixir
|
||||
from graphify.extractors.razor import extract_razor
|
||||
from graphify.extractors.zig import extract_zig
|
||||
|
||||
LANGUAGE_EXTRACTORS: dict[str, Callable[[Path], dict]] = {
|
||||
"blade": extract_blade,
|
||||
"elixir": extract_elixir,
|
||||
"razor": extract_razor,
|
||||
"zig": extract_zig,
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
# DO NOT import from graphify.extract here — direction is extract.py → extractors/ only.
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from graphify.ids import make_id
|
||||
|
||||
# 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)).
|
||||
# Without this filter they become god-nodes accumulating spurious edges from
|
||||
# every call site. Filter applied at same-file and cross-file resolution.
|
||||
# See issue #726.
|
||||
_LANGUAGE_BUILTIN_GLOBALS: frozenset[str] = frozenset({
|
||||
# JavaScript / TypeScript ECMAScript built-ins
|
||||
"String", "Number", "Boolean", "Object", "Array", "Symbol", "BigInt",
|
||||
"Date", "RegExp", "Error", "TypeError", "RangeError", "SyntaxError",
|
||||
"ReferenceError", "EvalError", "URIError",
|
||||
"Promise", "Map", "Set", "WeakMap", "WeakSet", "JSON", "Math",
|
||||
"Reflect", "Proxy", "Intl",
|
||||
"parseInt", "parseFloat", "isNaN", "isFinite",
|
||||
"encodeURIComponent", "decodeURIComponent", "encodeURI", "decodeURI",
|
||||
# Browser / Node common globals
|
||||
"URL", "URLSearchParams", "FormData", "Blob", "File",
|
||||
"Headers", "Request", "Response", "AbortController", "AbortSignal",
|
||||
"TextEncoder", "TextDecoder", "console",
|
||||
# Python built-in callables
|
||||
"str", "int", "float", "bool", "list", "dict", "set", "tuple", "bytes",
|
||||
"len", "range", "enumerate", "zip", "map", "filter", "sum", "min", "max",
|
||||
"print", "open", "isinstance", "type", "super", "sorted", "reversed",
|
||||
"any", "all", "abs", "round", "next", "iter", "hash", "id", "repr",
|
||||
"callable", "getattr", "setattr", "hasattr", "delattr", "vars", "dir",
|
||||
})
|
||||
|
||||
|
||||
def _make_id(*parts: str) -> str:
|
||||
return make_id(*parts)
|
||||
|
||||
|
||||
def _file_stem(path: Path) -> str:
|
||||
"""Stem used as the node-ID prefix for a file and its symbols.
|
||||
|
||||
The full path (extension dropped) is preserved as path segments; ``make_id``
|
||||
later collapses the separators to underscores. Using every segment — not just
|
||||
the immediate parent dir (#1504) — means same-named files in different
|
||||
directories get distinct IDs instead of colliding into one
|
||||
last-writer-wins node:
|
||||
|
||||
docs/v1/api/README.md -> docs/v1/api/README -> docs_v1_api_readme
|
||||
docs/v2/api/README.md -> docs/v2/api/README -> docs_v2_api_readme
|
||||
|
||||
Top-level files keep a bare stem (``setup.py`` -> ``setup``). When passed an
|
||||
absolute path the whole path is encoded; the extract() id-remap post-pass
|
||||
re-derives the canonical repo-relative form from ``source_file`` so the on-disk
|
||||
location can't leak into the persisted IDs (#502)."""
|
||||
return path.with_suffix("").as_posix()
|
||||
|
||||
|
||||
def _read_text(node, source: bytes) -> str:
|
||||
return source[node.start_byte:node.end_byte].decode("utf-8", errors="replace")
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Laravel Blade template extractor. Moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from graphify.extractors.base import _make_id
|
||||
|
||||
|
||||
def extract_blade(path: Path) -> dict:
|
||||
"""Extract @include, <livewire:> components, and wire:click bindings from Blade templates."""
|
||||
import re
|
||||
try:
|
||||
src = path.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
return {"error": f"cannot read {path}"}
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
nodes = [{"id": file_nid, "label": path.name, "file_type": "code",
|
||||
"source_file": str(path), "source_location": None}]
|
||||
edges = []
|
||||
|
||||
# @include('path.to.partial') or @include("path.to.partial")
|
||||
for m in re.finditer(r"@include\(['\"]([^'\"]+)['\"]", src):
|
||||
tgt = m.group(1).replace(".", "/")
|
||||
tgt_nid = _make_id(tgt)
|
||||
if tgt_nid not in {n["id"] for n in nodes}:
|
||||
nodes.append({"id": tgt_nid, "label": m.group(1), "file_type": "code",
|
||||
"source_file": str(path), "source_location": None})
|
||||
edges.append({"source": file_nid, "target": tgt_nid, "relation": "includes",
|
||||
"confidence": "EXTRACTED", "confidence_score": 1.0,
|
||||
"source_file": str(path), "source_location": None, "weight": 1.0})
|
||||
|
||||
# <livewire:component.name /> or <livewire:component.name>
|
||||
for m in re.finditer(r"<livewire:([\w.\-]+)", src):
|
||||
tgt_nid = _make_id(m.group(1))
|
||||
if tgt_nid not in {n["id"] for n in nodes}:
|
||||
nodes.append({"id": tgt_nid, "label": m.group(1), "file_type": "code",
|
||||
"source_file": str(path), "source_location": None})
|
||||
edges.append({"source": file_nid, "target": tgt_nid, "relation": "uses_component",
|
||||
"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))
|
||||
if tgt_nid not in {n["id"] for n in nodes}:
|
||||
nodes.append({"id": tgt_nid, "label": m.group(1), "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,
|
||||
"source_file": str(path), "source_location": None, "weight": 1.0})
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
@@ -0,0 +1,393 @@
|
||||
"""C# cross-file resolution.
|
||||
|
||||
The config-driven C# *extractor* (``extract_csharp`` → ``_extract_generic``)
|
||||
still lives in ``graphify/extract.py``; per ``extractors/MIGRATION.md`` the
|
||||
config-driven languages cannot be ported one-by-one until the shared
|
||||
``_extract_generic`` core moves as its own coordinated batch. This module is
|
||||
the C# home for the parts that *are* cleanly separable — today, the cross-file
|
||||
type-reference resolver below — and is where ``extract_csharp`` will land when
|
||||
the core migration happens.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
from pathlib import Path
|
||||
|
||||
from graphify.extractors.base import _make_id
|
||||
|
||||
|
||||
def _build_csharp_type_def_index(all_nodes: list[dict]) -> dict[tuple[str, str], str]:
|
||||
"""Return deterministic ``(namespace, name) -> node_id`` C# type definitions."""
|
||||
candidates: dict[tuple[str, str], list[dict]] = {}
|
||||
for node in all_nodes:
|
||||
if node.get("type") == "namespace":
|
||||
continue
|
||||
metadata = node.get("metadata") or {}
|
||||
if not isinstance(metadata, dict):
|
||||
metadata = {}
|
||||
if metadata.get("is_nested_type"):
|
||||
continue
|
||||
nid = node.get("id")
|
||||
label = node.get("label")
|
||||
if not (isinstance(nid, str) and nid and isinstance(label, str) and label):
|
||||
continue
|
||||
source_file = node.get("source_file")
|
||||
if (
|
||||
not isinstance(source_file, str)
|
||||
or not source_file.endswith(".cs")
|
||||
or node.get("file_type") != "code"
|
||||
):
|
||||
continue
|
||||
if label.endswith(")") or label.startswith(".") or "." in label:
|
||||
continue
|
||||
namespace = metadata.get("namespace", "")
|
||||
if not isinstance(namespace, str):
|
||||
namespace = ""
|
||||
candidates.setdefault((namespace, label), []).append(node)
|
||||
|
||||
return {
|
||||
key: sorted(
|
||||
nodes,
|
||||
key=lambda node: (
|
||||
str(node.get("source_file") or ""),
|
||||
str(node.get("source_location") or ""),
|
||||
str(node.get("id") or ""),
|
||||
),
|
||||
)[0]["id"]
|
||||
for key, nodes in candidates.items()
|
||||
}
|
||||
|
||||
|
||||
def _strip_trailing_csharp_generic_args(target_fqn: str) -> str:
|
||||
target_fqn = target_fqn.strip()
|
||||
if not target_fqn.endswith(">"):
|
||||
return target_fqn
|
||||
depth = 0
|
||||
for index in range(len(target_fqn) - 1, -1, -1):
|
||||
char = target_fqn[index]
|
||||
if char == ">":
|
||||
depth += 1
|
||||
elif char == "<":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return target_fqn[:index].strip()
|
||||
return target_fqn
|
||||
|
||||
|
||||
def _resolve_cross_file_csharp_imports(
|
||||
per_file: list[dict],
|
||||
paths: list[Path],
|
||||
all_nodes: list[dict],
|
||||
all_edges: list[dict],
|
||||
) -> None:
|
||||
"""Re-point resolvable C# ``using`` import edges to canonical internal nodes.
|
||||
|
||||
Namespace imports resolve only to canonical C# namespace nodes. Alias imports
|
||||
resolve only when the alias target's prefix is a known canonical namespace and
|
||||
the simple type name exists in the shared C# type-definition index. ``using
|
||||
static`` and nested type aliases remain deliberate gaps because they need
|
||||
member/nested-type modeling beyond this import pass.
|
||||
"""
|
||||
_ = (per_file, paths)
|
||||
namespace_id_by_label: dict[str, str] = {}
|
||||
for node in sorted(
|
||||
all_nodes,
|
||||
key=lambda node: (
|
||||
str(node.get("source_file") or ""),
|
||||
str(node.get("source_location") or ""),
|
||||
str(node.get("id") or ""),
|
||||
),
|
||||
):
|
||||
if node.get("type") != "namespace":
|
||||
continue
|
||||
label = node.get("label")
|
||||
nid = node.get("id")
|
||||
if isinstance(label, str) and label and isinstance(nid, str) and nid:
|
||||
namespace_id_by_label.setdefault(label, nid)
|
||||
|
||||
type_def_index = _build_csharp_type_def_index(all_nodes)
|
||||
if not namespace_id_by_label and not type_def_index:
|
||||
return
|
||||
|
||||
repointed_from: set[str] = set()
|
||||
for edge in all_edges:
|
||||
if edge.get("relation") != "imports":
|
||||
continue
|
||||
metadata = edge.get("metadata") or {}
|
||||
if not isinstance(metadata, dict):
|
||||
continue
|
||||
using_kind = metadata.get("using_kind")
|
||||
target_fqn = metadata.get("target_fqn")
|
||||
if not using_kind or not isinstance(target_fqn, str) or not target_fqn:
|
||||
continue
|
||||
|
||||
resolved = None
|
||||
if using_kind == "namespace":
|
||||
resolved = namespace_id_by_label.get(target_fqn)
|
||||
elif using_kind == "alias":
|
||||
base_fqn = _strip_trailing_csharp_generic_args(html.unescape(target_fqn))
|
||||
prefix, sep, name = base_fqn.rpartition(".")
|
||||
if sep and prefix in namespace_id_by_label:
|
||||
resolved = type_def_index.get((prefix, name))
|
||||
|
||||
old_target = edge.get("target")
|
||||
if resolved and resolved != old_target:
|
||||
edge["target"] = resolved
|
||||
if isinstance(old_target, str) and old_target:
|
||||
repointed_from.add(old_target)
|
||||
|
||||
if not repointed_from:
|
||||
return
|
||||
|
||||
still_referenced: set[str] = set()
|
||||
for edge in all_edges:
|
||||
still_referenced.add(edge.get("source"))
|
||||
still_referenced.add(edge.get("target"))
|
||||
all_nodes[:] = [
|
||||
node for node in all_nodes
|
||||
if node.get("id") not in repointed_from or node.get("id") in still_referenced
|
||||
]
|
||||
|
||||
|
||||
def _resolve_csharp_type_references(
|
||||
per_file: list[dict],
|
||||
paths: list[Path],
|
||||
all_nodes: list[dict],
|
||||
all_edges: list[dict],
|
||||
) -> None:
|
||||
"""Arbitrate all C# ``inherits``/``implements``/``references`` targets.
|
||||
|
||||
The extractor emits provisional same-file bindings and sourceless stubs. This
|
||||
pass is the single soundness gate: it uses only graph-stamped namespace/import
|
||||
facts, keeps a binding only when the referenced simple name resolves to one
|
||||
in-scope real type definition, and otherwise leaves the edge on a dangling stub.
|
||||
"""
|
||||
_ = (per_file, paths)
|
||||
|
||||
def _is_cs_file(value: object) -> bool:
|
||||
return isinstance(value, str) and value.endswith(".cs")
|
||||
|
||||
def _metadata(value: object) -> dict:
|
||||
return value if isinstance(value, dict) else {}
|
||||
|
||||
def _namespace(node: dict | None) -> str:
|
||||
metadata = _metadata((node or {}).get("metadata"))
|
||||
namespace = metadata.get("namespace", "")
|
||||
return namespace if isinstance(namespace, str) else ""
|
||||
|
||||
def _append_unique(items: list[str], value: str) -> None:
|
||||
if value not in items:
|
||||
items.append(value)
|
||||
|
||||
node_by_id = {
|
||||
node["id"]: node
|
||||
for node in all_nodes
|
||||
if isinstance(node.get("id"), str) and node.get("id")
|
||||
}
|
||||
type_def_index = _build_csharp_type_def_index(all_nodes)
|
||||
known_namespaces = {
|
||||
node.get("label")
|
||||
for node in all_nodes
|
||||
if node.get("type") == "namespace" and isinstance(node.get("label"), str)
|
||||
}
|
||||
|
||||
# Each using carries its lexical scope: ("file", None) applies file-wide;
|
||||
# ("namespace", scope_id) applies only where scope_id is in the ref's scope_chain.
|
||||
namespace_usings_by_file: dict[str, list[tuple[str, str, str | None]]] = {}
|
||||
aliases_by_file: dict[str, dict[str, list[tuple[str, str, str | None]]]] = {}
|
||||
|
||||
for edge in all_edges:
|
||||
if edge.get("relation") != "imports":
|
||||
continue
|
||||
source_node = node_by_id.get(edge.get("source"))
|
||||
if not (
|
||||
source_node
|
||||
and isinstance(source_node.get("label"), str)
|
||||
and source_node.get("label", "").endswith(".cs")
|
||||
):
|
||||
continue
|
||||
source_file = source_node.get("source_file")
|
||||
if not _is_cs_file(source_file):
|
||||
continue
|
||||
metadata = _metadata(edge.get("metadata"))
|
||||
target_fqn = metadata.get("target_fqn")
|
||||
if not isinstance(target_fqn, str) or not target_fqn:
|
||||
continue
|
||||
scope_kind = metadata.get("scope_kind") or "file"
|
||||
scope_id = metadata.get("scope_id")
|
||||
using_kind = metadata.get("using_kind")
|
||||
if using_kind == "namespace":
|
||||
entry = (target_fqn, scope_kind, scope_id)
|
||||
bucket = namespace_usings_by_file.setdefault(source_file, [])
|
||||
if entry not in bucket:
|
||||
bucket.append(entry)
|
||||
elif using_kind == "alias":
|
||||
alias = metadata.get("alias")
|
||||
if isinstance(alias, str) and alias:
|
||||
entry = (target_fqn, scope_kind, scope_id)
|
||||
bucket = aliases_by_file.setdefault(source_file, {}).setdefault(alias, [])
|
||||
if entry not in bucket:
|
||||
bucket.append(entry)
|
||||
|
||||
def _scope_chain(node: dict) -> list[str]:
|
||||
chain = _metadata(node.get("metadata")).get("scope_chain")
|
||||
return chain if isinstance(chain, list) else []
|
||||
|
||||
def _using_in_scope(scope_kind: str, scope_id: str | None, source_node: dict) -> bool:
|
||||
if scope_kind == "file":
|
||||
return True
|
||||
return scope_id is not None and scope_id in _scope_chain(source_node)
|
||||
|
||||
def _scopes_for(source_node: dict, source_file: str) -> list[str]:
|
||||
scopes: list[str] = []
|
||||
_append_unique(scopes, _namespace(source_node))
|
||||
_append_unique(scopes, "")
|
||||
for namespace, scope_kind, scope_id in namespace_usings_by_file.get(source_file, []):
|
||||
if _using_in_scope(scope_kind, scope_id, source_node):
|
||||
_append_unique(scopes, namespace)
|
||||
return scopes
|
||||
|
||||
def _resolve_alias(label: str, source_node: dict, source_file: str) -> str | None:
|
||||
hits = set()
|
||||
for target_fqn, scope_kind, scope_id in aliases_by_file.get(source_file, {}).get(label, []):
|
||||
if not _using_in_scope(scope_kind, scope_id, source_node):
|
||||
continue
|
||||
base_fqn = _strip_trailing_csharp_generic_args(html.unescape(target_fqn))
|
||||
namespace, sep, simple_name = base_fqn.rpartition(".")
|
||||
if not sep:
|
||||
simple_name = namespace
|
||||
namespace = ""
|
||||
if not simple_name:
|
||||
continue
|
||||
hit = type_def_index.get((namespace, simple_name))
|
||||
if hit:
|
||||
hits.add(hit)
|
||||
return next(iter(hits)) if len(hits) == 1 else None
|
||||
|
||||
def _resolve_label(label: str, source_node: dict, source_file: str) -> str | None:
|
||||
if label in aliases_by_file.get(source_file, {}):
|
||||
return _resolve_alias(label, source_node, source_file)
|
||||
candidates: list[str] = []
|
||||
for namespace in _scopes_for(source_node, source_file):
|
||||
hit = type_def_index.get((namespace, label))
|
||||
if hit and hit not in candidates:
|
||||
candidates.append(hit)
|
||||
return candidates[0] if len(candidates) == 1 else None
|
||||
|
||||
def _resolve_qualified(label: str, qualifier: object, source_node: dict, source_file: str) -> str | None:
|
||||
# Sound qualified resolution: an in-scope alias for Q shadows the namespace Q. For a qualified
|
||||
# ref Q.label, look up (alias_target_namespace, label). If no in-scope alias, fall through to an
|
||||
# exact known namespace. Dangle on ambiguity / no hit / unknown qualifier.
|
||||
if not isinstance(qualifier, str) or not qualifier:
|
||||
return None
|
||||
in_scope = [
|
||||
entry for entry in aliases_by_file.get(source_file, {}).get(qualifier, [])
|
||||
if _using_in_scope(entry[1], entry[2], source_node)
|
||||
]
|
||||
if in_scope:
|
||||
hits = set()
|
||||
for target_fqn, _scope_kind, _scope_id in in_scope:
|
||||
alias_ns = _strip_trailing_csharp_generic_args(html.unescape(target_fqn))
|
||||
hit = type_def_index.get((alias_ns, label))
|
||||
if hit:
|
||||
hits.add(hit)
|
||||
return next(iter(hits)) if len(hits) == 1 else None
|
||||
if qualifier in known_namespaces:
|
||||
return type_def_index.get((qualifier, label))
|
||||
return None
|
||||
|
||||
def _is_placeholder(node: dict | None) -> bool:
|
||||
return bool(node) and not node.get("source_file")
|
||||
|
||||
def _is_csharp_relevant_target(node: dict) -> bool:
|
||||
if node.get("type") == "namespace":
|
||||
return True
|
||||
source_file = node.get("source_file")
|
||||
return not source_file or _is_cs_file(source_file)
|
||||
|
||||
def _label_for_type_ref_target(target_node: dict, source_file: str) -> str | None:
|
||||
label = target_node.get("label")
|
||||
if not isinstance(label, str) or not label:
|
||||
return None
|
||||
if not label.endswith(".cs"):
|
||||
return label
|
||||
|
||||
stem = label[:-3]
|
||||
for alias in aliases_by_file.get(source_file, {}):
|
||||
if alias.lower() == stem.lower() or _make_id(alias) == _make_id(stem):
|
||||
return alias
|
||||
return stem or None
|
||||
|
||||
def _dangling_stub_id(label: str, current_target: object) -> str:
|
||||
current = node_by_id.get(current_target)
|
||||
if _is_placeholder(current) and current.get("label") == label:
|
||||
return str(current_target)
|
||||
|
||||
for node in all_nodes:
|
||||
nid = node.get("id")
|
||||
if (
|
||||
isinstance(nid, str)
|
||||
and node.get("label") == label
|
||||
and _is_placeholder(node)
|
||||
):
|
||||
return nid
|
||||
|
||||
stem = _make_id(label)
|
||||
stub_id = stem
|
||||
if stub_id in node_by_id:
|
||||
stub_id = _make_id("csharp_type_ref", label)
|
||||
suffix = 2
|
||||
while stub_id in node_by_id:
|
||||
stub_id = _make_id("csharp_type_ref", label, str(suffix))
|
||||
suffix += 1
|
||||
node = {
|
||||
"id": stub_id,
|
||||
"label": label,
|
||||
"file_type": "code",
|
||||
"source_file": "",
|
||||
"source_location": "",
|
||||
}
|
||||
all_nodes.append(node)
|
||||
node_by_id[stub_id] = node
|
||||
return stub_id
|
||||
|
||||
REPOINT_RELATIONS = {"implements", "inherits", "references"}
|
||||
repointed_from: set[str] = set()
|
||||
for edge in all_edges:
|
||||
if edge.get("relation") not in REPOINT_RELATIONS:
|
||||
continue
|
||||
source_file = edge.get("source_file")
|
||||
if not _is_cs_file(source_file):
|
||||
continue
|
||||
source_node = node_by_id.get(edge.get("source"))
|
||||
target_node = node_by_id.get(edge.get("target"))
|
||||
if not source_node or not target_node:
|
||||
continue
|
||||
if not _is_csharp_relevant_target(target_node):
|
||||
continue
|
||||
metadata = _metadata(edge.get("metadata"))
|
||||
label = metadata.get("ref_token") or _label_for_type_ref_target(target_node, source_file)
|
||||
if not label:
|
||||
continue
|
||||
if metadata.get("qualified"):
|
||||
resolved = _resolve_qualified(label, metadata.get("ref_qualifier"), source_node, source_file)
|
||||
else:
|
||||
resolved = _resolve_label(label, source_node, source_file)
|
||||
target = edge.get("target")
|
||||
desired = resolved or _dangling_stub_id(label, target)
|
||||
if desired != target:
|
||||
edge["target"] = desired
|
||||
if isinstance(target, str) and _is_placeholder(target_node):
|
||||
repointed_from.add(target)
|
||||
|
||||
if not repointed_from:
|
||||
return
|
||||
|
||||
still_referenced: set[str] = set()
|
||||
for edge in all_edges:
|
||||
still_referenced.add(edge.get("source"))
|
||||
still_referenced.add(edge.get("target"))
|
||||
all_nodes[:] = [
|
||||
node for node in all_nodes
|
||||
if node.get("id") not in repointed_from or node.get("id") in still_referenced
|
||||
]
|
||||
@@ -0,0 +1,228 @@
|
||||
"""Elixir extractor. Moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from graphify.extractors.base import _LANGUAGE_BUILTIN_GLOBALS, _file_stem, _make_id
|
||||
|
||||
|
||||
def extract_elixir(path: Path) -> dict:
|
||||
"""Extract modules, functions, imports, and calls from a .ex/.exs file."""
|
||||
try:
|
||||
import tree_sitter_elixir as tselixir
|
||||
from tree_sitter import Language, Parser
|
||||
except ImportError:
|
||||
return {"nodes": [], "edges": [], "error": "tree_sitter_elixir not installed"}
|
||||
|
||||
try:
|
||||
language = Language(tselixir.language())
|
||||
parser = Parser(language)
|
||||
source = path.read_bytes()
|
||||
tree = parser.parse(source)
|
||||
root = tree.root_node
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
function_bodies: list[tuple[str, Any]] = []
|
||||
|
||||
def add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({"id": nid, "label": label, "file_type": "code",
|
||||
"source_file": str_path, "source_location": f"L{line}"})
|
||||
|
||||
def add_edge(src: str, tgt: str, relation: str, line: int,
|
||||
confidence: str = "EXTRACTED", weight: float = 1.0,
|
||||
context: str | None = None) -> None:
|
||||
edge = {"source": src, "target": tgt, "relation": relation,
|
||||
"confidence": confidence, "source_file": str_path,
|
||||
"source_location": f"L{line}", "weight": weight}
|
||||
if context:
|
||||
edge["context"] = context
|
||||
edges.append(edge)
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
add_node(file_nid, path.name, 1)
|
||||
|
||||
_IMPORT_KEYWORDS = frozenset({"alias", "import", "require", "use"})
|
||||
|
||||
def _get_alias_text(node) -> str | None:
|
||||
for child in node.children:
|
||||
if child.type == "alias":
|
||||
return source[child.start_byte:child.end_byte].decode("utf-8", errors="replace")
|
||||
return None
|
||||
|
||||
def _get_alias_modules(node) -> list[str]:
|
||||
"""Every module named by an alias/import/require/use argument.
|
||||
|
||||
Handles the single form (``alias Foo.Bar`` -> ``["Foo.Bar"]``) and the
|
||||
multi-alias brace form (``alias Foo.{Bar, Baz}`` ->
|
||||
``["Foo.Bar", "Foo.Baz"]``), which the grammar represents as a ``dot``
|
||||
node holding the base alias and a trailing ``tuple`` of member aliases.
|
||||
"""
|
||||
def _text(n) -> str:
|
||||
return source[n.start_byte:n.end_byte].decode("utf-8", errors="replace")
|
||||
|
||||
for child in node.children:
|
||||
if child.type == "alias":
|
||||
return [_text(child)]
|
||||
if child.type == "dot":
|
||||
base = None
|
||||
tuple_node = None
|
||||
for sub in child.children:
|
||||
if sub.type == "alias" and base is None:
|
||||
base = _text(sub)
|
||||
elif sub.type == "tuple":
|
||||
tuple_node = sub
|
||||
if base and tuple_node is not None:
|
||||
members = [_text(m) for m in tuple_node.children if m.type == "alias"]
|
||||
if members:
|
||||
return [f"{base}.{m}" for m in members]
|
||||
return [_text(child)]
|
||||
return []
|
||||
|
||||
def walk(node, parent_module_nid: str | None = None) -> None:
|
||||
if node.type != "call":
|
||||
for child in node.children:
|
||||
walk(child, parent_module_nid)
|
||||
return
|
||||
|
||||
identifier_node = None
|
||||
arguments_node = None
|
||||
do_block_node = None
|
||||
for child in node.children:
|
||||
if child.type == "identifier":
|
||||
identifier_node = child
|
||||
elif child.type == "arguments":
|
||||
arguments_node = child
|
||||
elif child.type == "do_block":
|
||||
do_block_node = child
|
||||
|
||||
if identifier_node is None:
|
||||
for child in node.children:
|
||||
walk(child, parent_module_nid)
|
||||
return
|
||||
|
||||
keyword = source[identifier_node.start_byte:identifier_node.end_byte].decode("utf-8", errors="replace")
|
||||
line = node.start_point[0] + 1
|
||||
|
||||
if keyword == "defmodule":
|
||||
module_name = _get_alias_text(arguments_node) if arguments_node else None
|
||||
if not module_name:
|
||||
return
|
||||
module_nid = _make_id(stem, module_name)
|
||||
add_node(module_nid, module_name, line)
|
||||
add_edge(file_nid, module_nid, "contains", line)
|
||||
if do_block_node:
|
||||
for child in do_block_node.children:
|
||||
walk(child, parent_module_nid=module_nid)
|
||||
return
|
||||
|
||||
if keyword in ("def", "defp"):
|
||||
func_name = None
|
||||
if arguments_node:
|
||||
for child in arguments_node.children:
|
||||
if child.type == "call":
|
||||
for sub in child.children:
|
||||
if sub.type == "identifier":
|
||||
func_name = source[sub.start_byte:sub.end_byte].decode("utf-8", errors="replace")
|
||||
break
|
||||
elif child.type == "identifier":
|
||||
func_name = source[child.start_byte:child.end_byte].decode("utf-8", errors="replace")
|
||||
break
|
||||
if not func_name:
|
||||
return
|
||||
container = parent_module_nid or file_nid
|
||||
func_nid = _make_id(container, func_name)
|
||||
add_node(func_nid, f"{func_name}()", line)
|
||||
if parent_module_nid:
|
||||
add_edge(parent_module_nid, func_nid, "method", line)
|
||||
else:
|
||||
add_edge(file_nid, func_nid, "contains", line)
|
||||
if do_block_node:
|
||||
function_bodies.append((func_nid, do_block_node))
|
||||
return
|
||||
|
||||
if keyword in _IMPORT_KEYWORDS and arguments_node:
|
||||
for module_name in _get_alias_modules(arguments_node):
|
||||
tgt_nid = _make_id(module_name)
|
||||
add_edge(file_nid, tgt_nid, "imports", line, context="import")
|
||||
return
|
||||
|
||||
for child in node.children:
|
||||
walk(child, parent_module_nid)
|
||||
|
||||
walk(root)
|
||||
|
||||
label_to_nid: dict[str, str] = {}
|
||||
for n in nodes:
|
||||
normalised = n["label"].strip("()").lstrip(".")
|
||||
label_to_nid[normalised] = n["id"]
|
||||
|
||||
seen_call_pairs: set[tuple[str, str]] = set()
|
||||
raw_calls: list[dict] = []
|
||||
_SKIP_KEYWORDS = frozenset({
|
||||
"def", "defp", "defmodule", "defmacro", "defmacrop",
|
||||
"defstruct", "defprotocol", "defimpl", "defguard",
|
||||
"alias", "import", "require", "use",
|
||||
"if", "unless", "case", "cond", "with", "for",
|
||||
})
|
||||
|
||||
def walk_calls(node, caller_nid: str) -> None:
|
||||
if node.type != "call":
|
||||
for child in node.children:
|
||||
walk_calls(child, caller_nid)
|
||||
return
|
||||
for child in node.children:
|
||||
if child.type == "identifier":
|
||||
kw = source[child.start_byte:child.end_byte].decode("utf-8", errors="replace")
|
||||
if kw in _SKIP_KEYWORDS:
|
||||
for c in node.children:
|
||||
walk_calls(c, caller_nid)
|
||||
return
|
||||
break
|
||||
callee_name: str | None = None
|
||||
is_member_call: bool = False
|
||||
for child in node.children:
|
||||
if child.type == "dot":
|
||||
is_member_call = True
|
||||
dot_text = source[child.start_byte:child.end_byte].decode("utf-8", errors="replace")
|
||||
parts = dot_text.rstrip(".").split(".")
|
||||
if parts:
|
||||
callee_name = parts[-1]
|
||||
break
|
||||
if child.type == "identifier":
|
||||
callee_name = source[child.start_byte:child.end_byte].decode("utf-8", errors="replace")
|
||||
break
|
||||
if callee_name and callee_name not in _LANGUAGE_BUILTIN_GLOBALS:
|
||||
tgt_nid = 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:
|
||||
seen_call_pairs.add(pair)
|
||||
add_edge(caller_nid, tgt_nid, "calls",
|
||||
node.start_point[0] + 1, confidence="EXTRACTED", weight=1.0,
|
||||
context="call")
|
||||
else:
|
||||
raw_calls.append({
|
||||
"caller_nid": caller_nid,
|
||||
"callee": callee_name,
|
||||
"is_member_call": is_member_call,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
})
|
||||
for child in node.children:
|
||||
walk_calls(child, caller_nid)
|
||||
|
||||
for caller_nid, body in function_bodies:
|
||||
walk_calls(body, caller_nid)
|
||||
|
||||
clean_edges = [e for e in edges if e["source"] in seen_ids and
|
||||
(e["target"] in seen_ids or e["relation"] == "imports")]
|
||||
return {"nodes": nodes, "edges": clean_edges, "raw_calls": raw_calls, "input_tokens": 0, "output_tokens": 0}
|
||||
@@ -0,0 +1,119 @@
|
||||
"""ASP.NET Razor component extractor. Moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from graphify.extractors.base import _file_stem, _make_id
|
||||
|
||||
|
||||
def extract_razor(path: Path) -> dict:
|
||||
"""Extract directives, component refs, and @code methods from .razor/.cshtml."""
|
||||
try:
|
||||
src = path.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
return {"nodes": [], "edges": [], "error": f"cannot read {path}"}
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = [{"id": file_nid, "label": path.name, "file_type": "code",
|
||||
"source_file": str_path, "source_location": None}]
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
seen_ids.add(file_nid)
|
||||
|
||||
def _add_ref(target_name: str, relation: str, line: int) -> None:
|
||||
tgt_nid = _make_id(target_name)
|
||||
if not tgt_nid:
|
||||
return
|
||||
if tgt_nid not in seen_ids:
|
||||
seen_ids.add(tgt_nid)
|
||||
nodes.append({"id": tgt_nid, "label": target_name,
|
||||
"file_type": "code", "source_file": str_path,
|
||||
"source_location": f"L{line}"})
|
||||
edges.append({"source": file_nid, "target": tgt_nid,
|
||||
"relation": relation, "confidence": "EXTRACTED",
|
||||
"source_file": str_path, "source_location": f"L{line}",
|
||||
"weight": 1.0})
|
||||
|
||||
for i, line in enumerate(src.splitlines(), 1):
|
||||
m = re.match(r'@using\s+([\w.]+)', line)
|
||||
if m:
|
||||
_add_ref(m.group(1), "imports", i)
|
||||
continue
|
||||
|
||||
m = re.match(r'@inject\s+([\w.<>\[\]]+)\s+(\w+)', line)
|
||||
if m:
|
||||
_add_ref(m.group(1), "imports", i)
|
||||
continue
|
||||
|
||||
m = re.match(r'@inherits\s+([\w.<>\[\]]+)', line)
|
||||
if m:
|
||||
_add_ref(m.group(1), "inherits", i)
|
||||
continue
|
||||
|
||||
m = re.match(r'@model\s+([\w.<>\[\]]+)', line)
|
||||
if m:
|
||||
_add_ref(m.group(1), "references", i)
|
||||
continue
|
||||
|
||||
m = re.match(r'@page\s+"([^"]+)"', line)
|
||||
if m:
|
||||
route = m.group(1)
|
||||
route_nid = _make_id("route", route)
|
||||
if route_nid and route_nid not in seen_ids:
|
||||
seen_ids.add(route_nid)
|
||||
nodes.append({"id": route_nid, "label": f"route:{route}",
|
||||
"file_type": "concept", "source_file": str_path,
|
||||
"source_location": f"L{i}"})
|
||||
edges.append({"source": file_nid, "target": route_nid,
|
||||
"relation": "references", "confidence": "EXTRACTED",
|
||||
"source_file": str_path, "weight": 1.0})
|
||||
continue
|
||||
|
||||
_COMPONENT_RE = re.compile(r'<([A-Z][A-Za-z0-9]+)[\s/>]')
|
||||
_HTML_TAGS = frozenset({
|
||||
"DOCTYPE", "Html", "Head", "Body", "Div", "Span", "Table", "Form",
|
||||
"Input", "Button", "Select", "Option", "Label", "Textarea",
|
||||
"Script", "Style", "Link", "Meta", "Title", "Header", "Footer",
|
||||
"Nav", "Main", "Section", "Article", "Aside",
|
||||
})
|
||||
for m in _COMPONENT_RE.finditer(src):
|
||||
comp_name = m.group(1)
|
||||
if comp_name in _HTML_TAGS:
|
||||
continue
|
||||
line_num = src[:m.start()].count("\n") + 1
|
||||
_add_ref(comp_name, "calls", line_num)
|
||||
|
||||
_CODE_BLOCK_RE = re.compile(r'@code\s*\{', re.MULTILINE)
|
||||
for m in _CODE_BLOCK_RE.finditer(src):
|
||||
block_start = m.end()
|
||||
depth = 1
|
||||
pos = block_start
|
||||
while pos < len(src) and depth > 0:
|
||||
if src[pos] == '{':
|
||||
depth += 1
|
||||
elif src[pos] == '}':
|
||||
depth -= 1
|
||||
pos += 1
|
||||
code_block = src[block_start:pos - 1] if depth == 0 else ""
|
||||
|
||||
_METHOD_RE = re.compile(
|
||||
r'(?:public|private|protected|internal|static|async|override|virtual|abstract)\s+'
|
||||
r'[\w<>\[\],\s]+\s+(\w+)\s*\('
|
||||
)
|
||||
for mm in _METHOD_RE.finditer(code_block):
|
||||
method_name = mm.group(1)
|
||||
abs_pos = block_start + mm.start()
|
||||
method_line = src[:abs_pos].count("\n") + 1
|
||||
method_nid = _make_id(_file_stem(path), method_name)
|
||||
if method_nid and method_nid not in seen_ids:
|
||||
seen_ids.add(method_nid)
|
||||
nodes.append({"id": method_nid, "label": method_name,
|
||||
"file_type": "code", "source_file": str_path,
|
||||
"source_location": f"L{method_line}"})
|
||||
edges.append({"source": file_nid, "target": method_nid,
|
||||
"relation": "contains", "confidence": "EXTRACTED",
|
||||
"source_file": str_path, "weight": 1.0})
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
@@ -0,0 +1,175 @@
|
||||
"""Zig extractor (tree-sitter). Moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from graphify.extractors.base import _file_stem, _make_id, _read_text
|
||||
|
||||
|
||||
def extract_zig(path: Path) -> dict:
|
||||
"""Extract functions, structs, enums, unions, and imports from a .zig file."""
|
||||
try:
|
||||
import tree_sitter_zig as tszig
|
||||
from tree_sitter import Language, Parser
|
||||
except ImportError:
|
||||
return {"nodes": [], "edges": [], "error": "tree_sitter_zig not installed"}
|
||||
|
||||
try:
|
||||
language = Language(tszig.language())
|
||||
parser = Parser(language)
|
||||
source = path.read_bytes()
|
||||
tree = parser.parse(source)
|
||||
root = tree.root_node
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
function_bodies: list[tuple[str, Any]] = []
|
||||
|
||||
def add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({"id": nid, "label": label, "file_type": "code",
|
||||
"source_file": str_path, "source_location": f"L{line}"})
|
||||
|
||||
def add_edge(src: str, tgt: str, relation: str, line: int,
|
||||
confidence: str = "EXTRACTED", weight: float = 1.0,
|
||||
context: str | None = None) -> None:
|
||||
edge = {"source": src, "target": tgt, "relation": relation,
|
||||
"confidence": confidence, "source_file": str_path,
|
||||
"source_location": f"L{line}", "weight": weight}
|
||||
if context:
|
||||
edge["context"] = context
|
||||
edges.append(edge)
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
add_node(file_nid, path.name, 1)
|
||||
|
||||
def _extract_import(node) -> None:
|
||||
for child in node.children:
|
||||
if child.type == "builtin_function":
|
||||
bi = None
|
||||
args = None
|
||||
for c in child.children:
|
||||
if c.type == "builtin_identifier":
|
||||
bi = _read_text(c, source)
|
||||
elif c.type == "arguments":
|
||||
args = c
|
||||
if bi in ("@import", "@cImport") and args:
|
||||
for arg in args.children:
|
||||
if arg.type in ("string_literal", "string"):
|
||||
raw = _read_text(arg, source).strip('"')
|
||||
module_name = raw.split("/")[-1].split(".")[0]
|
||||
if module_name:
|
||||
tgt_nid = _make_id(module_name)
|
||||
add_edge(file_nid, tgt_nid, "imports_from",
|
||||
node.start_point[0] + 1)
|
||||
return
|
||||
elif child.type == "field_expression":
|
||||
_extract_import(child)
|
||||
return
|
||||
|
||||
def walk(node, parent_struct_nid: str | None = None) -> None:
|
||||
t = node.type
|
||||
|
||||
if t == "function_declaration":
|
||||
name_node = node.child_by_field_name("name")
|
||||
if name_node:
|
||||
func_name = _read_text(name_node, source)
|
||||
line = node.start_point[0] + 1
|
||||
if parent_struct_nid:
|
||||
func_nid = _make_id(parent_struct_nid, func_name)
|
||||
add_node(func_nid, f".{func_name}()", line)
|
||||
add_edge(parent_struct_nid, func_nid, "method", line)
|
||||
else:
|
||||
func_nid = _make_id(stem, func_name)
|
||||
add_node(func_nid, f"{func_name}()", line)
|
||||
add_edge(file_nid, func_nid, "contains", line)
|
||||
body = node.child_by_field_name("body")
|
||||
if body:
|
||||
function_bodies.append((func_nid, body))
|
||||
return
|
||||
|
||||
if t == "variable_declaration":
|
||||
name_node = None
|
||||
value_node = None
|
||||
for child in node.children:
|
||||
if child.type == "identifier":
|
||||
name_node = child
|
||||
elif child.type in ("struct_declaration", "enum_declaration",
|
||||
"union_declaration", "builtin_function",
|
||||
"field_expression"):
|
||||
value_node = child
|
||||
|
||||
if value_node and value_node.type == "struct_declaration":
|
||||
if name_node:
|
||||
struct_name = _read_text(name_node, source)
|
||||
line = node.start_point[0] + 1
|
||||
struct_nid = _make_id(stem, struct_name)
|
||||
add_node(struct_nid, struct_name, line)
|
||||
add_edge(file_nid, struct_nid, "contains", line)
|
||||
for child in value_node.children:
|
||||
walk(child, parent_struct_nid=struct_nid)
|
||||
return
|
||||
|
||||
if value_node and value_node.type in ("enum_declaration", "union_declaration"):
|
||||
if name_node:
|
||||
type_name = _read_text(name_node, source)
|
||||
line = node.start_point[0] + 1
|
||||
type_nid = _make_id(stem, type_name)
|
||||
add_node(type_nid, type_name, line)
|
||||
add_edge(file_nid, type_nid, "contains", line)
|
||||
return
|
||||
|
||||
if value_node and value_node.type in ("builtin_function", "field_expression"):
|
||||
_extract_import(node)
|
||||
return
|
||||
|
||||
for child in node.children:
|
||||
walk(child, parent_struct_nid)
|
||||
|
||||
walk(root)
|
||||
|
||||
seen_call_pairs: set[tuple[str, str]] = set()
|
||||
raw_calls: list[dict] = []
|
||||
|
||||
def walk_calls(node, caller_nid: str) -> None:
|
||||
if node.type == "function_declaration":
|
||||
return
|
||||
if node.type == "call_expression":
|
||||
fn = node.child_by_field_name("function")
|
||||
if fn:
|
||||
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)
|
||||
if tgt_nid and tgt_nid != caller_nid:
|
||||
pair = (caller_nid, tgt_nid)
|
||||
if pair not in seen_call_pairs:
|
||||
seen_call_pairs.add(pair)
|
||||
add_edge(caller_nid, tgt_nid, "calls",
|
||||
node.start_point[0] + 1,
|
||||
confidence="EXTRACTED", weight=1.0)
|
||||
elif callee:
|
||||
raw_calls.append({
|
||||
"caller_nid": caller_nid,
|
||||
"callee": callee,
|
||||
"is_member_call": is_member_call,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
})
|
||||
for child in node.children:
|
||||
walk_calls(child, caller_nid)
|
||||
|
||||
for caller_nid, body_node in function_bodies:
|
||||
walk_calls(body_node, caller_nid)
|
||||
|
||||
clean_edges = [e for e in edges if e["source"] in seen_ids and
|
||||
(e["target"] in seen_ids or e["relation"] == "imports_from")]
|
||||
return {"nodes": nodes, "edges": clean_edges, "raw_calls": raw_calls}
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Intra-file slicing for oversized text documents (#1369).
|
||||
|
||||
The extraction packer (`_pack_chunks_by_tokens`) treats each file as atomic and
|
||||
`_read_files` caps every file at ``_FILE_CHAR_CAP`` characters, so a document
|
||||
larger than that cap had everything past the cap silently dropped — the model
|
||||
never saw it, and nothing in the adaptive-retry path could recover it ("a single
|
||||
file larger than the budget ... packing can't shrink one big file").
|
||||
|
||||
This module splits an oversized *splittable text* document (Markdown, plain
|
||||
text, reStructuredText) into contiguous ``FileSlice`` units at heading /
|
||||
paragraph / line boundaries so the whole file gets extracted across several
|
||||
units. Every slice of a file reports the **parent file path** as its source, so
|
||||
the resulting nodes are never fragmented per-slice — they merge by source_file
|
||||
exactly as if the file had been extracted in one pass.
|
||||
|
||||
Only plain-text documents are sliced: code files need whole-symbol context, and
|
||||
PDFs/images are read through their own extractors and have no char-offset model.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
# Plain-text document types where boundary-based slicing is meaningful and where
|
||||
# `_file_to_text` is a straight ``read_text`` (so a char range matches the bytes
|
||||
# the model is shown). Deliberately excludes code (.py, .ts, ...) and binary
|
||||
# docs (.pdf) — those are never sliced.
|
||||
_SPLITTABLE_TEXT_SUFFIXES = frozenset({".md", ".mdx", ".markdown", ".txt", ".rst"})
|
||||
|
||||
# Boundary preferences, strongest first. A Markdown heading (``\n#``) keeps a
|
||||
# section with its title; a blank line keeps a paragraph intact; a bare newline
|
||||
# avoids cutting mid-line. If none is found in the window we hard-cut.
|
||||
_BOUNDARY_SEPARATORS = ("\n#", "\n\n", "\n")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FileSlice:
|
||||
"""A contiguous ``[start, end)`` character range of a splittable text file.
|
||||
|
||||
``index``/``total`` are for logging only. ``path`` is the real file on disk;
|
||||
the slice always reports ``path`` as its source so slices don't fragment the
|
||||
graph.
|
||||
"""
|
||||
|
||||
path: Path
|
||||
start: int
|
||||
end: int
|
||||
index: int
|
||||
total: int
|
||||
|
||||
|
||||
# A unit of extraction work: either a whole file (``Path``) or one slice of one.
|
||||
Unit = "Path | FileSlice"
|
||||
|
||||
|
||||
def unit_path(unit: "Path | FileSlice") -> Path:
|
||||
"""The on-disk path a unit belongs to (the parent file for a slice)."""
|
||||
return unit.path if isinstance(unit, FileSlice) else unit
|
||||
|
||||
|
||||
def is_splittable_text(path: Path) -> bool:
|
||||
"""True for plain-text document types that may be sliced."""
|
||||
return path.suffix.lower() in _SPLITTABLE_TEXT_SUFFIXES
|
||||
|
||||
|
||||
def _best_cut(text: str, start: int, end: int) -> int:
|
||||
"""Return a cut index in ``(start, end]`` at the strongest nearby boundary.
|
||||
|
||||
Searches the window ``text[start:end]`` for the latest heading, then blank
|
||||
line, then newline, and returns the index just *after* it (a heading cuts
|
||||
just *before* the ``#`` so the heading leads the next slice). Falls back to a
|
||||
hard cut at ``end`` when the window has no usable boundary, which still makes
|
||||
forward progress because ``end > start``.
|
||||
"""
|
||||
window = text[start:end]
|
||||
for sep in _BOUNDARY_SEPARATORS:
|
||||
idx = window.rfind(sep)
|
||||
if idx > 0: # a boundary strictly inside the window (non-empty prev slice)
|
||||
if sep == "\n#":
|
||||
return start + idx + 1 # keep the newline with the previous slice
|
||||
return start + idx + len(sep)
|
||||
return end
|
||||
|
||||
|
||||
def slice_boundaries(text: str, max_chars: int) -> list[tuple[int, int]]:
|
||||
"""Contiguous ``(start, end)`` ranges covering all of ``text``, each ≤ max_chars.
|
||||
|
||||
Ranges are gap-free and non-overlapping, so concatenating the slices
|
||||
reproduces ``text`` exactly — no content is dropped.
|
||||
"""
|
||||
n = len(text)
|
||||
if n <= max_chars:
|
||||
return [(0, n)]
|
||||
bounds: list[tuple[int, int]] = []
|
||||
pos = 0
|
||||
while pos < n:
|
||||
hard = min(pos + max_chars, n)
|
||||
end = _best_cut(text, pos, hard) if hard < n else n
|
||||
if end <= pos: # defensive: never stall
|
||||
end = hard
|
||||
bounds.append((pos, end))
|
||||
pos = end
|
||||
return bounds
|
||||
|
||||
|
||||
def expand_oversized_files(
|
||||
files: list[Path], max_chars: int
|
||||
) -> list["Path | FileSlice"]:
|
||||
"""Replace each oversized splittable-text file with a list of ``FileSlice``s.
|
||||
|
||||
Files at or below ``max_chars`` (and all non-splittable files) pass through
|
||||
unchanged as ``Path``, so behaviour is identical for everything that already
|
||||
fit. Unreadable files pass through untouched (the reader handles the error).
|
||||
"""
|
||||
out: list["Path | FileSlice"] = []
|
||||
for f in files:
|
||||
if not is_splittable_text(f):
|
||||
out.append(f)
|
||||
continue
|
||||
try:
|
||||
text = f.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
out.append(f)
|
||||
continue
|
||||
if len(text) <= max_chars:
|
||||
out.append(f)
|
||||
continue
|
||||
ranges = slice_boundaries(text, max_chars)
|
||||
total = len(ranges)
|
||||
for i, (s, e) in enumerate(ranges):
|
||||
out.append(FileSlice(path=f, start=s, end=e, index=i, total=total))
|
||||
return out
|
||||
|
||||
|
||||
def read_slice_text(fs: FileSlice) -> str:
|
||||
"""Read just this slice's characters from its parent file."""
|
||||
text = fs.path.read_text(encoding="utf-8", errors="replace")
|
||||
return text[fs.start:fs.end]
|
||||
|
||||
|
||||
def bisect_slice(fs: FileSlice) -> tuple[FileSlice, FileSlice] | None:
|
||||
"""Split a slice into two halves at a newline near its midpoint, or None.
|
||||
|
||||
Used by the adaptive-retry path when a single slice still overflows the
|
||||
model's output: halving it produces a smaller response. Returns None when the
|
||||
slice is already too small to split meaningfully.
|
||||
"""
|
||||
if fs.end - fs.start <= 1:
|
||||
return None
|
||||
try:
|
||||
text = fs.path.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
return None
|
||||
mid = (fs.start + fs.end) // 2
|
||||
nl = text.find("\n", mid, fs.end)
|
||||
cut = nl + 1 if (nl != -1 and fs.start < nl + 1 < fs.end) else mid
|
||||
if not (fs.start < cut < fs.end):
|
||||
return 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
|
||||
@@ -0,0 +1,182 @@
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import hashlib
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph as _jg
|
||||
|
||||
_GLOBAL_DIR = Path.home() / ".graphify"
|
||||
_GLOBAL_GRAPH = _GLOBAL_DIR / "global-graph.json"
|
||||
_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"))
|
||||
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
|
||||
# error so the user can recover or report it.
|
||||
backup = _GLOBAL_MANIFEST.with_suffix(
|
||||
_GLOBAL_MANIFEST.suffix + f".corrupt.{int(datetime.now(timezone.utc).timestamp())}"
|
||||
)
|
||||
try:
|
||||
_GLOBAL_MANIFEST.rename(backup)
|
||||
print(
|
||||
f"[graphify global] manifest at {_GLOBAL_MANIFEST} failed to parse ({exc}); "
|
||||
f"moved to {backup} and starting fresh. Restore from the backup if this was "
|
||||
f"unexpected.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
except Exception as rename_exc:
|
||||
print(
|
||||
f"[graphify global] manifest at {_GLOBAL_MANIFEST} failed to parse ({exc}) "
|
||||
f"and could not be backed up ({rename_exc}). Starting fresh.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return {"version": 1, "repos": {}}
|
||||
|
||||
|
||||
def _save_manifest(manifest: dict) -> None:
|
||||
_GLOBAL_DIR.mkdir(parents=True, exist_ok=True)
|
||||
_GLOBAL_MANIFEST.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
def _load_global_graph() -> nx.Graph:
|
||||
if _GLOBAL_GRAPH.exists():
|
||||
from graphify.security import check_graph_file_size_cap
|
||||
check_graph_file_size_cap(_GLOBAL_GRAPH)
|
||||
data = json.loads(_GLOBAL_GRAPH.read_text(encoding="utf-8"))
|
||||
if "links" not in data and "edges" in data:
|
||||
data = dict(data, links=data["edges"])
|
||||
try:
|
||||
return _jg.node_link_graph(data, edges="links")
|
||||
except TypeError:
|
||||
return _jg.node_link_graph(data)
|
||||
return nx.Graph()
|
||||
|
||||
|
||||
def _save_global_graph(G: nx.Graph) -> None:
|
||||
_GLOBAL_DIR.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
data = _jg.node_link_data(G, edges="links")
|
||||
except TypeError:
|
||||
data = _jg.node_link_data(G)
|
||||
_GLOBAL_GRAPH.write_text(json.dumps(data, indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
def _file_hash(path: Path) -> str:
|
||||
h = hashlib.sha256()
|
||||
h.update(path.read_bytes())
|
||||
return h.hexdigest()[:16]
|
||||
|
||||
|
||||
def global_add(source_path: Path, repo_tag: str) -> dict:
|
||||
"""Add or update a project graph in the global graph.
|
||||
|
||||
Returns a summary dict with keys: repo_tag, nodes_added, nodes_removed, skipped.
|
||||
Skipped=True means the source graph hasn't changed since last add.
|
||||
"""
|
||||
from graphify.build import prefix_graph_for_global, prune_repo_from_graph
|
||||
|
||||
if not source_path.exists():
|
||||
raise FileNotFoundError(f"graph not found: {source_path}")
|
||||
|
||||
manifest = _load_manifest()
|
||||
src_hash = _file_hash(source_path)
|
||||
|
||||
existing = manifest["repos"].get(repo_tag, {})
|
||||
existing_path = existing.get("source_path", "")
|
||||
if existing_path and existing_path != str(source_path.resolve()):
|
||||
print(
|
||||
f"[graphify global] warning: repo tag '{repo_tag}' previously pointed to "
|
||||
f"{existing_path!r}, now updating to {str(source_path.resolve())!r}. "
|
||||
f"Use --as <tag> to give it a different name.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
if existing.get("source_hash") == src_hash:
|
||||
return {"repo_tag": repo_tag, "nodes_added": 0, "nodes_removed": 0, "skipped": True}
|
||||
|
||||
# Load source graph
|
||||
from graphify.security import check_graph_file_size_cap
|
||||
check_graph_file_size_cap(source_path)
|
||||
data = json.loads(source_path.read_text(encoding="utf-8"))
|
||||
if "links" not in data and "edges" in data:
|
||||
data = dict(data, links=data["edges"])
|
||||
try:
|
||||
src_G = _jg.node_link_graph(data, edges="links")
|
||||
except TypeError:
|
||||
src_G = _jg.node_link_graph(data)
|
||||
|
||||
# Prefix IDs for cross-project isolation
|
||||
prefixed = prefix_graph_for_global(src_G, repo_tag)
|
||||
|
||||
# Load global graph and prune stale nodes for this repo
|
||||
G = _load_global_graph()
|
||||
removed = prune_repo_from_graph(G, repo_tag)
|
||||
|
||||
# Merge external-library nodes (no source_file) by label to avoid duplication
|
||||
external_labels = {
|
||||
d.get("label", ""): n
|
||||
for n, d in G.nodes(data=True)
|
||||
if not d.get("source_file") and d.get("label")
|
||||
}
|
||||
# Map each deduplicated external onto the existing global node so that
|
||||
# edges incident to it can be rewired instead of dropped.
|
||||
remap = {}
|
||||
for node, data in prefixed.nodes(data=True):
|
||||
if not data.get("source_file") and data.get("label") in external_labels:
|
||||
remap[node] = external_labels[data["label"]]
|
||||
|
||||
# Compose: add prefixed nodes (except deduplicated externals) into global graph
|
||||
for node, data in prefixed.nodes(data=True):
|
||||
if node not in remap:
|
||||
G.add_node(node, **data)
|
||||
for u, v, data in prefixed.edges(data=True):
|
||||
u = remap.get(u, u)
|
||||
v = remap.get(v, v)
|
||||
if u != v: # don't introduce self-loops via remapping
|
||||
G.add_edge(u, v, **data)
|
||||
|
||||
added = prefixed.number_of_nodes() - len(remap)
|
||||
_save_global_graph(G)
|
||||
|
||||
manifest["repos"][repo_tag] = {
|
||||
"added_at": datetime.now(timezone.utc).isoformat(),
|
||||
"source_path": str(source_path.resolve()),
|
||||
"node_count": added,
|
||||
"edge_count": prefixed.number_of_edges(),
|
||||
"source_hash": src_hash,
|
||||
}
|
||||
_save_manifest(manifest)
|
||||
|
||||
return {"repo_tag": repo_tag, "nodes_added": added, "nodes_removed": removed, "skipped": False}
|
||||
|
||||
|
||||
def global_remove(repo_tag: str) -> int:
|
||||
"""Remove all nodes for repo_tag from the global graph. Returns count removed."""
|
||||
from graphify.build import prune_repo_from_graph
|
||||
|
||||
manifest = _load_manifest()
|
||||
if repo_tag not in manifest["repos"]:
|
||||
raise KeyError(f"repo '{repo_tag}' not in global graph")
|
||||
|
||||
G = _load_global_graph()
|
||||
removed = prune_repo_from_graph(G, repo_tag)
|
||||
_save_global_graph(G)
|
||||
|
||||
del manifest["repos"][repo_tag]
|
||||
_save_manifest(manifest)
|
||||
return removed
|
||||
|
||||
|
||||
def global_list() -> dict:
|
||||
"""Return the manifest repos dict."""
|
||||
return _load_manifest().get("repos", {})
|
||||
|
||||
|
||||
def global_path() -> Path:
|
||||
return _GLOBAL_GRAPH
|
||||
@@ -0,0 +1,223 @@
|
||||
"""Optional Google Workspace shortcut export support.
|
||||
|
||||
Google Drive for desktop stores native Docs, Sheets, and Slides as small JSON
|
||||
shortcut files (.gdoc, .gsheet, .gslides). Those files are pointers, not the
|
||||
document content. This module exports them to Markdown sidecars via the
|
||||
googleworkspace CLI (`gws`) so Graphify can extract their actual contents.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import urllib.parse
|
||||
from pathlib import Path
|
||||
from typing import Callable, Any
|
||||
|
||||
|
||||
GOOGLE_WORKSPACE_EXTENSIONS = {".gdoc", ".gsheet", ".gslides"}
|
||||
|
||||
|
||||
def google_workspace_enabled(value: str | None = None) -> bool:
|
||||
"""Return True when Google Workspace shortcut export is enabled."""
|
||||
raw = value if value is not None else os.environ.get("GRAPHIFY_GOOGLE_WORKSPACE", "")
|
||||
return raw.strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def _safe_yaml_str(value: str) -> str:
|
||||
return value.replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ").replace("\r", " ")
|
||||
|
||||
|
||||
def _extract_file_id_from_url(url: str) -> str | None:
|
||||
"""Extract a Drive file ID from common Google Docs/Drive URL shapes."""
|
||||
if not url:
|
||||
return None
|
||||
parsed = urllib.parse.urlparse(url)
|
||||
query = urllib.parse.parse_qs(parsed.query)
|
||||
if query.get("id"):
|
||||
return query["id"][0]
|
||||
match = re.search(r"/(?:document|spreadsheets|presentation|file)/d/([^/?#]+)", parsed.path)
|
||||
if match:
|
||||
return match.group(1)
|
||||
return None
|
||||
|
||||
|
||||
def _extract_resource_key(url: str, data: dict[str, Any]) -> str | None:
|
||||
for key in ("resource_key", "resourceKey"):
|
||||
value = data.get(key)
|
||||
if value:
|
||||
return str(value)
|
||||
if not url:
|
||||
return None
|
||||
parsed = urllib.parse.urlparse(url)
|
||||
query = urllib.parse.parse_qs(parsed.query)
|
||||
if query.get("resourcekey"):
|
||||
return query["resourcekey"][0]
|
||||
return None
|
||||
|
||||
|
||||
def read_google_shortcut(path: Path) -> dict[str, str | None]:
|
||||
"""Read a .gdoc/.gsheet/.gslides shortcut and return export metadata."""
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except Exception as exc:
|
||||
raise RuntimeError(f"could not read Google Workspace shortcut {path}: {exc}") from exc
|
||||
|
||||
url = str(data.get("url") or "")
|
||||
file_id = (
|
||||
data.get("doc_id")
|
||||
or data.get("file_id")
|
||||
or data.get("fileId")
|
||||
or data.get("id")
|
||||
or _extract_file_id_from_url(url)
|
||||
)
|
||||
if not file_id:
|
||||
resource_id = str(data.get("resource_id") or "")
|
||||
if ":" in resource_id:
|
||||
file_id = resource_id.split(":", 1)[1]
|
||||
|
||||
if not file_id:
|
||||
raise RuntimeError(f"Google Workspace shortcut {path} does not include a Drive file ID")
|
||||
|
||||
return {
|
||||
"file_id": str(file_id),
|
||||
"url": url or None,
|
||||
"resource_key": _extract_resource_key(url, data),
|
||||
"account": str(data.get("email")) if data.get("email") else None,
|
||||
}
|
||||
|
||||
|
||||
def _run_gws_export(file_id: str, mime_type: str, output: Path, resource_key: str | None = None) -> None:
|
||||
exe = shutil.which("gws")
|
||||
if not exe:
|
||||
raise RuntimeError(
|
||||
"gws is required for Google Workspace export. Install it from "
|
||||
"https://github.com/googleworkspace/cli and run `gws auth login -s drive`."
|
||||
)
|
||||
|
||||
params: dict[str, str] = {"fileId": file_id, "mimeType": mime_type}
|
||||
# Drive resource keys are sent via X-Goog-Drive-Resource-Keys. The current
|
||||
# gws export command has no custom-header flag, so do not pass resourceKey
|
||||
# as an unsupported query parameter.
|
||||
_ = resource_key
|
||||
output = output.resolve()
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
timeout = int(os.environ.get("GRAPHIFY_GOOGLE_WORKSPACE_TIMEOUT", "120"))
|
||||
result = subprocess.run(
|
||||
[exe, "drive", "files", "export", "--params", json.dumps(params), "-o", output.name],
|
||||
capture_output=True,
|
||||
cwd=output.parent,
|
||||
text=True,
|
||||
timeout=timeout,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
stderr = (result.stderr or result.stdout or "").strip()
|
||||
if len(stderr) > 1200:
|
||||
stderr = stderr[:1200] + "..."
|
||||
raise RuntimeError(f"gws export failed for {file_id}: {stderr}")
|
||||
|
||||
|
||||
def _sidecar_path(path: Path, out_dir: Path) -> Path:
|
||||
name_hash = hashlib.sha256(str(path.resolve()).encode()).hexdigest()[:8]
|
||||
return out_dir / f"{path.stem}_{name_hash}.md"
|
||||
|
||||
|
||||
def _with_frontmatter(path: Path, shortcut: dict[str, str | None], body: str, exported_mime_type: str) -> str:
|
||||
source_url = shortcut.get("url") or ""
|
||||
account = shortcut.get("account") or ""
|
||||
account_line = ""
|
||||
if account:
|
||||
account_hash = hashlib.sha256(account.encode()).hexdigest()[:12]
|
||||
account_line = f'google_account_hash: "{account_hash}"\n'
|
||||
return (
|
||||
"---\n"
|
||||
f'source_file: "{_safe_yaml_str(str(path))}"\n'
|
||||
'source_type: "google_workspace"\n'
|
||||
f'google_file_id: "{_safe_yaml_str(shortcut["file_id"] or "")}"\n'
|
||||
f'google_export_mime_type: "{_safe_yaml_str(exported_mime_type)}"\n'
|
||||
f'source_url: "{_safe_yaml_str(source_url)}"\n'
|
||||
f"{account_line}"
|
||||
"---\n\n"
|
||||
f"<!-- converted from Google Workspace shortcut: {path.name} -->\n\n"
|
||||
f"{body.strip()}\n"
|
||||
)
|
||||
|
||||
|
||||
def convert_google_workspace_file(
|
||||
path: Path,
|
||||
out_dir: Path,
|
||||
*,
|
||||
xlsx_to_markdown: Callable[[Path], str] | None = None,
|
||||
) -> Path | None:
|
||||
"""Export a Google Workspace shortcut to a Markdown sidecar.
|
||||
|
||||
Returns the converted Markdown path, or None when conversion is unsupported
|
||||
or produced no readable content.
|
||||
"""
|
||||
ext = path.suffix.lower()
|
||||
if ext not in GOOGLE_WORKSPACE_EXTENSIONS:
|
||||
return None
|
||||
|
||||
shortcut = read_google_shortcut(path)
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
out_path = _sidecar_path(path, out_dir)
|
||||
|
||||
if ext == ".gdoc":
|
||||
with tempfile.NamedTemporaryFile("w+b", suffix=".md", delete=False, dir=out_dir) as tmp:
|
||||
tmp_path = Path(tmp.name)
|
||||
try:
|
||||
_run_gws_export(shortcut["file_id"] or "", "text/markdown", tmp_path, shortcut.get("resource_key"))
|
||||
body = tmp_path.read_text(encoding="utf-8", errors="replace")
|
||||
finally:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
if not body.strip():
|
||||
return None
|
||||
out_path.write_text(_with_frontmatter(path, shortcut, body, "text/markdown"), encoding="utf-8")
|
||||
return out_path
|
||||
|
||||
if ext == ".gslides":
|
||||
with tempfile.NamedTemporaryFile("w+b", suffix=".txt", delete=False, dir=out_dir) as tmp:
|
||||
tmp_path = Path(tmp.name)
|
||||
try:
|
||||
_run_gws_export(shortcut["file_id"] or "", "text/plain", tmp_path, shortcut.get("resource_key"))
|
||||
body = tmp_path.read_text(encoding="utf-8", errors="replace")
|
||||
finally:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
if not body.strip():
|
||||
return None
|
||||
out_path.write_text(_with_frontmatter(path, shortcut, body, "text/plain"), encoding="utf-8")
|
||||
return out_path
|
||||
|
||||
if ext == ".gsheet":
|
||||
if xlsx_to_markdown is None:
|
||||
raise RuntimeError("Google Sheets export requires the office extra: pip install graphifyy[office,google]")
|
||||
with tempfile.NamedTemporaryFile("w+b", suffix=".xlsx", delete=False, dir=out_dir) as tmp:
|
||||
tmp_path = Path(tmp.name)
|
||||
try:
|
||||
_run_gws_export(
|
||||
shortcut["file_id"] or "",
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
tmp_path,
|
||||
shortcut.get("resource_key"),
|
||||
)
|
||||
body = xlsx_to_markdown(tmp_path)
|
||||
finally:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
if not body.strip():
|
||||
return None
|
||||
out_path.write_text(
|
||||
_with_frontmatter(
|
||||
path,
|
||||
shortcut,
|
||||
body,
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return out_path
|
||||
|
||||
return None
|
||||
@@ -0,0 +1,548 @@
|
||||
# git hook integration - install/uninstall graphify post-commit and post-checkout hooks
|
||||
from __future__ import annotations
|
||||
import configparser
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_HOOK_MARKER = "# graphify-hook-start"
|
||||
_HOOK_MARKER_END = "# graphify-hook-end"
|
||||
_CHECKOUT_MARKER = "# graphify-checkout-hook-start"
|
||||
_CHECKOUT_MARKER_END = "# graphify-checkout-hook-end"
|
||||
|
||||
# __PINNED_PYTHON__ is replaced at install time with the absolute path of the
|
||||
# Python interpreter that ran `graphify hook install`. For uv-tool and pipx
|
||||
# installs the interpreter lives inside an isolated venv, so the launcher on
|
||||
# PATH is the only entry point — and GUI git clients / CI runners often have a
|
||||
# minimal PATH that omits ~/.local/bin. Pinning sys.executable at install time
|
||||
# makes the hook work regardless of PATH at git-trigger time.
|
||||
_PYTHON_DETECT = """\
|
||||
# Detect the correct Python interpreter (handles uv tool, pipx, venv, system installs).
|
||||
# _PINNED was recorded at hook-install time; tried first so the hook works even
|
||||
# when the graphify launcher is not on PATH (common in GUI clients and CI).
|
||||
#
|
||||
# Probes check availability with importlib.util.find_spec instead of importing
|
||||
# the package: a probe that imports graphify wholesale executes the full package
|
||||
# import (10s+ cold on machines with AV-scanned or large site-packages) and used
|
||||
# to run up to FOUR times synchronously, stalling every commit before the
|
||||
# detached launch even started. find_spec locates the package without executing
|
||||
# it, so each probe costs interpreter startup only. The detached rebuild still
|
||||
# fails loudly in the log if the package is broken under that interpreter.
|
||||
_GFY_PROBE="import importlib.util, sys; sys.exit(0 if importlib.util.find_spec('graphify') else 1)"
|
||||
GRAPHIFY_PYTHON=""
|
||||
_PINNED='__PINNED_PYTHON__'
|
||||
if [ -n "$_PINNED" ] && [ -x "$_PINNED" ] && "$_PINNED" -c "$_GFY_PROBE" 2>/dev/null; then
|
||||
GRAPHIFY_PYTHON="$_PINNED"
|
||||
fi
|
||||
# Second probe: read graphify-out/.graphify_python (written by the skill and
|
||||
# CLI; survives uv-tool reinstalls and is the same source the README documents).
|
||||
if [ -z "$GRAPHIFY_PYTHON" ]; then
|
||||
_GFY_PYTHON_FILE="graphify-out/.graphify_python"
|
||||
if [ -f "$_GFY_PYTHON_FILE" ]; then
|
||||
_FROM_FILE=$(cat "$_GFY_PYTHON_FILE" 2>/dev/null | tr -d '[:space:]')
|
||||
case "$_FROM_FILE" in
|
||||
*[!a-zA-Z0-9/_.@:\\-]*) _FROM_FILE="" ;; # allowlist (covers Windows paths)
|
||||
esac
|
||||
if [ -n "$_FROM_FILE" ] && [ -x "$_FROM_FILE" ] && "$_FROM_FILE" -c "$_GFY_PROBE" 2>/dev/null; then
|
||||
GRAPHIFY_PYTHON="$_FROM_FILE"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
# Third probe: resolve via the graphify launcher on PATH.
|
||||
if [ -z "$GRAPHIFY_PYTHON" ]; then
|
||||
GRAPHIFY_BIN=$(command -v graphify 2>/dev/null)
|
||||
if [ -n "$GRAPHIFY_BIN" ]; then
|
||||
# Windows pip layout: Scripts/graphify(.exe) sits beside ..\\python.exe
|
||||
# (or .\\python.exe inside a venv's Scripts dir). NOTE: command -v may
|
||||
# return the launcher path WITHOUT the .exe suffix, so this cannot key
|
||||
# on the extension.
|
||||
_GFY_BINDIR=$(dirname "$GRAPHIFY_BIN")
|
||||
if [ -x "$_GFY_BINDIR/../python.exe" ] && "$_GFY_BINDIR/../python.exe" -c "$_GFY_PROBE" 2>/dev/null; then
|
||||
GRAPHIFY_PYTHON="$_GFY_BINDIR/../python.exe"
|
||||
elif [ -x "$_GFY_BINDIR/python.exe" ] && "$_GFY_BINDIR/python.exe" -c "$_GFY_PROBE" 2>/dev/null; then
|
||||
GRAPHIFY_PYTHON="$_GFY_BINDIR/python.exe"
|
||||
fi
|
||||
fi
|
||||
if [ -z "$GRAPHIFY_PYTHON" ] && [ -n "$GRAPHIFY_BIN" ]; then
|
||||
# POSIX launcher: parse the shebang. head -c + tr strip NUL bytes first —
|
||||
# when the launcher is a Windows binary reached without its .exe suffix,
|
||||
# a raw `head -1` reads binary into the command substitution and the
|
||||
# shell warns about ignored null bytes on every commit.
|
||||
case "$GRAPHIFY_BIN" in
|
||||
*.exe) _SHEBANG="" ;;
|
||||
*) _SHEBANG=$(head -c 256 "$GRAPHIFY_BIN" 2>/dev/null | tr -d '\\000' | head -n 1 | sed 's/^#![[:space:]]*//') ;;
|
||||
esac
|
||||
case "$_SHEBANG" in
|
||||
*/env\\ *) GRAPHIFY_PYTHON="${_SHEBANG#*/env }" ;;
|
||||
*) GRAPHIFY_PYTHON="$_SHEBANG" ;;
|
||||
esac
|
||||
# Allowlist: only keep characters valid in a filesystem path to prevent
|
||||
# injection if the shebang contains shell metacharacters.
|
||||
case "$GRAPHIFY_PYTHON" in
|
||||
*[!a-zA-Z0-9/_.@-]*) GRAPHIFY_PYTHON="" ;;
|
||||
esac
|
||||
if [ -n "$GRAPHIFY_PYTHON" ] && ! "$GRAPHIFY_PYTHON" -c "$_GFY_PROBE" 2>/dev/null; then
|
||||
GRAPHIFY_PYTHON=""
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
# Last resort: try python3 / python (works for system/venv installs on PATH).
|
||||
if [ -z "$GRAPHIFY_PYTHON" ]; then
|
||||
if command -v python3 >/dev/null 2>&1 && python3 -c "$_GFY_PROBE" 2>/dev/null; then
|
||||
GRAPHIFY_PYTHON="python3"
|
||||
elif command -v python >/dev/null 2>&1 && python -c "$_GFY_PROBE" 2>/dev/null; then
|
||||
GRAPHIFY_PYTHON="python"
|
||||
else
|
||||
echo "[graphify hook] could not locate a Python with graphify installed. Add the graphify bin dir to PATH or re-run 'graphify hook install' from the env where graphify lives." >&2
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
"""
|
||||
|
||||
# The Python that the rebuild runs, shared by both hooks. Embedded verbatim into
|
||||
# the launcher below and re-executed in the detached child. Must not contain the
|
||||
# double-quote, $, backtick or backslash characters: it is carried inside a
|
||||
# shell double-quoted `-c "..."` argument (see _detached_launch).
|
||||
_REBUILD_BODY_COMMIT = """\
|
||||
import os, signal, sys
|
||||
from pathlib import Path
|
||||
|
||||
changed_raw = os.environ.get('GRAPHIFY_CHANGED', '')
|
||||
changed = [Path(f.strip()) for f in changed_raw.strip().splitlines() if f.strip()]
|
||||
|
||||
if not changed:
|
||||
sys.exit(0)
|
||||
|
||||
print(f'[graphify hook] {len(changed)} file(s) changed - rebuilding graph...')
|
||||
|
||||
try:
|
||||
from graphify.watch import _rebuild_code, _apply_resource_limits
|
||||
_apply_resource_limits()
|
||||
_timeout = int(os.environ.get('GRAPHIFY_REBUILD_TIMEOUT', '600'))
|
||||
if _timeout > 0 and hasattr(signal, 'SIGALRM'):
|
||||
signal.signal(signal.SIGALRM, lambda *_: (_ for _ in ()).throw(TimeoutError(f'graphify rebuild exceeded {_timeout}s')))
|
||||
signal.alarm(_timeout)
|
||||
_force = os.environ.get('GRAPHIFY_FORCE', '').lower() in ('1', 'true', 'yes')
|
||||
_root = Path('.')
|
||||
_out = os.environ.get('GRAPHIFY_OUT', 'graphify-out')
|
||||
_saved = Path(_out) / '.graphify_root'
|
||||
if _saved.exists():
|
||||
_txt = _saved.read_text(encoding='utf-8').strip()
|
||||
if _txt:
|
||||
_root = Path(_txt)
|
||||
_rebuild_code(_root, changed_paths=changed, force=_force)
|
||||
# Refresh the work-memory lessons doc when saved Q&A outcomes exist
|
||||
# (best-effort; never fails the hook).
|
||||
try:
|
||||
_md = (_root / _out) / 'memory'
|
||||
if _md.is_dir() and any(_md.glob('*.md')):
|
||||
from graphify.reflect import reflect as _reflect
|
||||
_gj = (_root / _out) / 'graph.json'
|
||||
_reflect(memory_dir=_md, out_path=(_root / _out) / 'reflections' / 'LESSONS.md',
|
||||
graph_path=_gj if _gj.exists() else None)
|
||||
except Exception:
|
||||
pass
|
||||
except TimeoutError as exc:
|
||||
print(f'[graphify hook] {exc}')
|
||||
sys.exit(1)
|
||||
except Exception as exc:
|
||||
print(f'[graphify hook] Rebuild failed: {exc}')
|
||||
sys.exit(1)
|
||||
"""
|
||||
|
||||
_REBUILD_BODY_CHECKOUT = """\
|
||||
from graphify.watch import _rebuild_code, _apply_resource_limits
|
||||
from pathlib import Path
|
||||
import os, signal, sys
|
||||
try:
|
||||
_apply_resource_limits()
|
||||
_timeout = int(os.environ.get('GRAPHIFY_REBUILD_TIMEOUT', '600'))
|
||||
if _timeout > 0 and hasattr(signal, 'SIGALRM'):
|
||||
signal.signal(signal.SIGALRM, lambda *_: (_ for _ in ()).throw(TimeoutError(f'graphify rebuild exceeded {_timeout}s')))
|
||||
signal.alarm(_timeout)
|
||||
_force = os.environ.get('GRAPHIFY_FORCE', '').lower() in ('1', 'true', 'yes')
|
||||
# post-checkout: branch switch can touch arbitrary files; full rebuild path
|
||||
# (no changed_paths) is correct here. The flock inside _rebuild_code still
|
||||
# prevents pile-ups when commit + checkout fire back-to-back.
|
||||
_root = Path('.')
|
||||
_out = os.environ.get('GRAPHIFY_OUT', 'graphify-out')
|
||||
_saved = Path(_out) / '.graphify_root'
|
||||
if _saved.exists():
|
||||
_txt = _saved.read_text(encoding='utf-8').strip()
|
||||
if _txt:
|
||||
_root = Path(_txt)
|
||||
_rebuild_code(_root, force=_force)
|
||||
# Refresh the work-memory lessons doc when saved Q&A outcomes exist
|
||||
# (best-effort; never fails the hook).
|
||||
try:
|
||||
_md = (_root / _out) / 'memory'
|
||||
if _md.is_dir() and any(_md.glob('*.md')):
|
||||
from graphify.reflect import reflect as _reflect
|
||||
_gj = (_root / _out) / 'graph.json'
|
||||
_reflect(memory_dir=_md, out_path=(_root / _out) / 'reflections' / 'LESSONS.md',
|
||||
graph_path=_gj if _gj.exists() else None)
|
||||
except Exception:
|
||||
pass
|
||||
except TimeoutError as exc:
|
||||
print(f'[graphify] {exc}')
|
||||
sys.exit(1)
|
||||
except Exception as exc:
|
||||
print(f'[graphify] Rebuild failed: {exc}')
|
||||
sys.exit(1)
|
||||
"""
|
||||
|
||||
# Cross-platform detached-launch shim (#1161). The hooks used to background the
|
||||
# rebuild with `nohup "$GRAPHIFY_PYTHON" -c "..." &`, but Git for Windows' bundled
|
||||
# MSYS shell ships no nohup (nor setsid), so that line died with
|
||||
# 'nohup: command not found' and the rebuild silently never ran — git commit/pull
|
||||
# still returned 0, so the graph just went stale with no signal. graphify already
|
||||
# requires Python, so we let Python do the detaching: a tiny outer process spawns
|
||||
# the real rebuild fully detached and returns immediately, so the hook never
|
||||
# blocks. POSIX uses start_new_session (the setsid equivalent); Windows uses
|
||||
# DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP, breaking away from any job object
|
||||
# when allowed. This payload is carried inside a shell double-quoted -c argument,
|
||||
# so it deliberately uses only single-quoted Python strings (no ", $, ` or \\).
|
||||
_LAUNCHER_TEMPLATE = """\
|
||||
import os, subprocess, sys
|
||||
_src = '''
|
||||
__REBUILD_BODY__
|
||||
'''
|
||||
_log = os.environ.get('GRAPHIFY_REBUILD_LOG') or os.path.join(os.path.expanduser('~'), '.cache', 'graphify-rebuild.log')
|
||||
try:
|
||||
os.makedirs(os.path.dirname(_log), exist_ok=True)
|
||||
_out = open(_log, 'a', buffering=1, encoding='utf-8', errors='replace')
|
||||
except OSError:
|
||||
_out = subprocess.DEVNULL
|
||||
_kw = dict(stdout=_out, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, cwd=os.getcwd(), close_fds=True)
|
||||
_cmd = [sys.executable, '-c', _src]
|
||||
if os.name == 'nt':
|
||||
_flags = 0x00000008 | 0x00000200 # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
|
||||
try:
|
||||
subprocess.Popen(_cmd, creationflags=_flags | 0x01000000, **_kw) # + CREATE_BREAKAWAY_FROM_JOB
|
||||
except OSError:
|
||||
subprocess.Popen(_cmd, creationflags=_flags, **_kw)
|
||||
else:
|
||||
subprocess.Popen(_cmd, start_new_session=True, **_kw)
|
||||
"""
|
||||
|
||||
|
||||
def _detached_launch(rebuild_body: str) -> str:
|
||||
"""Return a POSIX-sh line that runs ``rebuild_body`` as a detached background
|
||||
Python process via ``$GRAPHIFY_PYTHON``.
|
||||
|
||||
Replaces the old ``nohup ... &`` form, which failed on Git for Windows'
|
||||
shell (no nohup/setsid) and let the rebuild silently never run (#1161).
|
||||
The launcher writes the child's output to ``$GRAPHIFY_REBUILD_LOG`` and
|
||||
returns the instant the child is spawned, so the git hook never blocks.
|
||||
"""
|
||||
launcher = _LAUNCHER_TEMPLATE.replace("__REBUILD_BODY__", rebuild_body)
|
||||
return '"$GRAPHIFY_PYTHON" -c "' + launcher + '"\n'
|
||||
|
||||
|
||||
_HOOK_SCRIPT = """\
|
||||
# graphify-hook-start
|
||||
# Auto-rebuilds the knowledge graph after each commit (code files only, no LLM needed).
|
||||
# Installed by: graphify hook install
|
||||
|
||||
# Deterministic clustering: networkx louvain iterates string-keyed sets whose
|
||||
# order is randomized per-process by PYTHONHASHSEED, so community assignments
|
||||
# churn run-to-run. Pinning it makes graphify-out reproducible.
|
||||
export PYTHONHASHSEED=0
|
||||
|
||||
# Git for Windows/MSYS hooks can inherit fragile pipe handles from GUI clients
|
||||
# and agent shells. Keep hook-triggered rebuilds sequential by default there;
|
||||
# explicit GRAPHIFY_MAX_WORKERS still wins for users who want parallelism.
|
||||
if [ -n "${WINDIR:-}" ] || [ -n "${MSYSTEM:-}" ]; then
|
||||
export GRAPHIFY_MAX_WORKERS="${GRAPHIFY_MAX_WORKERS:-1}"
|
||||
fi
|
||||
|
||||
# Skip during rebase/merge/cherry-pick to avoid blocking --continue with unstaged changes
|
||||
# git exports GIT_DIR to hooks; the rev-parse fallback only runs when invoked by
|
||||
# hand (each git exec costs 1s+ on AV-scanned Windows machines).
|
||||
GIT_DIR=${GIT_DIR:-$(git rev-parse --git-dir 2>/dev/null)}
|
||||
[ -d "$GIT_DIR/rebase-merge" ] && exit 0
|
||||
[ -d "$GIT_DIR/rebase-apply" ] && exit 0
|
||||
[ -f "$GIT_DIR/MERGE_HEAD" ] && exit 0
|
||||
[ -f "$GIT_DIR/CHERRY_PICK_HEAD" ] && exit 0
|
||||
|
||||
[ "${GRAPHIFY_SKIP_HOOK:-0}" = "1" ] && exit 0
|
||||
|
||||
CHANGED=$(git diff --name-only HEAD~1 HEAD 2>/dev/null || git diff --name-only HEAD 2>/dev/null)
|
||||
if [ -z "$CHANGED" ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Skip when only graphify-out/ artifacts changed (avoids rebuild loop when graph outputs are tracked in git)
|
||||
_NON_GRAPH=$(echo "$CHANGED" | grep -v '^graphify-out/' || true)
|
||||
if [ -z "$_NON_GRAPH" ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
""" + _PYTHON_DETECT + """
|
||||
export GRAPHIFY_CHANGED="$CHANGED"
|
||||
|
||||
# Run the rebuild detached so git commit returns immediately. Full-repo rebuilds
|
||||
# can take hours; blocking the post-commit hook stalls the shell. The Python
|
||||
# launcher below detaches the child cross-platform, so it works on Git for
|
||||
# Windows' shell too (which lacks the coreutils backgrounding tools) (#1161).
|
||||
_GRAPHIFY_LOG="${HOME}/.cache/graphify-rebuild.log"
|
||||
mkdir -p "$(dirname "$_GRAPHIFY_LOG")"
|
||||
export GRAPHIFY_REBUILD_LOG="$_GRAPHIFY_LOG"
|
||||
echo "[graphify hook] launching background rebuild (log: $_GRAPHIFY_LOG)"
|
||||
""" + _detached_launch(_REBUILD_BODY_COMMIT) + """# graphify-hook-end
|
||||
"""
|
||||
|
||||
|
||||
_CHECKOUT_SCRIPT = """\
|
||||
# graphify-checkout-hook-start
|
||||
# Auto-rebuilds the knowledge graph (code only) when switching branches.
|
||||
# Installed by: graphify hook install
|
||||
|
||||
# Deterministic clustering: networkx louvain iterates string-keyed sets whose
|
||||
# order is randomized per-process by PYTHONHASHSEED, so community assignments
|
||||
# churn run-to-run. Pinning it makes graphify-out reproducible.
|
||||
export PYTHONHASHSEED=0
|
||||
|
||||
# Git for Windows/MSYS hooks can inherit fragile pipe handles from GUI clients
|
||||
# and agent shells. Keep hook-triggered rebuilds sequential by default there;
|
||||
# explicit GRAPHIFY_MAX_WORKERS still wins for users who want parallelism.
|
||||
if [ -n "${WINDIR:-}" ] || [ -n "${MSYSTEM:-}" ]; then
|
||||
export GRAPHIFY_MAX_WORKERS="${GRAPHIFY_MAX_WORKERS:-1}"
|
||||
fi
|
||||
|
||||
PREV_HEAD=$1
|
||||
NEW_HEAD=$2
|
||||
BRANCH_SWITCH=$3
|
||||
|
||||
# Only run on branch switches, not file checkouts
|
||||
if [ "$BRANCH_SWITCH" != "1" ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Only run if graphify-out/ exists (graph has been built before)
|
||||
if [ ! -d "graphify-out" ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Skip during rebase/merge/cherry-pick
|
||||
# git exports GIT_DIR to hooks; the rev-parse fallback only runs when invoked by
|
||||
# hand (each git exec costs 1s+ on AV-scanned Windows machines).
|
||||
GIT_DIR=${GIT_DIR:-$(git rev-parse --git-dir 2>/dev/null)}
|
||||
[ -d "$GIT_DIR/rebase-merge" ] && exit 0
|
||||
[ -d "$GIT_DIR/rebase-apply" ] && exit 0
|
||||
[ -f "$GIT_DIR/MERGE_HEAD" ] && exit 0
|
||||
[ -f "$GIT_DIR/CHERRY_PICK_HEAD" ] && exit 0
|
||||
|
||||
""" + _PYTHON_DETECT + """
|
||||
_GRAPHIFY_LOG="${HOME}/.cache/graphify-rebuild.log"
|
||||
mkdir -p "$(dirname "$_GRAPHIFY_LOG")"
|
||||
export GRAPHIFY_REBUILD_LOG="$_GRAPHIFY_LOG"
|
||||
echo "[graphify] Branch switched - launching background rebuild (log: $_GRAPHIFY_LOG)"
|
||||
""" + _detached_launch(_REBUILD_BODY_CHECKOUT) + """# graphify-checkout-hook-end
|
||||
"""
|
||||
|
||||
|
||||
def _git_root(path: Path) -> Path | None:
|
||||
"""Walk up to find .git directory."""
|
||||
current = path.resolve()
|
||||
for parent in [current, *current.parents]:
|
||||
if (parent / ".git").exists():
|
||||
return parent
|
||||
return None
|
||||
|
||||
|
||||
_WINDOWS_DRIVE_RE = re.compile(r"^[A-Za-z]:[\\/]")
|
||||
|
||||
|
||||
def _reject_windows_path(value: str, source: str) -> None:
|
||||
"""Raise if a hooks path looks like a Windows absolute path (#1385).
|
||||
|
||||
On POSIX/WSL ``Path("C:\\Users\\...").is_absolute()`` is False, so an absolute
|
||||
Windows hooks path gets joined under the repo root and mkdir'd as a literal
|
||||
junk directory (backslashes and all), while install reports success and the
|
||||
real ``.git/hooks`` gets nothing. Fail loudly instead so the user can fix it.
|
||||
"""
|
||||
if os.name == "nt":
|
||||
return
|
||||
if _WINDOWS_DRIVE_RE.match(value) or "\\" in value:
|
||||
raise RuntimeError(
|
||||
f"git hooks path from {source} looks like a Windows path: {value!r}. "
|
||||
f"On WSL/POSIX this can't resolve to a real directory. Unset it with "
|
||||
f"`git config --local --unset core.hooksPath`, or set a POSIX path."
|
||||
)
|
||||
|
||||
|
||||
def _hooks_dir(root: Path) -> Path:
|
||||
"""Return the git hooks directory, respecting core.hooksPath if set (e.g. Husky)."""
|
||||
try:
|
||||
cfg = configparser.RawConfigParser()
|
||||
cfg.read(root / ".git" / "config", encoding="utf-8")
|
||||
# configparser lowercases option names; git's hooksPath becomes hookspath
|
||||
custom = cfg.get("core", "hookspath", fallback="").strip()
|
||||
if custom:
|
||||
_reject_windows_path(custom, "core.hooksPath")
|
||||
p = Path(custom).expanduser()
|
||||
if not p.is_absolute():
|
||||
p = root / p
|
||||
# Validate the resolved path stays within the repository root
|
||||
# to prevent supply-chain attacks via malicious core.hooksPath values
|
||||
try:
|
||||
p.resolve().relative_to(root.resolve())
|
||||
except ValueError:
|
||||
pass # Path escapes repo root; fall through to default .git/hooks
|
||||
else:
|
||||
p.mkdir(parents=True, exist_ok=True)
|
||||
return p
|
||||
except (configparser.Error, OSError) as exc:
|
||||
# Narrow the exception (PR747-NEW-2): a bare `except Exception: pass`
|
||||
# was hiding tampering signals (corrupt .git/config, permission flips
|
||||
# by another tool). Surface them on stderr instead of silently
|
||||
# falling through to the default hooks directory.
|
||||
print(
|
||||
f"[graphify hooks] could not read core.hooksPath from "
|
||||
f"{root / '.git' / 'config'}: {exc}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
# In a linked worktree .git is a file not a directory, so constructing
|
||||
# root/.git/hooks directly fails. Ask git for the real hooks path instead.
|
||||
# NOTE: do NOT pass --path-format=absolute — added in git 2.31; older git
|
||||
# echoes it back as a literal argument, contaminating stdout and causing a
|
||||
# phantom directory to be created (#907). git -C <root> already returns an
|
||||
# absolute path for worktree/external-gitdir cases, and a path relative to
|
||||
# <root> for normal repos — anchoring on root covers both.
|
||||
import subprocess as _sp
|
||||
try:
|
||||
res = _sp.run(
|
||||
["git", "-C", str(root), "rev-parse", "--git-path", "hooks"],
|
||||
capture_output=True, text=True,
|
||||
)
|
||||
raw = res.stdout.strip()
|
||||
# A valid hooks path can never contain newlines or NUL. Their presence
|
||||
# means git echoed an unrecognised flag back (old git behaviour).
|
||||
if res.returncode == 0 and raw and not any(c in raw for c in ("\n", "\r", "\x00")):
|
||||
_reject_windows_path(raw, "git rev-parse --git-path hooks")
|
||||
d = (root / raw).resolve()
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
except (OSError, FileNotFoundError):
|
||||
pass
|
||||
d = root / ".git" / "hooks"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
def _install_hook(hooks_dir: Path, name: str, script: str, marker: str) -> str:
|
||||
"""Install a single git hook, appending if an existing hook is present."""
|
||||
hook_path = hooks_dir / name
|
||||
if hook_path.exists():
|
||||
content = hook_path.read_text(encoding="utf-8")
|
||||
if marker in content:
|
||||
return f"already installed at {hook_path}"
|
||||
hook_path.write_text(content.rstrip() + "\n\n" + script, encoding="utf-8", newline="\n")
|
||||
return f"appended to existing {name} hook at {hook_path}"
|
||||
hook_path.write_text("#!/bin/sh\n" + script, encoding="utf-8", newline="\n")
|
||||
hook_path.chmod(0o755)
|
||||
return f"installed at {hook_path}"
|
||||
|
||||
|
||||
def _uninstall_hook(hooks_dir: Path, name: str, marker: str, marker_end: str) -> str:
|
||||
"""Remove graphify section from a git hook using start/end markers."""
|
||||
hook_path = hooks_dir / name
|
||||
if not hook_path.exists():
|
||||
return f"no {name} hook found - nothing to remove."
|
||||
content = hook_path.read_text(encoding="utf-8")
|
||||
if marker not in content:
|
||||
return f"graphify hook not found in {name} - nothing to remove."
|
||||
new_content = re.sub(
|
||||
rf"{re.escape(marker)}.*?{re.escape(marker_end)}\n?",
|
||||
"",
|
||||
content,
|
||||
flags=re.DOTALL,
|
||||
).strip()
|
||||
if not new_content or new_content in ("#!/bin/bash", "#!/bin/sh"):
|
||||
hook_path.unlink()
|
||||
return f"removed {name} hook at {hook_path}"
|
||||
hook_path.write_text(new_content + "\n", encoding="utf-8", newline="\n")
|
||||
return f"graphify removed from {name} at {hook_path} (other hook content preserved)"
|
||||
|
||||
|
||||
def _user_hooks_dir(hooks_dir: Path) -> Path:
|
||||
"""Return the user-editable hooks directory.
|
||||
|
||||
Husky 9 sets core.hooksPath to .husky/_ (wrapper scripts auto-generated by
|
||||
Husky), while user-editable hooks live in the parent .husky/. Return the
|
||||
parent when the resolved dir ends in '_' so install/status/uninstall target
|
||||
the correct location (#987).
|
||||
"""
|
||||
if hooks_dir.name == "_":
|
||||
return hooks_dir.parent
|
||||
return hooks_dir
|
||||
|
||||
|
||||
def install(path: Path = Path(".")) -> str:
|
||||
"""Install graphify post-commit and post-checkout hooks in the nearest git repo."""
|
||||
root = _git_root(path)
|
||||
if root is None:
|
||||
raise RuntimeError(f"No git repository found at or above {path.resolve()}")
|
||||
|
||||
hooks_dir = _user_hooks_dir(_hooks_dir(root))
|
||||
|
||||
# Pin the current interpreter so the hook works even when the graphify
|
||||
# launcher is not on PATH at git-trigger time (uv tool / pipx isolation).
|
||||
# sys.executable is the Python running this very install command, so it is
|
||||
# always the correct isolated-venv interpreter. The placeholder is replaced
|
||||
# in both scripts before writing; the allowlist in _PYTHON_DETECT strips any
|
||||
# characters unsafe in a shell path, and import-verification catches a stale
|
||||
# pinned path so it safely falls through to the dynamic detection.
|
||||
# Apply the same allowlist used in _PYTHON_DETECT for all other probes.
|
||||
# This rejects any character that is not a valid plain filesystem path
|
||||
# character, preventing $(...), backtick, double-quote, semicolon, etc.
|
||||
# from being injected into the generated shell scripts. The allowlist
|
||||
# includes ':' and '\' so Windows paths (C:\...) are accepted.
|
||||
import re as _re
|
||||
_safe = sys.executable
|
||||
if _re.search(r"[^a-zA-Z0-9/_.@:\\-]", _safe):
|
||||
# Path contains characters outside the allowlist (spaces, quotes, etc.).
|
||||
# Embed an empty string so the pinned probe is skipped and the hook
|
||||
# falls through to the dynamic detection — safe degradation.
|
||||
_safe = ""
|
||||
pinned = _safe
|
||||
hook = _HOOK_SCRIPT.replace("__PINNED_PYTHON__", pinned)
|
||||
checkout = _CHECKOUT_SCRIPT.replace("__PINNED_PYTHON__", pinned)
|
||||
|
||||
commit_msg = _install_hook(hooks_dir, "post-commit", hook, _HOOK_MARKER)
|
||||
checkout_msg = _install_hook(hooks_dir, "post-checkout", checkout, _CHECKOUT_MARKER)
|
||||
|
||||
return f"post-commit: {commit_msg}\npost-checkout: {checkout_msg}"
|
||||
|
||||
|
||||
def uninstall(path: Path = Path(".")) -> str:
|
||||
"""Remove graphify post-commit and post-checkout hooks."""
|
||||
root = _git_root(path)
|
||||
if root is None:
|
||||
raise RuntimeError(f"No git repository found at or above {path.resolve()}")
|
||||
|
||||
hooks_dir = _user_hooks_dir(_hooks_dir(root))
|
||||
commit_msg = _uninstall_hook(hooks_dir, "post-commit", _HOOK_MARKER, _HOOK_MARKER_END)
|
||||
checkout_msg = _uninstall_hook(hooks_dir, "post-checkout", _CHECKOUT_MARKER, _CHECKOUT_MARKER_END)
|
||||
|
||||
return f"post-commit: {commit_msg}\npost-checkout: {checkout_msg}"
|
||||
|
||||
|
||||
def status(path: Path = Path(".")) -> str:
|
||||
"""Check if graphify hooks are installed."""
|
||||
root = _git_root(path)
|
||||
if root is None:
|
||||
return "Not in a git repository."
|
||||
hooks_dir = _user_hooks_dir(_hooks_dir(root))
|
||||
|
||||
def _check(name: str, marker: str) -> str:
|
||||
p = hooks_dir / name
|
||||
if not p.exists():
|
||||
return "not installed"
|
||||
return "installed" if marker in p.read_text(encoding="utf-8") else "not installed (hook exists but graphify not found)"
|
||||
|
||||
commit = _check("post-commit", _HOOK_MARKER)
|
||||
checkout = _check("post-checkout", _CHECKOUT_MARKER)
|
||||
return f"post-commit: {commit}\npost-checkout: {checkout}"
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Single source of truth for node-ID normalization.
|
||||
|
||||
Three independent producers must agree on node IDs or the graph splits a single
|
||||
entity into disconnected ghost nodes:
|
||||
|
||||
1. The AST extractor (``extract._make_id``) — deterministic, per-language.
|
||||
2. The semantic subagents (LLM) — follow the node-ID spec in the skill prompt.
|
||||
3. The graph builder (``build._normalize_id``) — reconciles edge endpoints when
|
||||
the LLM emits IDs with slightly different punctuation or casing than the AST.
|
||||
|
||||
Historically the normalization recipe was copy-pasted into ``extract._make_id``
|
||||
and ``build._normalize_id`` and kept in sync only by mirrored docstrings, which
|
||||
is exactly how the recurring ID-drift bug class crept in (#811 Unicode collapse,
|
||||
#550 same-filename collisions, #1033 AST-vs-LLM file-node mismatch, #1104). This
|
||||
module exists so the recipe lives in one place and the two callers can no longer
|
||||
diverge.
|
||||
|
||||
The recipe: NFKC-normalize (so composed/decomposed Unicode forms collapse),
|
||||
replace runs of non-word characters with a single underscore (``re.UNICODE`` so
|
||||
CJK/Cyrillic/Arabic/accented-Latin letters survive instead of collapsing to a
|
||||
per-file node), collapse repeated underscores, strip leading/trailing
|
||||
underscores, and casefold.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
__all__ = ["normalize_id", "make_id"]
|
||||
|
||||
|
||||
def normalize_id(s: str) -> str:
|
||||
r"""Normalize a single ID string to its canonical form.
|
||||
|
||||
Idempotent: ``normalize_id(normalize_id(s)) == normalize_id(s)``.
|
||||
"""
|
||||
s = unicodedata.normalize("NFKC", s)
|
||||
s = re.sub(r"[^\w]+", "_", s, flags=re.UNICODE)
|
||||
s = re.sub(r"_+", "_", s)
|
||||
return s.strip("_").casefold()
|
||||
|
||||
|
||||
def make_id(*parts: str) -> str:
|
||||
"""Build a canonical node ID from one or more name parts.
|
||||
|
||||
Parts are joined with ``_`` (after stripping stray ``_``/``.`` edges from each
|
||||
part) and then run through :func:`normalize_id`, so the result is identical to
|
||||
what the builder produces from the joined string.
|
||||
"""
|
||||
return normalize_id("_".join(p.strip("_.") for p in parts if p))
|
||||
+96
-32
@@ -2,7 +2,6 @@
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
from datetime import datetime, timezone
|
||||
@@ -11,6 +10,48 @@ from pathlib import Path
|
||||
from graphify.security import safe_fetch, safe_fetch_text, validate_url
|
||||
|
||||
|
||||
def _yaml_str(s: str) -> str:
|
||||
"""Escape a string for embedding in a YAML double-quoted scalar.
|
||||
|
||||
Handles every YAML 1.1/1.2 line-break and control character that could
|
||||
let a hostile value (e.g. a fetched page title) break out of the quoted
|
||||
scalar and inject sibling YAML keys (F-009 / F-019). The previous
|
||||
implementation missed `\\t`, `\\0`, the unicode line-separator U+2028 and
|
||||
paragraph-separator U+2029 — all of which YAML treats as line breaks.
|
||||
|
||||
We intentionally do not depend on PyYAML (not in pyproject deps) and
|
||||
instead emit safely-escaped double-quoted scalars by hand: the YAML
|
||||
double-quoted form recognises `\\\\`, `\\"`, `\\n`, `\\r`, `\\t`, `\\0`,
|
||||
`\\L` (U+2028), `\\P` (U+2029), and `\\xNN`/`\\uNNNN` numeric escapes.
|
||||
"""
|
||||
if s is None:
|
||||
return ""
|
||||
out: list[str] = []
|
||||
for ch in str(s):
|
||||
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 < 0x20 or cp == 0x7F:
|
||||
out.append(f"\\x{cp:02x}")
|
||||
else:
|
||||
out.append(ch)
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def _safe_filename(url: str, suffix: str) -> str:
|
||||
"""Turn a URL into a safe filename."""
|
||||
parsed = urllib.parse.urlparse(url)
|
||||
@@ -45,19 +86,16 @@ def _fetch_html(url: str) -> str:
|
||||
|
||||
|
||||
def _html_to_markdown(html: str, url: str) -> str:
|
||||
"""Convert HTML to clean markdown. Uses html2text if available, else basic strip."""
|
||||
"""Convert HTML to clean markdown. Uses markdownify if available, else basic strip."""
|
||||
# Always pre-strip script/style so their text content never leaks into output
|
||||
html = re.sub(r"<script[^>]*>.*?</script>", "", html, flags=re.DOTALL | re.IGNORECASE)
|
||||
html = re.sub(r"<style[^>]*>.*?</style>", "", html, flags=re.DOTALL | re.IGNORECASE)
|
||||
try:
|
||||
import html2text
|
||||
h = html2text.HTML2Text()
|
||||
h.ignore_links = False
|
||||
h.ignore_images = True
|
||||
h.body_width = 0
|
||||
return h.handle(html)
|
||||
from markdownify import markdownify
|
||||
return markdownify(html, heading_style="ATX", bullets="-", strip=["img"])
|
||||
except ImportError:
|
||||
# Fallback: strip tags
|
||||
text = re.sub(r"<script[^>]*>.*?</script>", "", html, flags=re.DOTALL | re.IGNORECASE)
|
||||
text = re.sub(r"<style[^>]*>.*?</style>", "", text, flags=re.DOTALL | re.IGNORECASE)
|
||||
text = re.sub(r"<[^>]+>", " ", text)
|
||||
# Fallback: basic tag strip
|
||||
text = re.sub(r"<[^>]+>", " ", html)
|
||||
text = re.sub(r"\s+", " ", text).strip()
|
||||
return text[:8000]
|
||||
|
||||
@@ -68,23 +106,21 @@ def _fetch_tweet(url: str, author: str | None, contributor: str | None) -> tuple
|
||||
oembed_url = url.replace("x.com", "twitter.com")
|
||||
oembed_api = f"https://publish.twitter.com/oembed?url={urllib.parse.quote(oembed_url)}&omit_script=true"
|
||||
try:
|
||||
req = urllib.request.Request(oembed_api, headers={"User-Agent": "graphify/1.0"})
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
data = json.loads(resp.read())
|
||||
data = json.loads(safe_fetch_text(oembed_api))
|
||||
tweet_text = re.sub(r"<[^>]+>", "", data.get("html", "")).strip()
|
||||
tweet_author = data.get("author_name", "unknown")
|
||||
except Exception:
|
||||
# oEmbed failed — save URL stub
|
||||
# oEmbed failed - save URL stub
|
||||
tweet_text = f"Tweet at {url} (could not fetch content)"
|
||||
tweet_author = "unknown"
|
||||
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
content = f"""---
|
||||
source_url: {url}
|
||||
source_url: "{_yaml_str(url)}"
|
||||
type: tweet
|
||||
author: {tweet_author}
|
||||
author: "{_yaml_str(tweet_author)}"
|
||||
captured_at: {now}
|
||||
contributor: {contributor or author or 'unknown'}
|
||||
contributor: "{_yaml_str(contributor or author or 'unknown')}"
|
||||
---
|
||||
|
||||
# Tweet by @{tweet_author}
|
||||
@@ -107,11 +143,11 @@ def _fetch_webpage(url: str, author: str | None, contributor: str | None) -> tup
|
||||
markdown = _html_to_markdown(html, url)
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
content = f"""---
|
||||
source_url: {url}
|
||||
source_url: "{_yaml_str(url)}"
|
||||
type: webpage
|
||||
title: "{title}"
|
||||
title: "{_yaml_str(title)}"
|
||||
captured_at: {now}
|
||||
contributor: {contributor or author or 'unknown'}
|
||||
contributor: "{_yaml_str(contributor or author or 'unknown')}"
|
||||
---
|
||||
|
||||
# {title}
|
||||
@@ -147,13 +183,13 @@ def _fetch_arxiv(url: str, author: str | None, contributor: str | None) -> tuple
|
||||
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
content = f"""---
|
||||
source_url: {url}
|
||||
arxiv_id: {arxiv_id.group(1) if arxiv_id else ''}
|
||||
source_url: "{_yaml_str(url)}"
|
||||
arxiv_id: "{_yaml_str(arxiv_id.group(1) if arxiv_id else '')}"
|
||||
type: paper
|
||||
title: "{title}"
|
||||
paper_authors: "{paper_authors}"
|
||||
title: "{_yaml_str(title)}"
|
||||
paper_authors: "{_yaml_str(paper_authors)}"
|
||||
captured_at: {now}
|
||||
contributor: {contributor or author or 'unknown'}
|
||||
contributor: "{_yaml_str(contributor or author or 'unknown')}"
|
||||
---
|
||||
|
||||
# {title}
|
||||
@@ -205,6 +241,12 @@ def ingest(url: str, target_dir: Path, author: str | None = None, contributor: s
|
||||
print(f"Downloaded image: {out.name}")
|
||||
return out
|
||||
|
||||
if url_type == "youtube":
|
||||
from graphify.transcribe import download_audio
|
||||
out = download_audio(url, target_dir)
|
||||
print(f"Downloaded audio: {out.name}")
|
||||
return out
|
||||
|
||||
if url_type == "tweet":
|
||||
content, filename = _fetch_tweet(url, author, contributor)
|
||||
elif url_type == "arxiv":
|
||||
@@ -215,9 +257,9 @@ def ingest(url: str, target_dir: Path, author: str | None = None, contributor: s
|
||||
raise RuntimeError(f"ingest: failed to fetch {url!r}: {exc}") from exc
|
||||
|
||||
out_path = target_dir / filename
|
||||
# Avoid overwriting — append counter if needed
|
||||
# Avoid overwriting - append counter if needed
|
||||
counter = 1
|
||||
while out_path.exists():
|
||||
while out_path.exists() and counter < 1000:
|
||||
stem = Path(filename).stem
|
||||
out_path = target_dir / f"{stem}_{counter}.md"
|
||||
counter += 1
|
||||
@@ -226,6 +268,8 @@ def ingest(url: str, target_dir: Path, author: str | None = None, contributor: s
|
||||
print(f"Saved {url_type}: {out_path.name}")
|
||||
return out_path
|
||||
|
||||
OUTCOMES = ("useful", "dead_end", "corrected")
|
||||
|
||||
|
||||
def save_query_result(
|
||||
question: str,
|
||||
@@ -233,13 +277,23 @@ def save_query_result(
|
||||
memory_dir: Path,
|
||||
query_type: str = "query",
|
||||
source_nodes: list[str] | None = None,
|
||||
outcome: str | None = None,
|
||||
correction: str | None = None,
|
||||
) -> Path:
|
||||
"""Save a Q&A result as markdown so it gets extracted into the graph on next --update.
|
||||
|
||||
Files are stored in memory_dir (typically .graphify/memory/) with YAML frontmatter
|
||||
Files are stored in memory_dir (typically graphify-out/memory/) with YAML frontmatter
|
||||
that graphify's extractor reads as node metadata. This closes the feedback loop:
|
||||
the system grows smarter from both what you add AND what you ask.
|
||||
|
||||
``outcome`` (one of :data:`OUTCOMES`) and ``correction`` are optional work-memory
|
||||
signals: they are written both to the frontmatter (so `graphify reflect` can
|
||||
aggregate them deterministically) and to an ``## Outcome`` body section (so the
|
||||
signal round-trips into the graph on the next semantic re-extraction).
|
||||
"""
|
||||
if outcome is not None and outcome not in OUTCOMES:
|
||||
raise ValueError(f"outcome must be one of {OUTCOMES}, got {outcome!r}")
|
||||
|
||||
memory_dir = Path(memory_dir)
|
||||
memory_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -251,11 +305,15 @@ def save_query_result(
|
||||
"---",
|
||||
f'type: "{query_type}"',
|
||||
f'date: "{now.isoformat()}"',
|
||||
f'question: "{re.sub(chr(10) + chr(13), " ", question).replace(chr(34), chr(39))}"',
|
||||
f'question: "{_yaml_str(question)}"',
|
||||
'contributor: "graphify"',
|
||||
]
|
||||
if outcome:
|
||||
frontmatter_lines.append(f'outcome: "{_yaml_str(outcome)}"')
|
||||
if correction:
|
||||
frontmatter_lines.append(f'correction: "{_yaml_str(correction)}"')
|
||||
if source_nodes:
|
||||
nodes_str = ", ".join(f'"{n}"' for n in source_nodes[:10])
|
||||
nodes_str = ", ".join(f'"{_yaml_str(n)}"' for n in source_nodes[:10])
|
||||
frontmatter_lines.append(f"source_nodes: [{nodes_str}]")
|
||||
frontmatter_lines.append("---")
|
||||
|
||||
@@ -267,6 +325,12 @@ def save_query_result(
|
||||
"",
|
||||
answer,
|
||||
]
|
||||
if outcome or correction:
|
||||
body_lines += ["", "## Outcome", ""]
|
||||
if outcome:
|
||||
body_lines.append(f"- Signal: {outcome}")
|
||||
if correction:
|
||||
body_lines.append(f"- Correction: {correction}")
|
||||
if source_nodes:
|
||||
body_lines += ["", "## Source Nodes", ""]
|
||||
body_lines += [f"- {n}" for n in source_nodes]
|
||||
|
||||
+2399
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,247 @@
|
||||
"""Deterministic package-manifest ingestion (#1377).
|
||||
|
||||
Package manifests (``apm.yml``, ``pyproject.toml``, ``go.mod``, ``pom.xml``)
|
||||
declare a package and its dependencies. Left to the LLM document path, the same
|
||||
package gets a different file-anchored node id from its own manifest than from
|
||||
each dependent's dependency reference, so it splits into duplicate nodes. This
|
||||
module parses manifests deterministically and emits ONE canonical package node
|
||||
per package -- keyed by NAME via :func:`graphify.ids.make_id` -- plus
|
||||
``depends_on`` edges, so a package referenced from N manifests collapses to a
|
||||
single hub node (the dependency stub and the package's own definition node share
|
||||
the canonical id and merge at build time).
|
||||
|
||||
Mirrors ``mcp_ingest``: recognized by filename, routed to the deterministic AST
|
||||
path (never the LLM), so a manifest is extracted exactly once.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import xml.etree.ElementTree as ET
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from graphify.ids import make_id
|
||||
|
||||
__all__ = ["is_package_manifest_path", "extract_package_manifest", "PACKAGE_MANIFEST_NAMES"]
|
||||
|
||||
# manifest filename (lowercased) -> ecosystem tag
|
||||
PACKAGE_MANIFEST_NAMES: dict[str, str] = {
|
||||
"apm.yml": "apm",
|
||||
"apm.yaml": "apm",
|
||||
"pyproject.toml": "python",
|
||||
"go.mod": "go",
|
||||
"pom.xml": "maven",
|
||||
}
|
||||
|
||||
_MAX_MANIFEST_BYTES = 2_000_000 # 2 MB cap — manifests are small; this rejects junk
|
||||
|
||||
|
||||
def is_package_manifest_path(path: Path) -> bool:
|
||||
"""True if ``path`` is a recognized package manifest (by filename)."""
|
||||
return path.name.lower() in PACKAGE_MANIFEST_NAMES
|
||||
|
||||
|
||||
def _pkg_id(name: str) -> str:
|
||||
"""Canonical package node id, keyed by package NAME so every reference to the
|
||||
same package -- its own manifest and any dependent's dependency line -- maps
|
||||
to one node."""
|
||||
return make_id("pkg", name)
|
||||
|
||||
|
||||
def extract_package_manifest(path: Path) -> dict[str, Any]:
|
||||
"""Parse a package manifest into a canonical package node + ``depends_on`` edges."""
|
||||
try:
|
||||
if path.stat().st_size > _MAX_MANIFEST_BYTES:
|
||||
return {"nodes": [], "edges": [], "error": "manifest too large to index"}
|
||||
text = path.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError as exc:
|
||||
return {"nodes": [], "edges": [], "error": f"manifest read error: {exc}"}
|
||||
|
||||
eco = PACKAGE_MANIFEST_NAMES[path.name.lower()]
|
||||
try:
|
||||
info = _PARSERS[eco](text)
|
||||
except Exception as exc: # noqa: BLE001 — a malformed manifest must not abort extraction
|
||||
return {"nodes": [], "edges": [], "error": f"manifest parse error: {exc}"}
|
||||
if not info or not info.get("name"):
|
||||
return {"nodes": [], "edges": []}
|
||||
|
||||
name = info["name"]
|
||||
str_path = str(path)
|
||||
pkg_nid = _pkg_id(name)
|
||||
node: dict[str, Any] = {
|
||||
"id": pkg_nid,
|
||||
"label": name,
|
||||
"file_type": "code", # valid schema type; `type` distinguishes packages
|
||||
"type": "package",
|
||||
"ecosystem": eco,
|
||||
"source_file": str_path,
|
||||
"source_location": "L1",
|
||||
}
|
||||
if info.get("version"):
|
||||
node["version"] = info["version"]
|
||||
nodes: list[dict] = [node]
|
||||
edges: list[dict] = []
|
||||
|
||||
seen: set[str] = set()
|
||||
for dep in info.get("deps", []):
|
||||
if not dep:
|
||||
continue
|
||||
dep_nid = _pkg_id(dep)
|
||||
if dep_nid == pkg_nid or dep_nid in seen:
|
||||
continue
|
||||
seen.add(dep_nid)
|
||||
# The edge targets the dependency's canonical package id. If that package's
|
||||
# own manifest is in the corpus, the edge resolves to its (single) node; if
|
||||
# the dependency is external, build_from_json prunes the dangling edge. We
|
||||
# deliberately do NOT emit a stub node — a stub with an empty source_file
|
||||
# would risk clobbering the real node's source_file under id-dedup.
|
||||
edges.append({
|
||||
"source": pkg_nid,
|
||||
"target": dep_nid,
|
||||
"relation": "depends_on",
|
||||
"context": "dependency",
|
||||
"confidence": "EXTRACTED",
|
||||
"confidence_score": 1.0,
|
||||
"source_file": str_path,
|
||||
"source_location": "L1",
|
||||
"weight": 1.0,
|
||||
})
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
|
||||
|
||||
# ── per-ecosystem parsers: text -> {"name", "version"?, "deps": [str]} | None ──
|
||||
|
||||
def _coerce_deps(value: Any) -> list[str]:
|
||||
"""A dependency block may be a list of names or a name->spec map."""
|
||||
if isinstance(value, dict):
|
||||
return [str(k) for k in value]
|
||||
if isinstance(value, list):
|
||||
out: list[str] = []
|
||||
for item in value:
|
||||
if isinstance(item, str):
|
||||
out.append(item)
|
||||
elif isinstance(item, dict) and item:
|
||||
out.append(str(next(iter(item))))
|
||||
return out
|
||||
return []
|
||||
|
||||
|
||||
def _parse_apm(text: str) -> dict | None:
|
||||
try:
|
||||
import yaml
|
||||
except ImportError:
|
||||
return _parse_apm_fallback(text)
|
||||
data = yaml.safe_load(text)
|
||||
if not isinstance(data, dict):
|
||||
return None
|
||||
return {
|
||||
"name": data.get("name"),
|
||||
"version": data.get("version"),
|
||||
"deps": _coerce_deps(data.get("dependencies")),
|
||||
}
|
||||
|
||||
|
||||
def _parse_apm_fallback(text: str) -> dict | None:
|
||||
"""Minimal line parser for apm.yml when PyYAML is unavailable: a top-level
|
||||
``name:`` plus a simple ``dependencies:`` block (list items or a name map)."""
|
||||
name = None
|
||||
deps: list[str] = []
|
||||
in_deps = False
|
||||
for line in text.splitlines():
|
||||
if not in_deps:
|
||||
m = re.match(r'^name:\s*["\']?([^"\'\s#]+)', line)
|
||||
if m:
|
||||
name = m.group(1)
|
||||
continue
|
||||
if re.match(r'^dependencies:\s*$', line):
|
||||
in_deps = True
|
||||
continue
|
||||
if in_deps:
|
||||
dm = (re.match(r'^\s*-\s*["\']?([^"\'\s#:]+)', line)
|
||||
or re.match(r'^\s{2,}([A-Za-z0-9._/@-]+)\s*:', line))
|
||||
if dm:
|
||||
deps.append(dm.group(1))
|
||||
elif re.match(r'^\S', line): # next top-level key ends the block
|
||||
in_deps = False
|
||||
return {"name": name, "version": None, "deps": deps} if name else None
|
||||
|
||||
|
||||
def _pep508_name(spec: str) -> str:
|
||||
"""`requests>=2.0` -> `requests`; `pkg[extra]==1; python_version<'3.9'` -> `pkg`."""
|
||||
return re.split(r'[\s<>=!~;\[\(]', spec.strip(), maxsplit=1)[0]
|
||||
|
||||
|
||||
def _parse_pyproject(text: str) -> dict | None:
|
||||
try:
|
||||
import tomllib as _toml
|
||||
except ImportError:
|
||||
try:
|
||||
import tomli as _toml # type: ignore
|
||||
except ImportError:
|
||||
return None
|
||||
data = _toml.loads(text)
|
||||
proj = data.get("project", {}) if isinstance(data.get("project"), dict) else {}
|
||||
poetry = (data.get("tool", {}) or {}).get("poetry", {}) if isinstance(data.get("tool"), dict) else {}
|
||||
name = proj.get("name") or (poetry.get("name") if isinstance(poetry, dict) else None)
|
||||
if not name:
|
||||
return None
|
||||
deps: list[str] = [_pep508_name(s) for s in (proj.get("dependencies") or []) if isinstance(s, str)]
|
||||
if isinstance(poetry, dict):
|
||||
for dep in (poetry.get("dependencies") or {}):
|
||||
if str(dep).lower() != "python":
|
||||
deps.append(str(dep))
|
||||
return {"name": name, "version": proj.get("version") or (poetry.get("version") if isinstance(poetry, dict) else None), "deps": deps}
|
||||
|
||||
|
||||
def _parse_gomod(text: str) -> dict | None:
|
||||
name = None
|
||||
deps: list[str] = []
|
||||
in_block = False
|
||||
for line in text.splitlines():
|
||||
s = line.strip()
|
||||
if name is None:
|
||||
m = re.match(r'^module\s+(\S+)', s)
|
||||
if m:
|
||||
name = m.group(1)
|
||||
continue
|
||||
if re.match(r'^require\s*\(', s):
|
||||
in_block = True
|
||||
continue
|
||||
if in_block:
|
||||
if s.startswith(')'):
|
||||
in_block = False
|
||||
continue
|
||||
dm = re.match(r'^(\S+)\s+v\S+', s)
|
||||
if dm:
|
||||
deps.append(dm.group(1))
|
||||
else:
|
||||
dm = re.match(r'^require\s+(\S+)\s+v\S+', s)
|
||||
if dm:
|
||||
deps.append(dm.group(1))
|
||||
return {"name": name, "version": None, "deps": deps} if name else None
|
||||
|
||||
|
||||
def _parse_pom(text: str) -> dict | None:
|
||||
# Drop the default namespace so findtext/findall don't need the {uri} prefix.
|
||||
text = re.sub(r'\sxmlns="[^"]*"', '', text, count=1)
|
||||
root = ET.fromstring(text)
|
||||
aid = root.findtext("artifactId")
|
||||
gid = root.findtext("groupId")
|
||||
if not aid:
|
||||
return None
|
||||
name = f"{gid}:{aid}" if gid else aid
|
||||
deps: list[str] = []
|
||||
for dep in root.findall(".//dependencies/dependency"):
|
||||
da = dep.findtext("artifactId")
|
||||
dg = dep.findtext("groupId")
|
||||
if da:
|
||||
deps.append(f"{dg}:{da}" if dg else da)
|
||||
return {"name": name, "version": root.findtext("version"), "deps": deps}
|
||||
|
||||
|
||||
_PARSERS = {
|
||||
"apm": _parse_apm,
|
||||
"python": _parse_pyproject,
|
||||
"go": _parse_gomod,
|
||||
"maven": _parse_pom,
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
"""mcp_ingest.py — Extract MCP (Model Context Protocol) server configuration files.
|
||||
|
||||
Reads `.mcp.json` / `claude_desktop_config.json` / `mcp.json` / `mcp_servers.json`
|
||||
and turns the `mcpServers` map into Graphify nodes and edges.
|
||||
|
||||
Symmetry with `serve.py`: Graphify exposes itself AS an MCP server. This module
|
||||
indexes MCP servers AS a corpus type, completing the loop — an agent that runs
|
||||
graphify with `--mcp` can now query its own configured MCP layer.
|
||||
|
||||
Entry point:
|
||||
extract_mcp_config(path: Path) -> dict[str, list[dict]]
|
||||
|
||||
Returns `{"nodes": [...], "edges": [...]}` compatible with Graphify's
|
||||
extraction-result format. Returns `{"nodes": [...], "edges": [...], "error": "..."}`
|
||||
when the file is malformed, too large, or has no `mcpServers` map — the empty
|
||||
result keeps it indistinguishable from "no MCP config here" for downstream
|
||||
callers.
|
||||
|
||||
Detected filenames (case-sensitive, matched on basename):
|
||||
- .mcp.json (Claude Code project config)
|
||||
- claude_desktop_config.json (Claude Desktop)
|
||||
- mcp.json (generic / per-tool)
|
||||
- mcp_servers.json (alternate naming)
|
||||
|
||||
Schema emitted:
|
||||
Node kinds:
|
||||
- file the config file itself (label = filename)
|
||||
- mcp_server one per entry under mcpServers
|
||||
- mcp_command executable (npx, uvx, node, python, ...) — global ID
|
||||
- mcp_package npm / pypi package id parsed from args — global ID
|
||||
- env_var env variable NAME only — global ID. VALUES ARE NEVER READ.
|
||||
|
||||
Edge relations:
|
||||
- contains file -> mcp_server
|
||||
- references mcp_server -> mcp_command
|
||||
- references mcp_server -> mcp_package
|
||||
- requires_env mcp_server -> env_var (new relation; distinguishes
|
||||
env dependencies from generic refs)
|
||||
|
||||
Security:
|
||||
- Env var VALUES are never read, persisted, labelled, or surfaced. Only env
|
||||
var NAMES become nodes. (`env: {"API_KEY": "sk-..."}` -> node "API_KEY" only.)
|
||||
- File size capped at 1 MiB (matches extract_json).
|
||||
- All labels go through `sanitize_label` (control characters stripped, length
|
||||
capped) before emission.
|
||||
- Args are NOT persisted as nodes/edges to avoid leaking paths or secrets that
|
||||
some servers embed as positional args.
|
||||
|
||||
Cross-config emergent edges:
|
||||
Because `mcp_command`, `mcp_package`, and `env_var` nodes use global IDs (no
|
||||
per-file stem prefix), the same package or env var across two MCP configs
|
||||
produces shared nodes — naturally surfacing "what configs depend on this
|
||||
thing?" via graph traversal. Server nodes ARE stem-scoped so two configs
|
||||
declaring different servers under the same key (e.g., both have "filesystem")
|
||||
do not collide.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import unicodedata
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from graphify.ids import make_id as _shared_make_id
|
||||
from graphify.security import sanitize_label
|
||||
|
||||
|
||||
MCP_CONFIG_FILENAMES: frozenset[str] = frozenset({
|
||||
".mcp.json",
|
||||
"claude_desktop_config.json",
|
||||
"mcp.json",
|
||||
"mcp_servers.json",
|
||||
})
|
||||
|
||||
_MAX_BYTES = 1_048_576 # 1 MiB — same cap as extract_json
|
||||
_MAX_SERVERS_PER_FILE = 200 # generous; flags pathological configs
|
||||
|
||||
|
||||
def is_mcp_config_path(path: Path) -> bool:
|
||||
"""Return True when ``path`` is a recognised MCP config filename."""
|
||||
return path.name in MCP_CONFIG_FILENAMES
|
||||
|
||||
|
||||
def extract_mcp_config(path: Path) -> dict[str, Any]:
|
||||
"""Parse an MCP config file into Graphify nodes and edges.
|
||||
|
||||
Behaviour matches other extractors in `extract.py`:
|
||||
- returns ``{"nodes": [...], "edges": [...]}`` on success
|
||||
- returns ``{"nodes": [], "edges": [], "error": "<reason>"}`` on parse
|
||||
failure, oversize file, or missing ``mcpServers`` map
|
||||
"""
|
||||
try:
|
||||
with path.open("rb") as fh:
|
||||
raw = fh.read(_MAX_BYTES + 1)
|
||||
except OSError as exc:
|
||||
return {"nodes": [], "edges": [], "error": f"mcp_ingest read error: {exc}"}
|
||||
|
||||
if len(raw) > _MAX_BYTES:
|
||||
return {"nodes": [], "edges": [], "error": "mcp config too large to index"}
|
||||
|
||||
try:
|
||||
text = raw.decode("utf-8")
|
||||
except UnicodeDecodeError as exc:
|
||||
return {"nodes": [], "edges": [], "error": f"mcp_ingest decode error: {exc}"}
|
||||
|
||||
try:
|
||||
doc = json.loads(text)
|
||||
except json.JSONDecodeError as exc:
|
||||
return {"nodes": [], "edges": [], "error": f"mcp_ingest json error: {exc}"}
|
||||
|
||||
if not isinstance(doc, dict):
|
||||
return {"nodes": [], "edges": [], "error": "mcp_ingest: root is not an object"}
|
||||
|
||||
servers = doc.get("mcpServers")
|
||||
if not isinstance(servers, dict):
|
||||
# Some tools nest the map (e.g., {"mcp": {"servers": {...}}}). Try one
|
||||
# well-known alternate shape but do not search exhaustively.
|
||||
nested = doc.get("mcp")
|
||||
if isinstance(nested, dict):
|
||||
servers = nested.get("servers")
|
||||
if not isinstance(servers, dict):
|
||||
return {"nodes": [], "edges": [], "error": "mcp_ingest: no mcpServers map"}
|
||||
|
||||
str_path = str(path)
|
||||
file_nid = _make_id(str_path)
|
||||
nodes: list[dict[str, Any]] = []
|
||||
edges: list[dict[str, Any]] = []
|
||||
seen_node_ids: set[str] = set()
|
||||
seen_edge_keys: set[tuple[str, str, str]] = set()
|
||||
|
||||
_add_node(
|
||||
nodes, seen_node_ids,
|
||||
nid=file_nid,
|
||||
label=path.name,
|
||||
kind="mcp_config_file",
|
||||
source_file=str_path,
|
||||
line=1,
|
||||
)
|
||||
|
||||
file_stem = _file_stem(path)
|
||||
server_count = 0
|
||||
for server_name, spec in servers.items():
|
||||
if not isinstance(server_name, str) or not server_name:
|
||||
continue
|
||||
if not isinstance(spec, dict):
|
||||
# Skip non-object server entries silently — the broken entry is
|
||||
# the user's, not ours.
|
||||
continue
|
||||
if server_count >= _MAX_SERVERS_PER_FILE:
|
||||
break
|
||||
server_count += 1
|
||||
_emit_server(
|
||||
server_name=server_name,
|
||||
spec=spec,
|
||||
file_nid=file_nid,
|
||||
file_stem=file_stem,
|
||||
source_file=str_path,
|
||||
nodes=nodes,
|
||||
edges=edges,
|
||||
seen_node_ids=seen_node_ids,
|
||||
seen_edge_keys=seen_edge_keys,
|
||||
)
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
|
||||
|
||||
def _emit_server(
|
||||
*,
|
||||
server_name: str,
|
||||
spec: dict[str, Any],
|
||||
file_nid: str,
|
||||
file_stem: str,
|
||||
source_file: str,
|
||||
nodes: list[dict[str, Any]],
|
||||
edges: list[dict[str, Any]],
|
||||
seen_node_ids: set[str],
|
||||
seen_edge_keys: set[tuple[str, str, str]],
|
||||
) -> None:
|
||||
"""Emit nodes/edges for one entry under ``mcpServers``."""
|
||||
server_nid = _make_id(file_stem, "mcp_server", server_name)
|
||||
_add_node(
|
||||
nodes, seen_node_ids,
|
||||
nid=server_nid,
|
||||
label=server_name,
|
||||
kind="mcp_server",
|
||||
source_file=source_file,
|
||||
line=1, # JSON doesn't expose line numbers without a parser pass
|
||||
)
|
||||
_add_edge(
|
||||
edges, seen_edge_keys,
|
||||
source=file_nid,
|
||||
target=server_nid,
|
||||
relation="contains",
|
||||
source_file=source_file,
|
||||
line=1,
|
||||
)
|
||||
|
||||
command = spec.get("command")
|
||||
if isinstance(command, str) and command.strip():
|
||||
cmd_label = command.strip()
|
||||
cmd_nid = _make_id("mcp_command", cmd_label)
|
||||
_add_node(
|
||||
nodes, seen_node_ids,
|
||||
nid=cmd_nid,
|
||||
label=cmd_label,
|
||||
kind="mcp_command",
|
||||
source_file=source_file,
|
||||
line=1,
|
||||
)
|
||||
_add_edge(
|
||||
edges, seen_edge_keys,
|
||||
source=server_nid,
|
||||
target=cmd_nid,
|
||||
relation="references",
|
||||
source_file=source_file,
|
||||
line=1,
|
||||
context="command",
|
||||
)
|
||||
|
||||
args = spec.get("args")
|
||||
if isinstance(args, list):
|
||||
package = _detect_package_from_args(args)
|
||||
if package:
|
||||
pkg_nid = _make_id("mcp_package", package)
|
||||
_add_node(
|
||||
nodes, seen_node_ids,
|
||||
nid=pkg_nid,
|
||||
label=package,
|
||||
kind="mcp_package",
|
||||
source_file=source_file,
|
||||
line=1,
|
||||
)
|
||||
_add_edge(
|
||||
edges, seen_edge_keys,
|
||||
source=server_nid,
|
||||
target=pkg_nid,
|
||||
relation="references",
|
||||
source_file=source_file,
|
||||
line=1,
|
||||
context="package",
|
||||
)
|
||||
|
||||
env = spec.get("env")
|
||||
if isinstance(env, dict):
|
||||
# ONLY KEYS. Values may contain secrets and are never read here.
|
||||
for env_name in env.keys():
|
||||
if not isinstance(env_name, str) or not env_name:
|
||||
continue
|
||||
env_nid = _make_id("env_var", env_name)
|
||||
_add_node(
|
||||
nodes, seen_node_ids,
|
||||
nid=env_nid,
|
||||
label=env_name,
|
||||
kind="env_var",
|
||||
source_file=source_file,
|
||||
line=1,
|
||||
)
|
||||
_add_edge(
|
||||
edges, seen_edge_keys,
|
||||
source=server_nid,
|
||||
target=env_nid,
|
||||
relation="requires_env",
|
||||
source_file=source_file,
|
||||
line=1,
|
||||
)
|
||||
|
||||
|
||||
# ── Package detection from args ───────────────────────────────────────────────
|
||||
|
||||
# Patterns observed in real MCP server configs:
|
||||
# ["-y", "@modelcontextprotocol/server-filesystem", "/data"] (npx)
|
||||
# ["-y", "@org/pkg@1.2.3"]
|
||||
# ["mcp-server-fetch"] (uvx / python)
|
||||
# ["mcp-server-time", "--local-timezone=UTC"]
|
||||
# ["@scoped/some-mcp"] (pnpx)
|
||||
# ["mcp-server-fetch"] (uvx direct)
|
||||
_NPM_PKG_RE = re.compile(r"^@[a-z0-9][a-z0-9._-]*/[a-z0-9][a-z0-9._-]*(?:@[\w.\-+]+)?$")
|
||||
_PY_MCP_PKG_RE = re.compile(r"^[a-z0-9][a-z0-9._-]*-mcp(?:-[a-z0-9._-]+)?$|^mcp-[a-z0-9][a-z0-9._-]*$")
|
||||
_ARG_FLAG_RE = re.compile(r"^-{1,2}\w")
|
||||
|
||||
|
||||
def _detect_package_from_args(args: list[Any]) -> str | None:
|
||||
"""Return the first arg that looks like an npm or pypi package id, else None.
|
||||
|
||||
Skips short flags (-y, --yes) and option arguments (--local-timezone=UTC).
|
||||
"""
|
||||
for raw in args:
|
||||
if not isinstance(raw, str):
|
||||
continue
|
||||
arg = raw.strip()
|
||||
if not arg or _ARG_FLAG_RE.match(arg):
|
||||
continue
|
||||
if _NPM_PKG_RE.match(arg):
|
||||
return _strip_version(arg)
|
||||
if _PY_MCP_PKG_RE.match(arg):
|
||||
return arg
|
||||
return None
|
||||
|
||||
|
||||
def _strip_version(pkg: str) -> str:
|
||||
"""Drop the ``@version`` suffix from an npm package id, preserving the scope.
|
||||
|
||||
Scoped: ``@scope/name`` or ``@scope/name@1.2.3`` — there are at most two
|
||||
``@`` chars; the second is the version separator.
|
||||
Unscoped: ``name`` or ``name@1.2.3``.
|
||||
"""
|
||||
if pkg.startswith("@"):
|
||||
version_at = pkg.find("@", 1)
|
||||
return pkg if version_at == -1 else pkg[:version_at]
|
||||
version_at = pkg.find("@")
|
||||
return pkg if version_at == -1 else pkg[:version_at]
|
||||
|
||||
|
||||
# ── Node / edge construction (Graphify schema) ────────────────────────────────
|
||||
|
||||
|
||||
def _add_node(
|
||||
nodes: list[dict[str, Any]],
|
||||
seen: set[str],
|
||||
*,
|
||||
nid: str,
|
||||
label: str,
|
||||
kind: str,
|
||||
source_file: str,
|
||||
line: int,
|
||||
) -> None:
|
||||
"""Append a node if not already present. ``kind`` is metadata, not file_type."""
|
||||
if not nid or nid in seen:
|
||||
return
|
||||
seen.add(nid)
|
||||
nodes.append({
|
||||
"id": nid,
|
||||
"label": sanitize_label(label),
|
||||
"file_type": "code",
|
||||
"source_file": source_file,
|
||||
"source_location": f"L{line}",
|
||||
"metadata": {"mcp_kind": kind},
|
||||
})
|
||||
|
||||
|
||||
def _add_edge(
|
||||
edges: list[dict[str, Any]],
|
||||
seen: set[tuple[str, str, str]],
|
||||
*,
|
||||
source: str,
|
||||
target: str,
|
||||
relation: str,
|
||||
source_file: str,
|
||||
line: int,
|
||||
context: str | None = None,
|
||||
) -> None:
|
||||
"""Append an edge if (source, target, relation) is not already present."""
|
||||
if not source or not target or source == target:
|
||||
return
|
||||
key = (source, target, relation)
|
||||
if key in seen:
|
||||
return
|
||||
seen.add(key)
|
||||
edge: dict[str, Any] = {
|
||||
"source": source,
|
||||
"target": target,
|
||||
"relation": relation,
|
||||
"confidence": "EXTRACTED",
|
||||
"confidence_score": 1.0,
|
||||
"source_file": source_file,
|
||||
"source_location": f"L{line}",
|
||||
"weight": 1.0,
|
||||
}
|
||||
if context:
|
||||
edge["context"] = context
|
||||
edges.append(edge)
|
||||
|
||||
|
||||
# ── ID helpers (kept local; mirror extract.py shape) ──────────────────────────
|
||||
|
||||
|
||||
def _make_id(*parts: str) -> str:
|
||||
"""Build a stable node ID via the single shared recipe (#1378)."""
|
||||
return _shared_make_id(*parts)
|
||||
|
||||
|
||||
# Canonical recipe imported directly (no import cycle: extractors.base imports
|
||||
# only graphify.ids), so this can no longer drift from extract._file_stem.
|
||||
from graphify.extractors.base import _file_stem # noqa: E402
|
||||
@@ -0,0 +1,212 @@
|
||||
"""Runtime compatibility probe for Graphify MultiDiGraph mode.
|
||||
|
||||
Verifies that the current NetworkX runtime supports the behaviors a future
|
||||
opt-in --multigraph build will rely on. The probe is BEHAVIOR-based, not
|
||||
version-based — both NX 3.4.2 (Py 3.10 lane) and NX 3.6.1+ (Py 3.11+ lane)
|
||||
pass. The probe result is cached for the process lifetime via lru_cache.
|
||||
|
||||
No call sites added yet; downstream multigraph PRs will gate on
|
||||
require_multigraph_capabilities() before enabling MDG mode.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from functools import lru_cache
|
||||
import sys
|
||||
from typing import Any
|
||||
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CapabilityCheck:
|
||||
name: str
|
||||
ok: bool
|
||||
detail: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MultigraphCapabilityResult:
|
||||
python_version: str
|
||||
networkx_version: str
|
||||
checks: tuple[CapabilityCheck, ...]
|
||||
|
||||
@property
|
||||
def ok(self) -> bool:
|
||||
return all(check.ok for check in self.checks)
|
||||
|
||||
@property
|
||||
def failed(self) -> tuple[CapabilityCheck, ...]:
|
||||
return tuple(check for check in self.checks if not check.ok)
|
||||
|
||||
def error_message(self) -> str:
|
||||
if self.ok:
|
||||
return (
|
||||
"Graphify MultiDiGraph capability probe passed "
|
||||
f"(Python {self.python_version}, NetworkX {self.networkx_version})."
|
||||
)
|
||||
failed = "; ".join(f"{check.name}: {check.detail}" for check in self.failed)
|
||||
return (
|
||||
"error: --multigraph requires NetworkX keyed MultiDiGraph node-link "
|
||||
"round-trip support. "
|
||||
f"Detected Python {self.python_version}, NetworkX {self.networkx_version}. "
|
||||
f"Failed capability check(s): {failed}. "
|
||||
"Default simple graph mode remains available."
|
||||
)
|
||||
|
||||
|
||||
def _check(name: str, func: Callable[[], bool | str]) -> CapabilityCheck:
|
||||
try:
|
||||
detail = func()
|
||||
except Exception as exc:
|
||||
return CapabilityCheck(name, False, f"{type(exc).__name__}: {exc}")
|
||||
if detail is True:
|
||||
return CapabilityCheck(name, True, "ok")
|
||||
if isinstance(detail, str):
|
||||
return CapabilityCheck(name, False, detail)
|
||||
return CapabilityCheck(name, False, f"unexpected result {detail!r}")
|
||||
|
||||
|
||||
def _build_probe_graph() -> nx.MultiDiGraph:
|
||||
graph = nx.MultiDiGraph()
|
||||
graph.add_node("a", label="A")
|
||||
graph.add_node("b", label="B")
|
||||
graph.add_edge("a", "b", key="calls:a.py:L1", relation="calls", source_file="a.py")
|
||||
graph.add_edge("a", "b", key="imports:a.py:L2", relation="imports", source_file="a.py")
|
||||
return graph
|
||||
|
||||
|
||||
def _probe_keyed_parallel_edges() -> bool | str:
|
||||
graph = _build_probe_graph()
|
||||
if not graph.is_multigraph() or not graph.is_directed():
|
||||
return f"probe graph type was {type(graph).__name__}"
|
||||
if graph.number_of_edges("a", "b") != 2:
|
||||
return f"expected 2 keyed parallel edges, got {graph.number_of_edges('a', 'b')}"
|
||||
keys = set(graph["a"]["b"].keys())
|
||||
expected = {"calls:a.py:L1", "imports:a.py:L2"}
|
||||
if keys != expected:
|
||||
return f"expected keys {sorted(expected)}, got {sorted(keys)}"
|
||||
return True
|
||||
|
||||
|
||||
def _probe_node_link_round_trip() -> bool | str:
|
||||
graph = _build_probe_graph()
|
||||
data = json_graph.node_link_data(graph, edges="links")
|
||||
if data.get("multigraph") is not True:
|
||||
return f"serialized multigraph flag was {data.get('multigraph')!r}"
|
||||
if data.get("directed") is not True:
|
||||
return f"serialized directed flag was {data.get('directed')!r}"
|
||||
links = data.get("links")
|
||||
if not isinstance(links, list) or len(links) != 2:
|
||||
length = 0 if not isinstance(links, list) else len(links)
|
||||
return f"serialized links length was {length}"
|
||||
serialized_keys: set[str] = set()
|
||||
for edge in links:
|
||||
if isinstance(edge, dict):
|
||||
edge_key = edge.get("key")
|
||||
if isinstance(edge_key, str):
|
||||
serialized_keys.add(edge_key)
|
||||
expected = {"calls:a.py:L1", "imports:a.py:L2"}
|
||||
if serialized_keys != expected:
|
||||
return f"serialized keys {sorted(serialized_keys)} did not match {sorted(expected)}"
|
||||
loaded = json_graph.node_link_graph(data, edges="links")
|
||||
if not isinstance(loaded, nx.MultiDiGraph):
|
||||
return f"round-trip graph type was {type(loaded).__name__}"
|
||||
if loaded.number_of_edges("a", "b") != 2:
|
||||
return f"round-trip edge count was {loaded.number_of_edges('a', 'b')}"
|
||||
loaded_keys = set(loaded["a"]["b"].keys())
|
||||
if loaded_keys != expected:
|
||||
return f"round-trip keys {sorted(loaded_keys)} did not match {sorted(expected)}"
|
||||
return True
|
||||
|
||||
|
||||
def _probe_duplicate_key_overwrite_semantics() -> bool | str:
|
||||
graph = nx.MultiDiGraph()
|
||||
graph.add_edge("x", "y", key="same", marker="first")
|
||||
graph.add_edge("x", "y", key="same", marker="second")
|
||||
edges = list(graph.edges(keys=True, data=True))
|
||||
if len(edges) != 1:
|
||||
return f"expected one edge after duplicate-key add, got {len(edges)}"
|
||||
if edges[0][3].get("marker") != "second":
|
||||
return f"expected second attr overwrite, got {edges[0][3].get('marker')!r}"
|
||||
return True
|
||||
|
||||
|
||||
def _probe_reserved_key_attr_rejected() -> bool | str:
|
||||
"""Verify the Python language guarantee that NetworkX add_edge inherits.
|
||||
|
||||
Python forbids passing the same keyword argument twice — once explicitly
|
||||
and once via **kwargs. This probe confirms that protection still applies
|
||||
to nx.MultiDiGraph.add_edge: a future loader that builds attrs from JSON
|
||||
will be reliably protected from accidentally setting `key` via attrs while
|
||||
also passing `key=` explicitly.
|
||||
|
||||
The probe always passes on any Python 3.x version. Its purpose is to
|
||||
document the invariant explicitly in the probe suite so that if a future
|
||||
Python version relaxes this rule (extremely unlikely), the probe surfaces
|
||||
the regression.
|
||||
"""
|
||||
graph = nx.MultiDiGraph()
|
||||
attrs: dict[str, Any] = {"key": "attr-key", "relation": "calls"}
|
||||
try:
|
||||
graph.add_edge("a", "b", key="schema-key", **attrs)
|
||||
except TypeError:
|
||||
return True
|
||||
return "add_edge accepted duplicate key keyword and attr; loader must not rely on this"
|
||||
|
||||
|
||||
def _probe_remove_edges_from_two_tuple_semantics() -> bool | str:
|
||||
graph = nx.MultiDiGraph()
|
||||
graph.add_edge("a", "b", key="one")
|
||||
graph.add_edge("a", "b", key="two")
|
||||
graph.remove_edges_from([("a", "b")])
|
||||
remaining = graph.number_of_edges("a", "b")
|
||||
if remaining != 1:
|
||||
return f"expected one remaining edge after two-tuple removal, got {remaining}"
|
||||
return True
|
||||
|
||||
|
||||
def _probe_to_undirected_preserves_multigraph_type() -> bool | str:
|
||||
graph = _build_probe_graph()
|
||||
undirected = graph.to_undirected()
|
||||
undirected_view = graph.to_undirected(as_view=True)
|
||||
if not isinstance(undirected, nx.MultiGraph):
|
||||
return f"to_undirected() returned {type(undirected).__name__}"
|
||||
if not isinstance(undirected_view, nx.MultiGraph):
|
||||
return f"to_undirected(as_view=True) returned {type(undirected_view).__name__}"
|
||||
return True
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def probe_multigraph_capabilities() -> MultigraphCapabilityResult:
|
||||
checks = (
|
||||
_check("keyed_parallel_edges", _probe_keyed_parallel_edges),
|
||||
_check("node_link_edges_links_round_trip", _probe_node_link_round_trip),
|
||||
_check("duplicate_key_overwrite_semantics", _probe_duplicate_key_overwrite_semantics),
|
||||
_check("reserved_key_attr_rejected", _probe_reserved_key_attr_rejected),
|
||||
_check(
|
||||
"remove_edges_from_two_tuple_semantics",
|
||||
_probe_remove_edges_from_two_tuple_semantics,
|
||||
),
|
||||
_check(
|
||||
"to_undirected_preserves_multigraph_type",
|
||||
_probe_to_undirected_preserves_multigraph_type,
|
||||
),
|
||||
)
|
||||
return MultigraphCapabilityResult(
|
||||
python_version=(
|
||||
f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
|
||||
),
|
||||
networkx_version=nx.__version__,
|
||||
checks=checks,
|
||||
)
|
||||
|
||||
|
||||
def require_multigraph_capabilities() -> MultigraphCapabilityResult:
|
||||
result = probe_multigraph_capabilities()
|
||||
if not result.ok:
|
||||
raise RuntimeError(result.error_message())
|
||||
return result
|
||||
@@ -0,0 +1,234 @@
|
||||
"""Single source of truth for the graphify output-directory name.
|
||||
|
||||
The output directory is ``graphify-out`` by default and overridable with the
|
||||
``GRAPHIFY_OUT`` env var (worktrees or shared-output setups, #686). It accepts a
|
||||
relative name (``"graphify-out-feature"``) or an absolute path
|
||||
(``"/shared/graphify-out"``).
|
||||
|
||||
This used to be duplicated as an identical ``_GRAPHIFY_OUT`` constant in
|
||||
``__main__``, ``cache``, and ``watch``, while ``security`` and ``callflow_html``
|
||||
hardcoded the literal ``"graphify-out"`` and silently ignored the override
|
||||
(#1423). Centralising it here keeps the name in one place. The value is read
|
||||
once at import time, matching the previous per-module constants — set
|
||||
``GRAPHIFY_OUT`` before the process starts (the normal worktree/shared-output
|
||||
flow) and every reader honours it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path, PurePosixPath
|
||||
|
||||
GRAPHIFY_OUT = os.environ.get("GRAPHIFY_OUT", "graphify-out")
|
||||
|
||||
# Directory segments that, when they appear as a whole path component, mark the
|
||||
# whole path as a test location. Matched against path *segments* (not raw
|
||||
# substrings) so "src/contest.py" / "latest/x.py" / "src/greatest/x.py" do NOT
|
||||
# match — only a segment that *equals* one of these names (case-insensitively).
|
||||
_TEST_DIR_SEGMENTS = frozenset({"tests", "test", "spec", "specs", "__tests__"})
|
||||
|
||||
# Filename patterns marking a file as a test, matched against the *filename*
|
||||
# only (case-insensitive). These are conventions across ecosystems:
|
||||
# test_*.py pytest / unittest
|
||||
# *_test.* Go / Python / Rust
|
||||
# *.test.* JS/TS (jest, vitest)
|
||||
# *.spec.* / *_spec.* Jasmine / RSpec / Karma
|
||||
# *.Tests.ps1 PowerShell Pester
|
||||
# *Test.java / *Tests.cs (case-sensitive convention, handled below)
|
||||
_TEST_FILENAME_PATTERNS = (
|
||||
re.compile(r"^test_.*", re.IGNORECASE),
|
||||
re.compile(r".*_test\..+$", re.IGNORECASE),
|
||||
re.compile(r".*\.test\..+$", re.IGNORECASE),
|
||||
re.compile(r".*\.spec\..+$", re.IGNORECASE),
|
||||
re.compile(r".*_spec\..+$", re.IGNORECASE),
|
||||
re.compile(r".*\.tests\.ps1$", re.IGNORECASE),
|
||||
# Java `FooTest.java` / `FooTests.java`, C# `FooTests.cs` style. Require an
|
||||
# uppercase-led `Test`/`Tests` immediately before the extension so plain
|
||||
# words like "greatest"/"contest.cs" do not match.
|
||||
re.compile(r".*Test\.java$"),
|
||||
re.compile(r".*Tests\.java$"),
|
||||
re.compile(r".*Tests\.cs$"),
|
||||
)
|
||||
|
||||
|
||||
def _is_test_path(path: str) -> bool:
|
||||
"""Classify a source path as a test path (case-insensitive, segment-aware).
|
||||
|
||||
Shared by extract.py and symbol_resolution.py so cross-file call resolution
|
||||
treats test mocks/stubs identically. A path is a test path when:
|
||||
* any whole path segment equals a known test dir name
|
||||
(``tests``/``test``/``spec``/``specs``/``__tests__``), or
|
||||
* the filename matches a known test-file naming convention.
|
||||
|
||||
Conservative on purpose: matches segments/filenames, never raw substrings,
|
||||
so ``latest.py``, ``src/contest.py`` and ``src/greatest/x.py`` are NON-test.
|
||||
"""
|
||||
if not path:
|
||||
return False
|
||||
# Accept both POSIX and Windows separators regardless of host OS so the
|
||||
# classifier is stable across the mixed paths that flow through extraction.
|
||||
norm = str(path).replace("\\", "/")
|
||||
pure = PurePosixPath(norm)
|
||||
segments = list(pure.parts)
|
||||
# Strip a leading drive/anchor segment (e.g. "C:/") that PureWindowsPath
|
||||
# would surface; with the manual "\\"->"/" swap above PurePosixPath keeps
|
||||
# the path body intact, but guard against a Windows drive embedded as a
|
||||
# segment just in case.
|
||||
for segment in segments:
|
||||
if segment.lower() in _TEST_DIR_SEGMENTS:
|
||||
return True
|
||||
# A drive-letter colon segment like "c:" is never a test dir.
|
||||
filename = pure.name
|
||||
if not filename:
|
||||
return False
|
||||
for pattern in _TEST_FILENAME_PATTERNS:
|
||||
if pattern.match(filename):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _path_proximity_winner(call_site_file: str, candidate_files: dict[str, str]) -> str | None:
|
||||
"""Pick the candidate whose source file is closest to the call site.
|
||||
|
||||
``candidate_files`` maps candidate id -> its source_file. Returns a single
|
||||
winning candidate id, or ``None`` when no proximity tier yields a unique
|
||||
winner. Tiers, in order:
|
||||
|
||||
1. same file as the call site,
|
||||
2. same directory,
|
||||
3. longest common path-prefix (must be a strict, unique maximum).
|
||||
|
||||
Used only as a secondary tie-break after the test/non-test filter, so the
|
||||
god-node guard still holds when proximity is genuinely ambiguous.
|
||||
"""
|
||||
if not call_site_file:
|
||||
return None
|
||||
call_norm = str(call_site_file).replace("\\", "/")
|
||||
call_dir = PurePosixPath(call_norm).parent
|
||||
|
||||
# Tier 1: exact same file.
|
||||
same_file = [cid for cid, f in candidate_files.items()
|
||||
if str(f).replace("\\", "/") == call_norm]
|
||||
if len(same_file) == 1:
|
||||
return same_file[0]
|
||||
if len(same_file) > 1:
|
||||
return None # genuinely ambiguous within one file; bail
|
||||
|
||||
# Tier 2: same directory.
|
||||
same_dir = [cid for cid, f in candidate_files.items()
|
||||
if PurePosixPath(str(f).replace("\\", "/")).parent == call_dir]
|
||||
if len(same_dir) == 1:
|
||||
return same_dir[0]
|
||||
if len(same_dir) > 1:
|
||||
return None
|
||||
|
||||
# Tier 3: longest common path-prefix, computed over path segments. The
|
||||
# winner must be a strict unique maximum, else we bail (guard holds).
|
||||
call_parts = call_dir.parts
|
||||
|
||||
def _common_prefix_len(f: str) -> int:
|
||||
parts = PurePosixPath(str(f).replace("\\", "/")).parent.parts
|
||||
n = 0
|
||||
for a, b in zip(call_parts, parts):
|
||||
if a != b:
|
||||
break
|
||||
n += 1
|
||||
return n
|
||||
|
||||
scored = sorted(
|
||||
((cid, _common_prefix_len(f)) for cid, f in candidate_files.items()),
|
||||
key=lambda kv: kv[1],
|
||||
reverse=True,
|
||||
)
|
||||
if not scored:
|
||||
return None
|
||||
best = scored[0][1]
|
||||
winners = [cid for cid, score in scored if score == best]
|
||||
if len(winners) == 1 and best > 0:
|
||||
return winners[0]
|
||||
return None
|
||||
|
||||
|
||||
def disambiguate_ambiguous_candidates(
|
||||
candidates: list[str],
|
||||
candidate_files: dict[str, str],
|
||||
call_site_file: str,
|
||||
) -> str | None:
|
||||
"""Resolve an ambiguous bare-name call to one candidate, or ``None``.
|
||||
|
||||
Shared god-node tie-breaker (#1553) used by both the inline cross-file call
|
||||
pass in ``extract.py`` and ``symbol_resolution.resolve_cross_file_raw_calls``
|
||||
so the heuristics stay aligned across languages. ``candidates`` is the list
|
||||
of node ids sharing the callee's name; ``candidate_files`` maps each id ->
|
||||
its source_file. Returns the surviving candidate id only when exactly one
|
||||
survives; otherwise ``None`` (caller keeps the god-node guard / ``continue``).
|
||||
|
||||
Tie-breakers, in order:
|
||||
1. NON-TEST preference. Classify the call site and each candidate as
|
||||
test/non-test. When the call site is NON-test, drop test candidates.
|
||||
When the call site IS a test file, prefer test-local candidates
|
||||
(same file first, then any test candidate); fall back to the full set
|
||||
only if no test candidate exists.
|
||||
2. PATH PROXIMITY over whatever survived step 1.
|
||||
"""
|
||||
if not candidates:
|
||||
return None
|
||||
if len(candidates) == 1:
|
||||
return candidates[0]
|
||||
|
||||
call_is_test = _is_test_path(call_site_file)
|
||||
test_cands = [c for c in candidates if _is_test_path(candidate_files.get(c, ""))]
|
||||
nontest_cands = [c for c in candidates if c not in set(test_cands)]
|
||||
|
||||
if call_is_test:
|
||||
# Prefer a test-local definition (same file) first.
|
||||
call_norm = str(call_site_file).replace("\\", "/")
|
||||
same_file_test = [
|
||||
c for c in test_cands
|
||||
if str(candidate_files.get(c, "")).replace("\\", "/") == call_norm
|
||||
]
|
||||
if len(same_file_test) == 1:
|
||||
return same_file_test[0]
|
||||
if test_cands:
|
||||
survivors = test_cands
|
||||
else:
|
||||
survivors = nontest_cands or candidates
|
||||
else:
|
||||
# Non-test call site: drop test mocks/stubs entirely.
|
||||
survivors = nontest_cands
|
||||
|
||||
if len(survivors) == 1:
|
||||
return survivors[0]
|
||||
if not survivors:
|
||||
return None
|
||||
|
||||
# Step 2: path proximity over the survivors.
|
||||
return _path_proximity_winner(
|
||||
call_site_file,
|
||||
{c: candidate_files.get(c, "") for c in survivors},
|
||||
)
|
||||
|
||||
# Bare directory name even when GRAPHIFY_OUT is an absolute path. Used by the
|
||||
# path guards that walk parents looking for the output dir by name, and by the
|
||||
# detect scan-exclude so a custom output dir is never re-ingested as source.
|
||||
GRAPHIFY_OUT_NAME = os.path.basename(os.path.normpath(GRAPHIFY_OUT))
|
||||
|
||||
|
||||
def out_path(*parts: str) -> Path:
|
||||
"""A path inside the configured output dir, e.g. ``out_path("cache")``.
|
||||
|
||||
``Path(GRAPHIFY_OUT) / ...`` resolves correctly for both a relative name
|
||||
("graphify-out") and an absolute override ("/shared/graphify-out").
|
||||
"""
|
||||
return Path(GRAPHIFY_OUT, *parts)
|
||||
|
||||
|
||||
def default_graph_json() -> str:
|
||||
"""Default ``graph.json`` path under the configured output dir.
|
||||
|
||||
The package-wide fallback used by serve/build/benchmark/prs and the CLI read
|
||||
commands so a ``GRAPHIFY_OUT`` override is honoured everywhere, not just where
|
||||
the path is passed explicitly (#1423).
|
||||
"""
|
||||
return str(out_path("graph.json"))
|
||||
@@ -0,0 +1,142 @@
|
||||
from __future__ import annotations
|
||||
from pathlib import Path
|
||||
from graphify.extract import extract_sql
|
||||
|
||||
|
||||
def _quote_ident(name: str) -> str:
|
||||
"""Double-quote a PostgreSQL identifier, escaping embedded double-quotes."""
|
||||
return '"' + name.replace('"', '""') + '"'
|
||||
|
||||
|
||||
def introspect_postgres(dsn: str | None = None) -> dict:
|
||||
"""Connect to PostgreSQL, reconstruct DDL, and extract via extract_sql()."""
|
||||
try:
|
||||
import psycopg
|
||||
except ModuleNotFoundError:
|
||||
raise ImportError(
|
||||
"psycopg is required for --postgres. "
|
||||
"Install with: pip install 'graphify[postgres]'"
|
||||
)
|
||||
|
||||
try:
|
||||
conn = psycopg.connect(dsn or "") # empty string = PG* env vars
|
||||
except psycopg.OperationalError as exc:
|
||||
# Sanitize: strip the DSN/credentials that psycopg may embed in the
|
||||
# OperationalError message (e.g. "connection to server … failed: …\nDETAIL: …")
|
||||
msg = str(exc).split("\n")[0]
|
||||
raise ConnectionError(f"could not connect to PostgreSQL: {msg}") from None
|
||||
|
||||
try:
|
||||
conn.execute("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE READ ONLY DEFERRABLE")
|
||||
|
||||
# 1. Query tables
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
SELECT table_schema, table_name, table_type
|
||||
FROM information_schema.tables
|
||||
WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
|
||||
ORDER BY table_schema, table_name;
|
||||
""")
|
||||
tables = cur.fetchall()
|
||||
|
||||
# 2. Query views
|
||||
cur.execute("""
|
||||
SELECT table_schema, table_name, view_definition
|
||||
FROM information_schema.views
|
||||
WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
|
||||
ORDER BY table_schema, table_name;
|
||||
""")
|
||||
views = cur.fetchall()
|
||||
|
||||
# 3. Query routines (functions/procedures), including language
|
||||
cur.execute("""
|
||||
SELECT routine_schema, routine_name, routine_type,
|
||||
routine_definition, external_language
|
||||
FROM information_schema.routines
|
||||
WHERE routine_schema NOT IN ('pg_catalog', 'information_schema')
|
||||
ORDER BY routine_schema, routine_name;
|
||||
""")
|
||||
routines = cur.fetchall()
|
||||
|
||||
# 4. Query foreign keys — grouped by constraint to handle composites
|
||||
cur.execute("""
|
||||
SELECT
|
||||
tc.constraint_name,
|
||||
kcu1.table_schema,
|
||||
kcu1.table_name,
|
||||
ARRAY_AGG(kcu1.column_name ORDER BY kcu1.ordinal_position) AS columns,
|
||||
kcu2.table_schema AS foreign_table_schema,
|
||||
kcu2.table_name AS foreign_table_name,
|
||||
ARRAY_AGG(kcu2.column_name ORDER BY kcu2.ordinal_position) AS foreign_columns
|
||||
FROM
|
||||
information_schema.table_constraints AS tc
|
||||
JOIN information_schema.referential_constraints AS rc
|
||||
ON tc.constraint_name = rc.constraint_name
|
||||
AND tc.table_schema = rc.constraint_schema
|
||||
JOIN information_schema.key_column_usage AS kcu1
|
||||
ON tc.constraint_name = kcu1.constraint_name
|
||||
AND tc.table_schema = kcu1.table_schema
|
||||
JOIN information_schema.key_column_usage AS kcu2
|
||||
ON rc.unique_constraint_name = kcu2.constraint_name
|
||||
AND rc.unique_constraint_schema = kcu2.table_schema
|
||||
AND kcu1.position_in_unique_constraint = kcu2.ordinal_position
|
||||
WHERE tc.constraint_type = 'FOREIGN KEY'
|
||||
AND tc.table_schema NOT IN ('pg_catalog', 'information_schema')
|
||||
GROUP BY tc.constraint_name, kcu1.table_schema, kcu1.table_name,
|
||||
kcu2.table_schema, kcu2.table_name
|
||||
ORDER BY kcu1.table_schema, kcu1.table_name;
|
||||
""")
|
||||
fks = cur.fetchall()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
ddl = []
|
||||
|
||||
# Tables — quote identifiers to handle reserved words, hyphens, mixed-case
|
||||
for schema, name, ttype in tables:
|
||||
if ttype == "BASE TABLE":
|
||||
ddl.append(f"CREATE TABLE {_quote_ident(schema)}.{_quote_ident(name)} (id INT);")
|
||||
|
||||
# Views — real body if available, stub if NULL (permission denied)
|
||||
for schema, name, body in views:
|
||||
if body:
|
||||
ddl.append(f"CREATE VIEW {_quote_ident(schema)}.{_quote_ident(name)} AS {body};")
|
||||
else:
|
||||
ddl.append(f"CREATE VIEW {_quote_ident(schema)}.{_quote_ident(name)} AS SELECT 1;")
|
||||
|
||||
# Functions & Procedures — real body if available, stub if NULL
|
||||
# Use $gfx$ as the dollar-quote tag to avoid collision with $$ inside bodies.
|
||||
# Use external_language from the catalog; fall back to plpgsql if NULL/blank.
|
||||
for schema, name, rtype, body, ext_lang in routines:
|
||||
lang = (ext_lang or "plpgsql").lower()
|
||||
fn_sig = f"{_quote_ident(schema)}.{_quote_ident(name)}()"
|
||||
stub_body = "BEGIN SELECT 1; END;"
|
||||
if rtype in ("FUNCTION", "PROCEDURE"):
|
||||
actual_body = body if body else stub_body
|
||||
# Represent PROCEDUREs as FUNCTION so tree-sitter-sql can parse them
|
||||
ddl.append(
|
||||
f"CREATE FUNCTION {fn_sig} RETURNS void"
|
||||
f" AS $gfx$ {actual_body} $gfx$ LANGUAGE {lang};"
|
||||
)
|
||||
|
||||
# FK edges — one ALTER TABLE per constraint (handles composite FKs correctly)
|
||||
for constraint_name, t_schema, t_name, cols, r_schema, r_name, r_cols in fks:
|
||||
col_list = ", ".join(_quote_ident(c) for c in cols)
|
||||
ref_col_list = ", ".join(_quote_ident(c) for c in r_cols)
|
||||
ddl.append(
|
||||
f"ALTER TABLE {_quote_ident(t_schema)}.{_quote_ident(t_name)} "
|
||||
f"ADD CONSTRAINT {_quote_ident(constraint_name)} "
|
||||
f"FOREIGN KEY ({col_list}) REFERENCES {_quote_ident(r_schema)}.{_quote_ident(r_name)}({ref_col_list});"
|
||||
)
|
||||
|
||||
ddl_string = "\n".join(ddl)
|
||||
|
||||
# Determine host/dbname for virtual path DSN sanitization
|
||||
info = psycopg.conninfo.conninfo_to_dict(dsn or "")
|
||||
host = info.get("host", "localhost")
|
||||
dbname = info.get("dbname", "db")
|
||||
virtual_path = Path(f"postgresql://{host}/{dbname}")
|
||||
|
||||
# Pass virtual path and in-memory DDL content to extract_sql
|
||||
result = extract_sql(virtual_path, content=ddl_string)
|
||||
return result
|
||||
+757
@@ -0,0 +1,757 @@
|
||||
"""graphify prs — graph-aware PR dashboard.
|
||||
|
||||
Fast terminal overview of open PRs with CI/review state, worktree mapping,
|
||||
and optional graph-impact analysis (which communities a PR touches) and
|
||||
Opus-powered triage ranking.
|
||||
|
||||
Usage:
|
||||
graphify prs # dashboard of all open PRs
|
||||
graphify prs <number> # deep dive on one PR
|
||||
graphify prs --triage # Opus ranks your review queue
|
||||
graphify prs --worktrees # show worktree → branch → PR mapping
|
||||
graphify prs --conflicts # PRs sharing graph communities (merge-order risk)
|
||||
graphify prs --base <branch> # filter to PRs targeting this base (default: v8)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import networkx as nx
|
||||
|
||||
from graphify.paths import default_graph_json as _default_graph_json
|
||||
|
||||
|
||||
# ── ANSI colours ─────────────────────────────────────────────────────────────
|
||||
|
||||
_NO_COLOR = not sys.stdout.isatty() or os.environ.get("NO_COLOR")
|
||||
|
||||
def _c(code: str, text: str) -> str:
|
||||
if _NO_COLOR:
|
||||
return text
|
||||
return f"\033[{code}m{text}\033[0m"
|
||||
|
||||
def green(t: str) -> str: return _c("32", t)
|
||||
def red(t: str) -> str: return _c("31", t)
|
||||
def yellow(t: str) -> str: return _c("33", t)
|
||||
def cyan(t: str) -> str: return _c("36", t)
|
||||
def bold(t: str) -> str: return _c("1", t)
|
||||
def dim(t: str) -> str: return _c("2", t)
|
||||
def magenta(t: str) -> str: return _c("35", t)
|
||||
|
||||
_ANSI_RE = re.compile(r"\033\[[0-9;]*m")
|
||||
|
||||
def _pad(s: str, width: int) -> str:
|
||||
"""Pad an ANSI-colored string to visible width (strips escape codes for length calc)."""
|
||||
visible_len = len(_ANSI_RE.sub("", s))
|
||||
return s + " " * max(0, width - visible_len)
|
||||
|
||||
|
||||
# ── Data model ────────────────────────────────────────────────────────────────
|
||||
|
||||
@dataclass
|
||||
class PRInfo:
|
||||
number: int
|
||||
title: str
|
||||
branch: str
|
||||
base_branch: str
|
||||
author: str
|
||||
is_draft: bool
|
||||
review_decision: str # APPROVED | CHANGES_REQUESTED | ""
|
||||
ci_status: str # SUCCESS | FAILURE | PENDING | NONE
|
||||
updated_at: datetime
|
||||
expected_base: str = "main" # set by fetch_prs via _detect_default_branch
|
||||
worktree_path: str | None = None
|
||||
# Graph impact — populated when graph.json exists
|
||||
communities_touched: list[int] = field(default_factory=list)
|
||||
nodes_affected: int = 0
|
||||
files_changed: list[str] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def status(self) -> str:
|
||||
return _classify(self, self.expected_base)
|
||||
|
||||
@property
|
||||
def days_old(self) -> int:
|
||||
return (datetime.now(timezone.utc) - self.updated_at).days
|
||||
|
||||
@property
|
||||
def blast_radius(self) -> str:
|
||||
if not self.nodes_affected:
|
||||
return ""
|
||||
n = self.nodes_affected
|
||||
c = len(self.communities_touched)
|
||||
return f"{n} node{'s' if n != 1 else ''} / {c} communit{'ies' if c != 1 else 'y'}"
|
||||
|
||||
|
||||
# ── Classification ────────────────────────────────────────────────────────────
|
||||
|
||||
_STATUS_ORDER = ["WRONG-BASE", "CI-FAIL", "CHANGES-REQ", "DRAFT", "STALE", "PENDING", "APPROVED", "READY"]
|
||||
_STALE_DAYS = 14
|
||||
|
||||
|
||||
def _classify(pr: "PRInfo", base: str = "v8") -> str:
|
||||
if pr.base_branch != base:
|
||||
return "WRONG-BASE"
|
||||
if pr.ci_status == "FAILURE":
|
||||
return "CI-FAIL"
|
||||
if pr.review_decision == "CHANGES_REQUESTED":
|
||||
return "CHANGES-REQ"
|
||||
if pr.is_draft:
|
||||
return "DRAFT"
|
||||
if pr.days_old >= _STALE_DAYS:
|
||||
return "STALE"
|
||||
if pr.review_decision == "APPROVED":
|
||||
return "APPROVED"
|
||||
if pr.ci_status == "PENDING":
|
||||
return "PENDING"
|
||||
return "READY"
|
||||
|
||||
|
||||
def _status_color(status: str) -> str:
|
||||
return {
|
||||
"READY": green(status),
|
||||
"APPROVED": bold(green(status)),
|
||||
"CI-FAIL": red(status),
|
||||
"CHANGES-REQ": red(status),
|
||||
"WRONG-BASE": dim(status),
|
||||
"STALE": dim(status),
|
||||
"DRAFT": yellow(status),
|
||||
"PENDING": yellow(status),
|
||||
}.get(status, status)
|
||||
|
||||
|
||||
def _ci_icon(status: str) -> str:
|
||||
return {"SUCCESS": green("✓"), "FAILURE": red("✗"), "PENDING": yellow("…"), "NONE": dim("–")}.get(status, "?")
|
||||
|
||||
|
||||
# ── GitHub data fetching ──────────────────────────────────────────────────────
|
||||
|
||||
def _gh(*args: str) -> list | dict | None:
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["gh", *args],
|
||||
capture_output=True, text=True, timeout=30
|
||||
)
|
||||
if result.returncode != 0:
|
||||
return None
|
||||
return json.loads(result.stdout)
|
||||
except (subprocess.TimeoutExpired, json.JSONDecodeError, FileNotFoundError):
|
||||
return None
|
||||
|
||||
|
||||
def _detect_default_branch(repo: str | None = None) -> str:
|
||||
"""Auto-detect the repo's default branch via gh, then git, then fall back to 'main'."""
|
||||
# Try gh first — works for any repo, not just the current directory
|
||||
args = ["repo", "view", "--json", "defaultBranchRef"]
|
||||
if repo:
|
||||
args += ["--repo", repo]
|
||||
data = _gh(*args)
|
||||
if data and data.get("defaultBranchRef", {}).get("name"):
|
||||
return data["defaultBranchRef"]["name"]
|
||||
# Fall back to git symbolic-ref for the current repo
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["git", "symbolic-ref", "refs/remotes/origin/HEAD"],
|
||||
capture_output=True, text=True, timeout=5
|
||||
)
|
||||
if result.returncode == 0:
|
||||
# refs/remotes/origin/main → main
|
||||
ref = result.stdout.strip()
|
||||
return ref.split("/")[-1] if ref else "main"
|
||||
except (subprocess.TimeoutExpired, FileNotFoundError):
|
||||
pass
|
||||
return "main"
|
||||
|
||||
|
||||
_CI_FAILURE_CONCLUSIONS = frozenset({"FAILURE", "CANCELLED", "TIMED_OUT", "ACTION_REQUIRED", "STARTUP_FAILURE"})
|
||||
|
||||
|
||||
def _parse_ci(rollup: list) -> str:
|
||||
if not rollup:
|
||||
return "NONE"
|
||||
conclusions = {r.get("conclusion") for r in rollup if r.get("conclusion")}
|
||||
if conclusions & _CI_FAILURE_CONCLUSIONS:
|
||||
return "FAILURE"
|
||||
statuses = {r.get("status") for r in rollup}
|
||||
if "IN_PROGRESS" in statuses or "QUEUED" in statuses:
|
||||
return "PENDING"
|
||||
if "SUCCESS" in conclusions:
|
||||
return "SUCCESS"
|
||||
return "NONE"
|
||||
|
||||
|
||||
def fetch_prs(repo: str | None = None, base: str | None = None, limit: int = 50) -> list[PRInfo]:
|
||||
resolved_base = base or _detect_default_branch(repo)
|
||||
args = [
|
||||
"pr", "list", "--state", "open", "--limit", str(limit),
|
||||
"--json", "number,title,headRefName,baseRefName,author,isDraft,"
|
||||
"reviewDecision,statusCheckRollup,updatedAt",
|
||||
]
|
||||
if repo:
|
||||
args += ["--repo", repo]
|
||||
|
||||
raw = _gh(*args)
|
||||
if raw is None:
|
||||
raise RuntimeError("gh CLI not found or not authenticated. Run: gh auth login")
|
||||
|
||||
prs = []
|
||||
for item in raw:
|
||||
updated = datetime.fromisoformat(item["updatedAt"].replace("Z", "+00:00"))
|
||||
prs.append(PRInfo(
|
||||
number=item["number"],
|
||||
title=item["title"],
|
||||
branch=item["headRefName"],
|
||||
base_branch=item["baseRefName"],
|
||||
author=item["author"]["login"] if item.get("author") else "?",
|
||||
is_draft=item.get("isDraft", False),
|
||||
review_decision=item.get("reviewDecision") or "",
|
||||
ci_status=_parse_ci(item.get("statusCheckRollup") or []),
|
||||
updated_at=updated,
|
||||
expected_base=resolved_base,
|
||||
))
|
||||
return prs
|
||||
|
||||
|
||||
def fetch_pr_files(number: int, repo: str | None = None) -> list[str]:
|
||||
args = ["pr", "diff", str(number), "--name-only"]
|
||||
if repo:
|
||||
args += ["--repo", repo]
|
||||
try:
|
||||
result = subprocess.run(["gh", *args], capture_output=True, text=True, timeout=30)
|
||||
if result.returncode != 0:
|
||||
return []
|
||||
return [l.strip() for l in result.stdout.splitlines() if l.strip()]
|
||||
except (subprocess.TimeoutExpired, FileNotFoundError):
|
||||
return []
|
||||
|
||||
|
||||
# ── Graph-native impact (used by MCP tools — works on nx.Graph directly) ─────
|
||||
|
||||
def _path_match(graph_src: str, pr_file: str) -> bool:
|
||||
"""True if graph_src and pr_file refer to the same file (path-boundary safe)."""
|
||||
if graph_src == pr_file:
|
||||
return True
|
||||
return graph_src.endswith("/" + pr_file) or pr_file.endswith("/" + graph_src)
|
||||
|
||||
|
||||
def compute_pr_impact(files: list[str], G: "nx.Graph") -> tuple[list[int], int]:
|
||||
"""Return (communities_touched, nodes_affected) for a set of changed files.
|
||||
|
||||
Builds a file→(communities, count) index first so lookup is O(nodes + files)
|
||||
rather than O(nodes × files).
|
||||
"""
|
||||
# Build index once
|
||||
file_comms: dict[str, set[int]] = {}
|
||||
file_count: dict[str, int] = {}
|
||||
for _, data in G.nodes(data=True):
|
||||
src = data.get("source_file") or ""
|
||||
if not src:
|
||||
continue
|
||||
if src not in file_comms:
|
||||
file_comms[src] = set()
|
||||
file_count[src] = 0
|
||||
c = data.get("community")
|
||||
if c is not None:
|
||||
file_comms[src].add(int(c))
|
||||
file_count[src] += 1
|
||||
|
||||
comms: set[int] = set()
|
||||
nodes = 0
|
||||
matched: set[str] = set()
|
||||
for f in files:
|
||||
for src, src_comms in file_comms.items():
|
||||
if src not in matched and _path_match(src, f):
|
||||
comms |= src_comms
|
||||
nodes += file_count[src]
|
||||
matched.add(src)
|
||||
return sorted(comms), nodes
|
||||
|
||||
|
||||
def format_prs_text(prs: list["PRInfo"], base: str) -> str:
|
||||
"""Plain-text PR summary for MCP output (no ANSI)."""
|
||||
actionable = [p for p in prs if p.base_branch == base]
|
||||
wrong = len(prs) - len(actionable)
|
||||
lines = [f"Open PRs targeting {base}: {len(actionable)} ({wrong} on wrong base, not shown)\n"]
|
||||
for p in sorted(actionable, key=lambda x: (_STATUS_ORDER.index(x.status) if x.status in _STATUS_ORDER else 99, x.days_old)):
|
||||
impact = f" blast_radius={p.blast_radius}" if p.blast_radius else ""
|
||||
lines.append(
|
||||
f"#{p.number} [{p.status}] CI={p.ci_status} review={p.review_decision or 'none'} "
|
||||
f"age={p.days_old}d author={p.author}{impact}\n {p.title}"
|
||||
)
|
||||
return "\n\n".join(lines)
|
||||
|
||||
|
||||
# ── Worktree mapping ──────────────────────────────────────────────────────────
|
||||
|
||||
def fetch_worktrees() -> dict[str, str]:
|
||||
"""Returns {branch: worktree_path}."""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["git", "worktree", "list", "--porcelain"],
|
||||
capture_output=True, text=True, timeout=10
|
||||
)
|
||||
if result.returncode != 0:
|
||||
return {}
|
||||
except (subprocess.TimeoutExpired, FileNotFoundError):
|
||||
return {}
|
||||
|
||||
mapping: dict[str, str] = {}
|
||||
current_path = None
|
||||
for line in result.stdout.splitlines():
|
||||
if not line:
|
||||
current_path = None # blank line = record separator; reset to avoid leaking across detached HEADs
|
||||
elif line.startswith("worktree "):
|
||||
current_path = line[9:]
|
||||
elif line.startswith("branch refs/heads/") and current_path:
|
||||
mapping[line[18:]] = current_path
|
||||
return mapping
|
||||
|
||||
|
||||
# ── Graph impact analysis ─────────────────────────────────────────────────────
|
||||
|
||||
def _load_graph_json(graph_path: Path) -> dict | None:
|
||||
if not graph_path.exists():
|
||||
return None
|
||||
from graphify.security import check_graph_file_size_cap
|
||||
try:
|
||||
check_graph_file_size_cap(graph_path)
|
||||
return json.loads(graph_path.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def build_community_labels(data: dict, top_n: int = 4) -> dict[int, list[str]]:
|
||||
"""Return {community_id: [top_labels]} extracted from graph node data."""
|
||||
comm_labels: dict[int, list[str]] = defaultdict(list)
|
||||
for node in data.get("nodes", []):
|
||||
c = node.get("community")
|
||||
if c is None:
|
||||
continue
|
||||
label = node.get("label") or node.get("id") or ""
|
||||
if label:
|
||||
comm_labels[int(c)].append(label)
|
||||
return {c: labels[:top_n] for c, labels in comm_labels.items()}
|
||||
|
||||
|
||||
def attach_graph_impact(
|
||||
prs: list[PRInfo], graph_path: Path, repo: str | None = None
|
||||
) -> dict[int, list[str]]:
|
||||
"""Fetch PR file lists concurrently, compute graph impact, return community labels."""
|
||||
data = _load_graph_json(graph_path)
|
||||
if not data:
|
||||
return {}
|
||||
|
||||
# Build file → {community, node_count} index
|
||||
file_to_communities: dict[str, set[int]] = {}
|
||||
file_to_nodes: dict[str, int] = {}
|
||||
for node in data.get("nodes", []):
|
||||
src = node.get("source_file") or ""
|
||||
if not src:
|
||||
continue
|
||||
comm = node.get("community")
|
||||
if src not in file_to_communities:
|
||||
file_to_communities[src] = set()
|
||||
file_to_nodes[src] = 0
|
||||
if comm is not None:
|
||||
file_to_communities[src].add(int(comm))
|
||||
file_to_nodes[src] += 1
|
||||
|
||||
# Fetch diffs concurrently — gh pr diff is the bottleneck (network I/O)
|
||||
actionable = [pr for pr in prs if pr.status != "WRONG-BASE"]
|
||||
workers = min(8, len(actionable)) if actionable else 1
|
||||
with ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
future_to_pr = {
|
||||
pool.submit(fetch_pr_files, pr.number, repo): pr
|
||||
for pr in actionable
|
||||
}
|
||||
for fut in as_completed(future_to_pr):
|
||||
pr = future_to_pr[fut]
|
||||
try:
|
||||
files = fut.result()
|
||||
except Exception:
|
||||
files = []
|
||||
pr.files_changed = files
|
||||
|
||||
comms: set[int] = set()
|
||||
nodes = 0
|
||||
matched: set[str] = set()
|
||||
for f in files:
|
||||
for gf, gcomms in file_to_communities.items():
|
||||
if gf not in matched and _path_match(gf, f):
|
||||
comms |= gcomms
|
||||
nodes += file_to_nodes.get(gf, 0)
|
||||
matched.add(gf)
|
||||
pr.communities_touched = sorted(comms)
|
||||
pr.nodes_affected = nodes
|
||||
|
||||
return build_community_labels(data)
|
||||
|
||||
|
||||
# ── Dashboard rendering ───────────────────────────────────────────────────────
|
||||
|
||||
def _truncate(s: str, n: int) -> str:
|
||||
return s if len(s) <= n else s[:n - 1] + "…"
|
||||
|
||||
|
||||
def render_dashboard(prs: list[PRInfo], base: str = "v8", show_wrong_base: bool = False) -> None:
|
||||
actionable = [p for p in prs if p.base_branch == base]
|
||||
wrong_base = [p for p in prs if p.base_branch != base]
|
||||
|
||||
# Sort: READY first, then by status order, then by recency
|
||||
actionable.sort(key=lambda p: (_STATUS_ORDER.index(p.status) if p.status in _STATUS_ORDER else 99, p.days_old))
|
||||
|
||||
print()
|
||||
print(bold(f" graphify prs · base: {base} · {len(actionable)} PRs"))
|
||||
print()
|
||||
|
||||
if not actionable:
|
||||
print(dim(" No open PRs targeting this base branch."))
|
||||
else:
|
||||
# Header
|
||||
print(f" {'#':>4} {'CI':2} {'STATUS':13} {'UPDATED':8} {'IMPACT':22} TITLE")
|
||||
print(f" {'─'*4} {'─'*2} {'─'*13} {'─'*8} {'─'*22} {'─'*40}")
|
||||
|
||||
for pr in actionable:
|
||||
status_str = _pad(_status_color(pr.status), 13)
|
||||
ci_str = _ci_icon(pr.ci_status)
|
||||
age = f"{pr.days_old}d" if pr.days_old > 0 else "today"
|
||||
impact = _pad(dim(_truncate(pr.blast_radius, 22)), 22) if pr.blast_radius else _pad(dim("–"), 22)
|
||||
wt = f" {cyan('⬡')}" if pr.worktree_path else " "
|
||||
draft = dim(" [draft]") if pr.is_draft else ""
|
||||
title = _truncate(pr.title, 52)
|
||||
num = _pad(bold(f"#{pr.number}"), 6)
|
||||
print(f" {num}{wt} {ci_str} {status_str} {age:>6} {impact} {title}{draft}")
|
||||
|
||||
# Summary line
|
||||
by_status: dict[str, int] = {}
|
||||
for p in actionable:
|
||||
by_status[p.status] = by_status.get(p.status, 0) + 1
|
||||
|
||||
parts = []
|
||||
if by_status.get("READY"): parts.append(green(f"{by_status['READY']} ready"))
|
||||
if by_status.get("APPROVED"): parts.append(bold(green(f"{by_status['APPROVED']} approved")))
|
||||
if by_status.get("PENDING"): parts.append(yellow(f"{by_status['PENDING']} pending CI"))
|
||||
if by_status.get("CI-FAIL"): parts.append(red(f"{by_status['CI-FAIL']} CI failing"))
|
||||
if by_status.get("CHANGES-REQ"):parts.append(red(f"{by_status['CHANGES-REQ']} changes requested"))
|
||||
if by_status.get("DRAFT"): parts.append(yellow(f"{by_status['DRAFT']} draft"))
|
||||
if by_status.get("STALE"): parts.append(dim(f"{by_status['STALE']} stale"))
|
||||
|
||||
if wrong_base:
|
||||
parts.append(dim(f"{len(wrong_base)} wrong base"))
|
||||
|
||||
print()
|
||||
print(f" {' · '.join(parts)}")
|
||||
print()
|
||||
|
||||
if wrong_base and show_wrong_base:
|
||||
print(dim(f" ── {len(wrong_base)} PRs targeting wrong base ──"))
|
||||
for pr in sorted(wrong_base, key=lambda p: p.number, reverse=True):
|
||||
print(dim(f" #{pr.number:4} base={pr.base_branch:12} {_truncate(pr.title, 60)}"))
|
||||
print()
|
||||
|
||||
|
||||
def render_worktrees(prs: list[PRInfo], worktrees: dict[str, str]) -> None:
|
||||
print()
|
||||
print(bold(" Worktrees"))
|
||||
print()
|
||||
if not worktrees:
|
||||
print(dim(" No active worktrees found."))
|
||||
print()
|
||||
return
|
||||
|
||||
pr_by_branch = {p.branch: p for p in prs}
|
||||
for branch, path in sorted(worktrees.items()):
|
||||
pr = pr_by_branch.get(branch)
|
||||
if pr:
|
||||
status = _status_color(pr.status)
|
||||
print(f" {cyan(path)}")
|
||||
print(f" {dim('branch:')} {branch} -> PR {bold(f'#{pr.number}')} [{status}] {_truncate(pr.title, 50)}")
|
||||
else:
|
||||
print(f" {cyan(path)}")
|
||||
print(f" {dim('branch:')} {branch} {dim('(no open PR)')}")
|
||||
print()
|
||||
|
||||
|
||||
def render_conflicts(
|
||||
prs: list[PRInfo],
|
||||
base: str = "v8",
|
||||
community_labels: dict[int, list[str]] | None = None,
|
||||
) -> None:
|
||||
actionable = [p for p in prs if p.base_branch == base and p.communities_touched]
|
||||
if not actionable:
|
||||
print(dim("\n No graph impact data - run with a valid graph.json to detect conflicts.\n"))
|
||||
return
|
||||
|
||||
# Build community → [PRs] map
|
||||
comm_to_prs: dict[int, list[PRInfo]] = {}
|
||||
for pr in actionable:
|
||||
for c in pr.communities_touched:
|
||||
comm_to_prs.setdefault(c, []).append(pr)
|
||||
|
||||
conflicts = {c: ps for c, ps in comm_to_prs.items() if len(ps) > 1}
|
||||
if not conflicts:
|
||||
print(green("\n No community overlap between open PRs - safe to merge in any order.\n"))
|
||||
return
|
||||
|
||||
print()
|
||||
print(bold(" Community conflicts (PRs sharing the same graph community)"))
|
||||
print()
|
||||
labels = community_labels or {}
|
||||
for comm, ps in sorted(conflicts.items(), key=lambda x: -len(x[1])):
|
||||
comm_label_str = ""
|
||||
if comm in labels and labels[comm]:
|
||||
comm_label_str = dim(" — " + ", ".join(labels[comm]))
|
||||
print(f" {yellow(f'Community {comm}')}{comm_label_str} ({len(ps)} PRs overlap)")
|
||||
for pr in ps:
|
||||
print(f" #{pr.number:4} {_pad(_status_color(pr.status), 13)} {_truncate(pr.title, 55)}")
|
||||
print()
|
||||
|
||||
|
||||
def render_pr_detail(pr: PRInfo, repo: str | None = None) -> None:
|
||||
print()
|
||||
print(bold(f" PR #{pr.number} · {_status_color(pr.status)}"))
|
||||
print(f" {pr.title}")
|
||||
print()
|
||||
print(f" {dim('branch:')} {pr.branch} -> {pr.base_branch}")
|
||||
print(f" {dim('author:')} {pr.author}")
|
||||
print(f" {dim('updated:')} {pr.days_old}d ago")
|
||||
print(f" {dim('CI:')} {_ci_icon(pr.ci_status)} {pr.ci_status}")
|
||||
if pr.review_decision:
|
||||
print(f" {dim('review:')} {pr.review_decision}")
|
||||
if pr.worktree_path:
|
||||
print(f" {dim('worktree:')} {cyan(pr.worktree_path)}")
|
||||
if pr.blast_radius:
|
||||
print()
|
||||
print(f" {bold('Graph impact:')} {pr.blast_radius}")
|
||||
print(f" {dim('communities:')} {pr.communities_touched}")
|
||||
if pr.files_changed:
|
||||
print(f" {dim('files changed:')} {len(pr.files_changed)}")
|
||||
for f in pr.files_changed[:10]:
|
||||
print(f" {dim(f)}")
|
||||
if len(pr.files_changed) > 10:
|
||||
print(dim(f" … and {len(pr.files_changed) - 10} more"))
|
||||
print()
|
||||
|
||||
|
||||
# ── Triage (multi-backend) ────────────────────────────────────────────────────
|
||||
|
||||
# Best model per backend for reasoning tasks (different from extraction defaults)
|
||||
_TRIAGE_MODEL_DEFAULTS: dict[str, str] = {
|
||||
"claude": "claude-opus-4-7",
|
||||
"kimi": "kimi-k2.6",
|
||||
"openai": "gpt-4.1-mini",
|
||||
"gemini": "gemini-3-flash-preview",
|
||||
}
|
||||
|
||||
|
||||
def _resolve_triage_backend() -> tuple[str, str]:
|
||||
"""Return (backend, model) using GRAPHIFY_TRIAGE_BACKEND or first available key."""
|
||||
from graphify.llm import BACKENDS, _get_backend_api_key, _default_model_for_backend
|
||||
|
||||
explicit = os.environ.get("GRAPHIFY_TRIAGE_BACKEND", "").strip()
|
||||
if explicit in BACKENDS:
|
||||
model = (os.environ.get("GRAPHIFY_TRIAGE_MODEL")
|
||||
or _TRIAGE_MODEL_DEFAULTS.get(explicit)
|
||||
or _default_model_for_backend(explicit))
|
||||
return explicit, model
|
||||
|
||||
for b in ("claude", "kimi", "openai", "gemini"):
|
||||
if _get_backend_api_key(b):
|
||||
model = (os.environ.get("GRAPHIFY_TRIAGE_MODEL")
|
||||
or _TRIAGE_MODEL_DEFAULTS.get(b)
|
||||
or _default_model_for_backend(b))
|
||||
return b, model
|
||||
|
||||
import shutil
|
||||
if shutil.which("claude"):
|
||||
return "claude-cli", "claude-code-plan"
|
||||
|
||||
return "ollama", _default_model_for_backend("ollama")
|
||||
|
||||
|
||||
def triage_with_opus(prs: list[PRInfo], base: str) -> None:
|
||||
try:
|
||||
from graphify.llm import BACKENDS, _get_backend_api_key
|
||||
except ImportError:
|
||||
print(red(" graphify.llm not available - cannot run triage."), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
candidates = [p for p in prs if p.base_branch == base and p.status not in ("WRONG-BASE", "STALE")]
|
||||
if not candidates:
|
||||
print(dim(" No actionable PRs to triage."))
|
||||
return
|
||||
|
||||
lines = []
|
||||
for pr in candidates:
|
||||
impact = f", blast_radius={pr.blast_radius}" if pr.blast_radius else ""
|
||||
lines.append(
|
||||
f"PR #{pr.number} [{pr.status}] CI={pr.ci_status} review={pr.review_decision or 'none'} "
|
||||
f"age={pr.days_old}d author={pr.author}{impact}\n title: {pr.title}"
|
||||
)
|
||||
|
||||
prompt = (
|
||||
"You are a senior engineer helping triage a PR review queue. "
|
||||
"Given these open PRs, rank them by review priority for the repo maintainer. "
|
||||
"For each PR give: priority number, one sentence on what action to take and why. "
|
||||
"Be direct and specific. Format each as: #<number> — <action>.\n\n"
|
||||
+ "\n\n".join(lines)
|
||||
)
|
||||
|
||||
try:
|
||||
backend, model = _resolve_triage_backend()
|
||||
except Exception as e:
|
||||
print(red(f" Could not resolve triage backend: {e}"), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
print()
|
||||
print(bold(" Triage") + dim(f" ({backend} / {model})"))
|
||||
print()
|
||||
|
||||
try:
|
||||
if backend == "claude":
|
||||
import anthropic
|
||||
client = anthropic.Anthropic(api_key=_get_backend_api_key("claude"))
|
||||
with client.messages.stream(
|
||||
model=model, max_tokens=1024,
|
||||
messages=[{"role": "user", "content": prompt}],
|
||||
) as stream:
|
||||
print(" ", end="", flush=True)
|
||||
for text in stream.text_stream:
|
||||
print(text.replace("\n", "\n "), end="", flush=True)
|
||||
print("\n")
|
||||
|
||||
elif backend in ("kimi", "openai", "gemini", "ollama"):
|
||||
from openai import OpenAI
|
||||
cfg = BACKENDS[backend]
|
||||
api_key = _get_backend_api_key(backend) or "ollama"
|
||||
client = OpenAI(api_key=api_key, base_url=cfg.get("base_url", ""))
|
||||
with client.chat.completions.create(
|
||||
model=model, max_tokens=1024, stream=True,
|
||||
messages=[{"role": "user", "content": prompt}],
|
||||
) as stream:
|
||||
print(" ", end="", flush=True)
|
||||
for chunk in stream:
|
||||
delta = chunk.choices[0].delta.content if chunk.choices else None
|
||||
if delta:
|
||||
print(delta.replace("\n", "\n "), end="", flush=True)
|
||||
print("\n")
|
||||
|
||||
elif backend == "claude-cli":
|
||||
import platform as _platform, shutil as _shutil, subprocess as _sp
|
||||
_claude = "claude"
|
||||
if _platform.system() == "Windows":
|
||||
_claude = _shutil.which("claude.cmd") or _shutil.which("claude") or "claude"
|
||||
proc = _sp.run(
|
||||
[_claude, "-p", "--no-session-persistence"],
|
||||
input=prompt, capture_output=True, text=True, timeout=120,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
print(red(f" claude -p failed: {proc.stderr.strip()[:300]}"), file=sys.stderr)
|
||||
else:
|
||||
try:
|
||||
result = json.loads(proc.stdout).get("result") or proc.stdout
|
||||
except json.JSONDecodeError:
|
||||
result = proc.stdout
|
||||
for line in result.splitlines():
|
||||
print(f" {line}")
|
||||
print()
|
||||
|
||||
except Exception as e:
|
||||
print(f"\n\n {red(f'Triage failed: {e}')}", file=sys.stderr)
|
||||
|
||||
|
||||
# ── Entry point ───────────────────────────────────────────────────────────────
|
||||
|
||||
def cmd_prs(argv: list[str]) -> None:
|
||||
base: str | None = None # auto-detected from repo if not given
|
||||
repo: str | None = None
|
||||
do_triage = False
|
||||
do_worktrees = False
|
||||
do_conflicts = False
|
||||
show_wrong_base = False
|
||||
pr_number: int | None = None
|
||||
graph_path = Path(_default_graph_json())
|
||||
|
||||
i = 0
|
||||
while i < len(argv):
|
||||
arg = argv[i]
|
||||
if arg == "--triage":
|
||||
do_triage = True
|
||||
elif arg == "--worktrees":
|
||||
do_worktrees = True
|
||||
elif arg == "--conflicts":
|
||||
do_conflicts = True
|
||||
elif arg == "--wrong-base":
|
||||
show_wrong_base = True
|
||||
elif arg in ("--base", "-b") and i + 1 < len(argv):
|
||||
base = argv[i + 1]; i += 1
|
||||
elif arg.startswith("--base="):
|
||||
base = arg.split("=", 1)[1]
|
||||
elif arg in ("--repo", "-R") and i + 1 < len(argv):
|
||||
repo = argv[i + 1]; i += 1
|
||||
elif arg.startswith("--graph="):
|
||||
graph_path = Path(arg.split("=", 1)[1])
|
||||
elif arg == "--graph" and i + 1 < len(argv):
|
||||
graph_path = Path(argv[i + 1]); i += 1
|
||||
elif arg.lstrip("#").isdigit():
|
||||
pr_number = int(arg.lstrip("#"))
|
||||
elif arg in ("-h", "--help"):
|
||||
print(__doc__)
|
||||
return
|
||||
i += 1
|
||||
|
||||
if base is None:
|
||||
base = _detect_default_branch(repo)
|
||||
|
||||
try:
|
||||
prs = fetch_prs(repo=repo, base=base)
|
||||
except RuntimeError as e:
|
||||
print(red(f" Error: {e}"), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
worktrees = fetch_worktrees()
|
||||
for pr in prs:
|
||||
pr.worktree_path = worktrees.get(pr.branch)
|
||||
|
||||
# Graph impact is expensive (concurrent gh pr diff calls) — only fetch when
|
||||
# the user actually needs it: deep dive, triage, and conflict detection.
|
||||
community_labels: dict[int, list[str]] = {}
|
||||
needs_impact = graph_path.exists() and (pr_number is not None or do_triage or do_conflicts)
|
||||
if needs_impact:
|
||||
community_labels = attach_graph_impact(prs, graph_path, repo)
|
||||
|
||||
if pr_number is not None:
|
||||
match = next((p for p in prs if p.number == pr_number), None)
|
||||
if not match:
|
||||
print(red(f" PR #{pr_number} not found in open PRs."), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
render_pr_detail(match, repo)
|
||||
return
|
||||
|
||||
if do_triage:
|
||||
render_dashboard(prs, base, show_wrong_base)
|
||||
triage_with_opus(prs, base)
|
||||
return
|
||||
|
||||
if do_worktrees:
|
||||
render_worktrees(prs, worktrees)
|
||||
return
|
||||
|
||||
if do_conflicts:
|
||||
render_dashboard(prs, base, show_wrong_base)
|
||||
render_conflicts(prs, base, community_labels)
|
||||
return
|
||||
|
||||
render_dashboard(prs, base, show_wrong_base)
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Query logging for graphify — append-only JSONL, fail-silent."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
_NODES_RE = re.compile(r"(\d+)\s+nodes?\s+found")
|
||||
|
||||
|
||||
def _log_path() -> Path | None:
|
||||
if os.environ.get("GRAPHIFY_QUERY_LOG_DISABLE", "").lower() in ("1", "true", "yes"):
|
||||
return None
|
||||
override = os.environ.get("GRAPHIFY_QUERY_LOG", "").strip()
|
||||
if override:
|
||||
return Path(override).expanduser()
|
||||
return Path.home() / ".cache" / "graphify-queries.log"
|
||||
|
||||
|
||||
def _log_responses() -> bool:
|
||||
return os.environ.get("GRAPHIFY_QUERY_LOG_RESPONSES", "").lower() in ("1", "true", "yes")
|
||||
|
||||
|
||||
def nodes_from_result(result: str) -> int | None:
|
||||
m = _NODES_RE.search(result or "")
|
||||
return int(m.group(1)) if m else None
|
||||
|
||||
|
||||
def log_query(
|
||||
*,
|
||||
kind: str,
|
||||
question: str,
|
||||
corpus: str,
|
||||
result: str | None = None,
|
||||
nodes_returned: int | None = None,
|
||||
duration_ms: float | None = None,
|
||||
**extra: Any,
|
||||
) -> None:
|
||||
"""Append one JSONL record to the query log. Never raises."""
|
||||
try:
|
||||
path = _log_path()
|
||||
if path is None:
|
||||
return
|
||||
if nodes_returned is None and result is not None:
|
||||
nodes_returned = nodes_from_result(result)
|
||||
rec: dict[str, Any] = {
|
||||
"ts": datetime.now(timezone.utc).isoformat(),
|
||||
"kind": kind,
|
||||
"question": question,
|
||||
"corpus": corpus,
|
||||
"nodes_returned": nodes_returned,
|
||||
}
|
||||
if result is not None:
|
||||
rec["result_chars"] = len(result)
|
||||
if duration_ms is not None:
|
||||
rec["duration_ms"] = round(duration_ms, 3)
|
||||
for k, v in extra.items():
|
||||
if v is not None:
|
||||
rec[k] = v
|
||||
if result is not None and _log_responses():
|
||||
rec["response"] = result
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with path.open("a", encoding="utf-8") as fh:
|
||||
fh.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,882 @@
|
||||
"""Deterministic "work memory" reflection over graphify-out/memory/.
|
||||
|
||||
`graphify reflect` reads the Q&A memory docs that `graphify save-result` files back
|
||||
into the graph, aggregates their outcome signals (useful / dead_end / corrected), and
|
||||
writes a single lessons artifact an agent can load at the start of the next session:
|
||||
|
||||
- **Preferred sources** — nodes corroborated by multiple ``useful`` answers.
|
||||
- **Tentative** — nodes seen useful only once (not yet corroborated).
|
||||
- **Contested** — nodes with both positive and negative signals; recency decides.
|
||||
- **Known dead ends** — questions/sources marked ``dead_end``; don't re-derive them.
|
||||
- **Corrections** — answers the user corrected, and what the right answer was.
|
||||
|
||||
Source nodes are scored, not counted: each citation contributes a signed,
|
||||
time-decayed value (``useful`` positive, ``dead_end``/``corrected`` negative, with a
|
||||
half-life so a fresh dead end outweighs a months-old useful). A node is only promoted
|
||||
to "preferred" once corroborated by enough distinct results; one save can't mint a
|
||||
trusted lesson. When a graph is in hand, source nodes that no longer exist are dropped.
|
||||
|
||||
It is deterministic: no LLM, stable sort orders, byte-stable output for a given input
|
||||
and a given ``now``. When a graph (`graph.json` + `.graphify_analysis.json`) is available
|
||||
the lessons are also grouped by community label; without it they degrade to a single
|
||||
flat section.
|
||||
|
||||
The artifact lands at ``graphify-out/reflections/LESSONS.md`` rather than inside the wiki
|
||||
because ``graphify export wiki`` deletes every ``wiki/*.md`` on each run — a lessons file
|
||||
written there would be clobbered on the next export.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from collections import Counter
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from graphify.ingest import OUTCOMES
|
||||
from graphify.paths import GRAPHIFY_OUT_NAME
|
||||
|
||||
_UNCATEGORIZED = "Uncategorized"
|
||||
|
||||
# Derived experiential layer written alongside graph.json (a SIDECAR, kept
|
||||
# separate from the durable structural truth in graph.json — no learning_*
|
||||
# fields are ever stamped into the graph itself). Read-surface annotations are
|
||||
# merged in at display time from this file.
|
||||
LEARNING_SIDECAR_NAME = ".graphify_learning.json"
|
||||
_LEARNING_SCHEMA_VERSION = 1
|
||||
_PROVENANCE_CAP = 5 # most-recent (question, date, outcome) entries per node
|
||||
|
||||
# Scoring defaults (both exposed as CLI flags).
|
||||
_DEFAULT_HALF_LIFE_DAYS = 30.0 # a signal's weight halves every 30 days
|
||||
_DEFAULT_MIN_CORROBORATION = 2 # distinct useful results needed to "prefer" a node
|
||||
|
||||
# Rounding for the signed score keeps sort order and the contested verdict stable
|
||||
# across platforms (C pow can differ in the last ULP).
|
||||
_SCORE_NDIGITS = 9
|
||||
|
||||
|
||||
# --- frontmatter parsing -------------------------------------------------------
|
||||
#
|
||||
# save_query_result writes a tiny, hand-built YAML subset (no PyYAML dependency),
|
||||
# so we parse the same subset by hand rather than adding a dependency: scalar
|
||||
# `key: "value"` lines and a `source_nodes: ["a", "b"]` flow list. Anything we
|
||||
# don't recognise is ignored, so foreign .md files in memory/ are skipped cleanly.
|
||||
|
||||
_SCALAR_RE = re.compile(r'^([A-Za-z_][\w-]*):\s*"(.*)"\s*$')
|
||||
_LIST_RE = re.compile(r"^([A-Za-z_][\w-]*):\s*\[(.*)\]\s*$")
|
||||
_DQ_ITEM_RE = re.compile(r'"((?:[^"\\]|\\.)*)"')
|
||||
|
||||
|
||||
def _yaml_unescape(s: str) -> str:
|
||||
"""Reverse the double-quoted escaping that ingest._yaml_str applies."""
|
||||
out: list[str] = []
|
||||
i = 0
|
||||
simple = {"n": "\n", "r": "\r", "t": "\t", "0": "\0", '"': '"', "\\": "\\",
|
||||
"L": "\u2028", "P": "\u2029"} # YAML line/paragraph separators
|
||||
while i < len(s):
|
||||
ch = s[i]
|
||||
if ch == "\\" and i + 1 < len(s):
|
||||
nxt = s[i + 1]
|
||||
if nxt in simple:
|
||||
out.append(simple[nxt])
|
||||
i += 2
|
||||
continue
|
||||
if nxt == "x" and i + 3 < len(s):
|
||||
try:
|
||||
out.append(chr(int(s[i + 2:i + 4], 16)))
|
||||
i += 4
|
||||
continue
|
||||
except ValueError:
|
||||
pass
|
||||
if nxt == "u" and i + 5 < len(s):
|
||||
try:
|
||||
out.append(chr(int(s[i + 2:i + 6], 16)))
|
||||
i += 6
|
||||
continue
|
||||
except ValueError:
|
||||
pass
|
||||
out.append(ch)
|
||||
i += 1
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def parse_memory_doc(text: str) -> dict[str, Any] | None:
|
||||
"""Parse the frontmatter of a memory doc into a dict, or None if it has none.
|
||||
|
||||
Returns the recognised fields (``type``, ``date``, ``question``, ``outcome``,
|
||||
``correction``, ``source_nodes``). ``source_nodes`` is always a list.
|
||||
"""
|
||||
if not text.startswith("---"):
|
||||
return None
|
||||
lines = text.splitlines()
|
||||
if not lines or lines[0].strip() != "---":
|
||||
return None
|
||||
fields: dict[str, Any] = {"source_nodes": []}
|
||||
for line in lines[1:]:
|
||||
if line.strip() == "---":
|
||||
break
|
||||
m = _LIST_RE.match(line)
|
||||
if m and m.group(1) == "source_nodes":
|
||||
fields["source_nodes"] = [
|
||||
_yaml_unescape(item) for item in _DQ_ITEM_RE.findall(m.group(2))
|
||||
]
|
||||
continue
|
||||
m = _SCALAR_RE.match(line)
|
||||
if m:
|
||||
key, val = m.group(1), _yaml_unescape(m.group(2))
|
||||
if key in ("type", "date", "question", "outcome", "correction", "contributor"):
|
||||
fields[key] = val
|
||||
return fields
|
||||
|
||||
|
||||
def load_memory_docs(memory_dir: Path) -> list[dict[str, Any]]:
|
||||
"""Parse every memory doc under ``memory_dir``, sorted by date then filename.
|
||||
|
||||
Each record is the parsed frontmatter plus ``_path`` (the source file). Docs
|
||||
without recognisable frontmatter (foreign .md files, the LESSONS.md artifact)
|
||||
are skipped.
|
||||
"""
|
||||
memory_dir = Path(memory_dir)
|
||||
if not memory_dir.exists():
|
||||
return []
|
||||
docs: list[dict[str, Any]] = []
|
||||
for path in sorted(memory_dir.glob("*.md")):
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8")
|
||||
except (OSError, UnicodeDecodeError):
|
||||
continue
|
||||
parsed = parse_memory_doc(text)
|
||||
if parsed is None:
|
||||
continue
|
||||
parsed["_path"] = path.name
|
||||
docs.append(parsed)
|
||||
# Stable order: by (date, filename) so output is deterministic across runs.
|
||||
docs.sort(key=lambda d: (d.get("date", ""), d["_path"]))
|
||||
return docs
|
||||
|
||||
|
||||
# --- graph / community lookup (optional) ---------------------------------------
|
||||
|
||||
|
||||
def _load_node_community(graph_path: Path, analysis_path: Path,
|
||||
labels_path: Path) -> dict[str, str] | None:
|
||||
"""Build a lookup from node id AND node label -> community label, or None if the
|
||||
graph isn't available.
|
||||
|
||||
Mirrors how `graphify export wiki` reads graph.json + .graphify_analysis.json +
|
||||
.graphify_labels.json. Community membership in the analysis sidecar is keyed by
|
||||
node id, but `save-result` cites nodes by label, so both are mapped — otherwise a
|
||||
cited ``build_from_json()`` never finds its community and every lesson collapses
|
||||
into Uncategorized. Best-effort: any missing/unparseable artifact disables grouping.
|
||||
"""
|
||||
if not graph_path.exists() or not analysis_path.exists():
|
||||
return None
|
||||
try:
|
||||
analysis = json.loads(analysis_path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
communities = analysis.get("communities", {})
|
||||
if not communities:
|
||||
return None
|
||||
labels: dict[str, str] = {}
|
||||
if labels_path.exists():
|
||||
try:
|
||||
labels = json.loads(labels_path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
labels = {}
|
||||
# id -> label from the graph, so a label-form citation resolves to a community too.
|
||||
id_to_label: dict[str, str] = {}
|
||||
try:
|
||||
gdata = json.loads(graph_path.read_text(encoding="utf-8"))
|
||||
for n in gdata.get("nodes", []):
|
||||
if isinstance(n, dict) and n.get("id") is not None and n.get("label") is not None:
|
||||
id_to_label[str(n["id"])] = str(n["label"])
|
||||
except (OSError, ValueError):
|
||||
id_to_label = {}
|
||||
# Sorted cid iteration + setdefault makes any label collision resolve
|
||||
# deterministically (smallest community id wins).
|
||||
node_community: dict[str, str] = {}
|
||||
for cid in sorted(communities, key=str):
|
||||
label = labels.get(str(cid)) or labels.get(cid) or f"Community {cid}"
|
||||
for nid in communities[cid]:
|
||||
nid = str(nid)
|
||||
node_community.setdefault(nid, label)
|
||||
nlabel = id_to_label.get(nid)
|
||||
if nlabel is not None:
|
||||
node_community.setdefault(nlabel, label)
|
||||
return node_community
|
||||
|
||||
|
||||
def _load_known_nodes(graph_path: Path) -> set[str] | None:
|
||||
"""The set of node ids AND labels in the current graph, or None if unavailable.
|
||||
|
||||
Used to drop source nodes from lessons once the code they pointed at is gone
|
||||
(deleted/renamed) — a stale lesson shouldn't keep getting recommended. Both ids
|
||||
and labels are collected because `save-result` records source nodes by their
|
||||
human-readable label (what an agent cites, e.g. ``build_from_json()``), while
|
||||
graph nodes are keyed by id (e.g. ``module_build_from_json``). Matching on either
|
||||
keeps a still-present node and only drops one that survives under neither name —
|
||||
indexing ids alone silently dropped every label-form citation (the common case).
|
||||
"""
|
||||
try:
|
||||
data = json.loads(Path(graph_path).read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
nodes = data.get("nodes")
|
||||
if not isinstance(nodes, list):
|
||||
return None
|
||||
known: set[str] = set()
|
||||
for n in nodes:
|
||||
if not isinstance(n, dict):
|
||||
continue
|
||||
if n.get("id") is not None:
|
||||
known.add(str(n["id"]))
|
||||
if n.get("label") is not None:
|
||||
known.add(str(n["label"]))
|
||||
return known or None
|
||||
|
||||
|
||||
def _doc_community(nodes: list[str],
|
||||
node_community: dict[str, str] | None) -> str:
|
||||
"""The community a doc belongs to: the plurality community of its source nodes.
|
||||
|
||||
Ties break to the lexicographically-smallest label, so the result is
|
||||
deterministic regardless of source-node order. Docs with no resolvable
|
||||
community (no source nodes, or no graph) fall into the Uncategorized bucket.
|
||||
"""
|
||||
if not node_community:
|
||||
return _UNCATEGORIZED
|
||||
labels = [node_community[n] for n in nodes if n in node_community]
|
||||
if not labels:
|
||||
return _UNCATEGORIZED
|
||||
counts = Counter(labels)
|
||||
# Highest count wins; on a tie, the smaller label (most-negative count first,
|
||||
# then ascending label) — a plain min() over (-count, label).
|
||||
return min(counts.items(), key=lambda kv: (-kv[1], kv[0]))[0]
|
||||
|
||||
|
||||
# --- scoring helpers -----------------------------------------------------------
|
||||
|
||||
|
||||
def _parse_dt(date_str: str) -> datetime | None:
|
||||
"""Parse an ISO date/datetime to an aware UTC datetime, or None if unparseable."""
|
||||
if not date_str:
|
||||
return None
|
||||
try:
|
||||
dt = datetime.fromisoformat(date_str)
|
||||
except ValueError:
|
||||
return None
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=timezone.utc)
|
||||
return dt
|
||||
|
||||
|
||||
def _decay(date_str: str, now: datetime, half_life_days: float) -> float:
|
||||
"""Time-decay weight in (0, 1]: halves every ``half_life_days``.
|
||||
|
||||
Undated/unparseable signals keep full weight (1.0); future-dated ones are
|
||||
clamped to age 0 (also 1.0).
|
||||
"""
|
||||
dt = _parse_dt(date_str)
|
||||
if dt is None or half_life_days <= 0:
|
||||
return 1.0
|
||||
age_days = max(0.0, (now - dt).total_seconds() / 86400.0)
|
||||
return 0.5 ** (age_days / half_life_days)
|
||||
|
||||
|
||||
# --- aggregation ---------------------------------------------------------------
|
||||
|
||||
|
||||
def _empty_bucket() -> dict[str, Any]:
|
||||
return {
|
||||
"counts": {k: 0 for k in (*OUTCOMES, "unmarked")},
|
||||
# node -> running signed, time-decayed score
|
||||
"node_score": {},
|
||||
# node -> distinct positive / negative result counts (for corroboration)
|
||||
"node_pos": Counter(),
|
||||
"node_neg": Counter(),
|
||||
# node -> most recent event date seen (for the contested verdict line)
|
||||
"node_last": {},
|
||||
# node -> list of (date, question, outcome) for useful/corrected citations.
|
||||
# Feeds the sidecar overlay's per-node provenance; never read by LESSONS.md,
|
||||
# so it doesn't touch the aggregate's public shape.
|
||||
"node_provenance": {},
|
||||
"dead_ends": [],
|
||||
"corrections": [],
|
||||
}
|
||||
|
||||
|
||||
def _record_node(bucket: dict[str, Any], node: str, sign: int,
|
||||
weight: float, date: str, *, outcome: str | None = None,
|
||||
question: str = "") -> None:
|
||||
bucket["node_score"][node] = bucket["node_score"].get(node, 0.0) + sign * weight
|
||||
if sign > 0:
|
||||
bucket["node_pos"][node] += 1
|
||||
elif sign < 0:
|
||||
bucket["node_neg"][node] += 1
|
||||
if date > bucket["node_last"].get(node, ""):
|
||||
bucket["node_last"][node] = date
|
||||
# Provenance: only useful/corrected events are recorded (the experiential
|
||||
# trail an agent cares about — what cited this node, and how it turned out).
|
||||
if outcome in ("useful", "corrected"):
|
||||
bucket["node_provenance"].setdefault(node, []).append(
|
||||
(date, question, outcome))
|
||||
|
||||
|
||||
def _finalize_sources(bucket: dict[str, Any],
|
||||
min_corroboration: int) -> dict[str, list]:
|
||||
"""Split a bucket's scored nodes into preferred / tentative / contested lists."""
|
||||
preferred, tentative, contested = [], [], []
|
||||
for node in bucket["node_score"]:
|
||||
pos = bucket["node_pos"][node]
|
||||
neg = bucket["node_neg"][node]
|
||||
score = round(bucket["node_score"][node], _SCORE_NDIGITS)
|
||||
if pos and neg:
|
||||
verdict = "useful" if score > 0 else "dead end" if score < 0 else "even"
|
||||
contested.append({"node": node, "pos": pos, "neg": neg,
|
||||
"score": score, "verdict": verdict,
|
||||
"last": bucket["node_last"].get(node, "")})
|
||||
elif pos: # positive-only
|
||||
entry = {"node": node, "n": pos, "score": score}
|
||||
(preferred if pos >= min_corroboration else tentative).append(entry)
|
||||
# negative-only nodes are surfaced via the dead-ends questions, not here.
|
||||
preferred.sort(key=lambda e: (-e["score"], e["node"]))
|
||||
tentative.sort(key=lambda e: (-e["score"], e["node"]))
|
||||
contested.sort(key=lambda e: (-e["score"], e["node"]))
|
||||
return {"preferred": preferred, "tentative": tentative, "contested": contested}
|
||||
|
||||
|
||||
def _dedupe_by_question(items: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""Collapse repeated questions to one entry. Docs are processed oldest-first, so
|
||||
the last write per question wins (recency — e.g. the most recent correction text).
|
||||
Output is deterministically ordered by (date, question). Without this, saving the
|
||||
same Q&A twice duplicated lines in the dead-ends / corrections lists, even though
|
||||
node scoring already dedups by node.
|
||||
"""
|
||||
latest: dict[str, dict[str, Any]] = {}
|
||||
for it in items:
|
||||
latest[it.get("question", "")] = it
|
||||
return sorted(latest.values(),
|
||||
key=lambda it: (it.get("date", ""), it.get("question", "")))
|
||||
|
||||
|
||||
def aggregate_lessons(docs: list[dict[str, Any]],
|
||||
node_community: dict[str, str] | None = None,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
half_life_days: float = _DEFAULT_HALF_LIFE_DAYS,
|
||||
min_corroboration: int = _DEFAULT_MIN_CORROBORATION,
|
||||
known_nodes: set[str] | None = None) -> dict[str, Any]:
|
||||
"""Aggregate parsed memory docs into a deterministic lessons structure.
|
||||
|
||||
``now`` anchors the time-decay (pass it explicitly for byte-stable output).
|
||||
``known_nodes`` (when given) gates out source nodes no longer in the graph.
|
||||
Returns ``{"total", "counts", "min_corroboration", "preferred", "tentative",
|
||||
"contested", "dead_ends", "corrections", "by_community"}``; ``by_community`` is
|
||||
empty unless a graph is supplied.
|
||||
"""
|
||||
if now is None:
|
||||
now = datetime.now(timezone.utc)
|
||||
elif now.tzinfo is None:
|
||||
now = now.replace(tzinfo=timezone.utc)
|
||||
|
||||
overall = _empty_bucket()
|
||||
by_community: dict[str, dict[str, Any]] = {}
|
||||
|
||||
for doc in docs:
|
||||
outcome = doc.get("outcome")
|
||||
date = doc.get("date", "")
|
||||
# One event per node per doc; drop nodes the graph no longer knows about.
|
||||
raw = doc.get("source_nodes", [])
|
||||
nodes = list(dict.fromkeys(
|
||||
n for n in raw if known_nodes is None or n in known_nodes))
|
||||
community = _doc_community(nodes, node_community)
|
||||
bucket = by_community.setdefault(community, _empty_bucket())
|
||||
|
||||
sign = 1 if outcome == "useful" else -1 if outcome in ("dead_end", "corrected") else 0
|
||||
weight = _decay(date, now, half_life_days) if sign else 0.0
|
||||
|
||||
for target in (overall, bucket):
|
||||
target["counts"][outcome if outcome in OUTCOMES else "unmarked"] += 1
|
||||
if sign:
|
||||
for n in nodes:
|
||||
_record_node(target, n, sign, weight, date,
|
||||
outcome=outcome, question=doc.get("question", ""))
|
||||
if outcome == "dead_end":
|
||||
target["dead_ends"].append(
|
||||
{"question": doc.get("question", ""), "nodes": nodes, "date": date})
|
||||
elif outcome == "corrected":
|
||||
target["corrections"].append(
|
||||
{"question": doc.get("question", ""),
|
||||
"correction": doc.get("correction", ""), "date": date})
|
||||
|
||||
# Only surface per-community grouping when a graph was actually supplied;
|
||||
# without one every doc falls into Uncategorized and the section would just
|
||||
# duplicate the flat "Lessons" block.
|
||||
community_out: dict[str, dict[str, Any]] = {}
|
||||
if node_community:
|
||||
community_out = {
|
||||
label: {"counts": b["counts"], **_finalize_sources(b, min_corroboration),
|
||||
"dead_ends": _dedupe_by_question(b["dead_ends"]),
|
||||
"corrections": _dedupe_by_question(b["corrections"])}
|
||||
for label, b in by_community.items()
|
||||
}
|
||||
|
||||
return {
|
||||
"total": len(docs),
|
||||
"counts": overall["counts"],
|
||||
"min_corroboration": min_corroboration,
|
||||
**_finalize_sources(overall, min_corroboration),
|
||||
"dead_ends": _dedupe_by_question(overall["dead_ends"]),
|
||||
"corrections": _dedupe_by_question(overall["corrections"]),
|
||||
"by_community": community_out,
|
||||
# Private: per-node (date, question, outcome) trail for the sidecar
|
||||
# overlay's provenance. Underscore-prefixed and not rendered by
|
||||
# render_lessons_md, so the public aggregate shape is unchanged.
|
||||
"_node_provenance": overall["node_provenance"],
|
||||
}
|
||||
|
||||
|
||||
# --- rendering -----------------------------------------------------------------
|
||||
|
||||
|
||||
def _render_bucket(out: list[str], data: dict[str, Any], k: int) -> None:
|
||||
preferred = data["preferred"]
|
||||
tentative = data["tentative"]
|
||||
contested = data["contested"]
|
||||
dead_ends = data["dead_ends"]
|
||||
corrections = data["corrections"]
|
||||
|
||||
if preferred:
|
||||
out += [f"**Preferred sources** — corroborated by ≥{k} useful results; "
|
||||
"start here.", ""]
|
||||
for e in preferred:
|
||||
out.append(f"- `{e['node']}` ({e['n']}× useful)")
|
||||
out.append("")
|
||||
if tentative:
|
||||
out += [f"**Tentative** — useful in fewer than {k} results; verify before "
|
||||
"relying.", ""]
|
||||
for e in tentative:
|
||||
out.append(f"- `{e['node']}` ({e['n']}× useful)")
|
||||
out.append("")
|
||||
if contested:
|
||||
out += ["**Contested** — mixed signals; recency decides.", ""]
|
||||
for e in contested:
|
||||
day = e["last"][:10]
|
||||
verdict = ("evenly split" if e["verdict"] == "even"
|
||||
else f"recency leans **{e['verdict']}**")
|
||||
out.append(
|
||||
f"- `{e['node']}` — {e['pos']}× useful, {e['neg']}× "
|
||||
f"dead end/corrected → {verdict}"
|
||||
+ (f" (latest {day})" if day else ""))
|
||||
out.append("")
|
||||
if dead_ends:
|
||||
out += ["**Known dead ends** — led nowhere; don't re-derive.", ""]
|
||||
for d in dead_ends:
|
||||
nodes = ", ".join(f"`{n}`" for n in d["nodes"])
|
||||
out.append(f"- \"{d['question']}\"" + (f" — {nodes}" if nodes else ""))
|
||||
out.append("")
|
||||
if corrections:
|
||||
out += ["**Corrections** — do these differently.", ""]
|
||||
for c in corrections:
|
||||
out.append(f"- \"{c['question']}\" → {c['correction']}")
|
||||
out.append("")
|
||||
if not (preferred or tentative or contested or dead_ends or corrections):
|
||||
out += ["_No marked outcomes yet._", ""]
|
||||
|
||||
|
||||
def render_lessons_md(agg: dict[str, Any]) -> str:
|
||||
"""Render the aggregate into the deterministic LESSONS.md markdown body."""
|
||||
c = agg["counts"]
|
||||
k = agg.get("min_corroboration", _DEFAULT_MIN_CORROBORATION)
|
||||
out: list[str] = [
|
||||
"# Lessons",
|
||||
"",
|
||||
f"_Auto-generated by `graphify reflect` from {agg['total']} session "
|
||||
f"{'memory' if agg['total'] == 1 else 'memories'} in graphify-out/memory/. "
|
||||
"Deterministic; no LLM. Use for orientation — verify before relying, and "
|
||||
"revisit dead ends if the code has changed since._",
|
||||
"",
|
||||
"## Summary",
|
||||
"",
|
||||
f"- {c['useful']} useful · {c['dead_end']} dead ends · "
|
||||
f"{c['corrected']} corrected · {c['unmarked']} unmarked",
|
||||
"",
|
||||
"## Lessons",
|
||||
"",
|
||||
]
|
||||
_render_bucket(out, agg, k)
|
||||
|
||||
if agg["by_community"]:
|
||||
out += ["## By topic", ""]
|
||||
# Uncategorized sorts last; everything else alphabetically.
|
||||
def _topic_key(label: str) -> tuple[int, str]:
|
||||
return (1 if label == _UNCATEGORIZED else 0, label)
|
||||
for label in sorted(agg["by_community"], key=_topic_key):
|
||||
out += [f"### {label}", ""]
|
||||
_render_bucket(out, agg["by_community"][label], k)
|
||||
|
||||
# Single trailing newline, no trailing whitespace lines.
|
||||
return "\n".join(out).rstrip("\n") + "\n"
|
||||
|
||||
|
||||
# --- orchestrator --------------------------------------------------------------
|
||||
|
||||
|
||||
def lessons_fresh(out_path: Path, memory_dir: Path,
|
||||
graph_path: Path | None = None,
|
||||
analysis_path: Path | None = None,
|
||||
labels_path: Path | None = None) -> bool:
|
||||
"""True if ``out_path`` exists and is at least as new as every input that
|
||||
feeds it (the memory docs, and the graph/sidecars when one is used).
|
||||
|
||||
Lets ``graphify reflect --if-stale`` skip a redundant run — e.g. when the git
|
||||
post-commit hook just regenerated ``LESSONS.md`` and an agent then runs reflect
|
||||
again at the start of a session. A missing output is never fresh (it must be
|
||||
built). Mtime-based and best-effort; it only gates whether to *recompute*, not
|
||||
what the recomputation produces (that stays deterministic).
|
||||
"""
|
||||
out_path = Path(out_path)
|
||||
try:
|
||||
out_mtime = out_path.stat().st_mtime
|
||||
except OSError:
|
||||
return False # missing/unreadable -> must build
|
||||
newest = 0.0
|
||||
md = Path(memory_dir)
|
||||
if md.is_dir():
|
||||
for f in md.glob("*.md"):
|
||||
try:
|
||||
newest = max(newest, f.stat().st_mtime)
|
||||
except OSError:
|
||||
pass
|
||||
for input_path in (graph_path, analysis_path, labels_path):
|
||||
if input_path is None:
|
||||
continue
|
||||
gp = Path(input_path)
|
||||
try:
|
||||
newest = max(newest, gp.stat().st_mtime)
|
||||
except OSError:
|
||||
pass
|
||||
return out_mtime >= newest
|
||||
|
||||
|
||||
def reflect(memory_dir: Path, out_path: Path,
|
||||
graph_path: Path | None = None,
|
||||
analysis_path: Path | None = None,
|
||||
labels_path: Path | None = None,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
half_life_days: float = _DEFAULT_HALF_LIFE_DAYS,
|
||||
min_corroboration: int = _DEFAULT_MIN_CORROBORATION,
|
||||
) -> tuple[Path, dict[str, Any]]:
|
||||
"""Scan ``memory_dir``, write the lessons doc to ``out_path``, return (path, agg).
|
||||
|
||||
If ``graph_path`` is given lessons are grouped by community and source nodes no
|
||||
longer in the graph are dropped; otherwise the doc is a single flat section.
|
||||
"""
|
||||
docs = load_memory_docs(memory_dir)
|
||||
|
||||
node_community = None
|
||||
known_nodes = None
|
||||
if graph_path is not None:
|
||||
graph_path = Path(graph_path)
|
||||
analysis_path = Path(analysis_path) if analysis_path else (
|
||||
graph_path.parent / ".graphify_analysis.json")
|
||||
labels_path = Path(labels_path) if labels_path else (
|
||||
graph_path.parent / ".graphify_labels.json")
|
||||
node_community = _load_node_community(graph_path, analysis_path, labels_path)
|
||||
known_nodes = _load_known_nodes(graph_path)
|
||||
|
||||
if now is None:
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
agg = aggregate_lessons(docs, node_community, now=now,
|
||||
half_life_days=half_life_days,
|
||||
min_corroboration=min_corroboration,
|
||||
known_nodes=known_nodes)
|
||||
out_path = Path(out_path)
|
||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
out_path.write_text(render_lessons_md(agg), encoding="utf-8")
|
||||
|
||||
# Also project a derived experiential sidecar next to graph.json when a graph
|
||||
# is in hand. Best-effort: a sidecar failure must never break LESSONS.md.
|
||||
if graph_path is not None:
|
||||
try:
|
||||
write_learning_sidecar(agg, Path(graph_path), now=now)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return out_path, agg
|
||||
|
||||
|
||||
# --- work-memory overlay sidecar ------------------------------------------------
|
||||
#
|
||||
# A derived, experiential projection of the reflect aggregate, written next to
|
||||
# graph.json as ``.graphify_learning.json``. It carries which nodes have proven
|
||||
# preferred/tentative/contested, a code fingerprint for staleness detection, and
|
||||
# a short provenance trail. graph.json (durable structural truth) is never
|
||||
# touched — read surfaces merge this overlay in only at display time.
|
||||
|
||||
|
||||
def _build_id_label_maps(graph_path: Path) -> tuple[dict[str, str], dict[str, list[str]],
|
||||
dict[str, dict[str, Any]]]:
|
||||
"""From graph.json build:
|
||||
|
||||
- ``id_set``: id -> id (every node id, so an id-form citation resolves to itself)
|
||||
- ``label_to_ids``: label -> [ids] (so a label-form citation can be resolved,
|
||||
and ambiguity — one label, many ids — can be detected and skipped)
|
||||
- ``node_by_id``: id -> node dict (for source_file lookup)
|
||||
|
||||
Best-effort; an unreadable/garbage graph yields empty maps.
|
||||
"""
|
||||
id_set: dict[str, str] = {}
|
||||
label_to_ids: dict[str, list[str]] = {}
|
||||
node_by_id: dict[str, dict[str, Any]] = {}
|
||||
try:
|
||||
data = json.loads(Path(graph_path).read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return id_set, label_to_ids, node_by_id
|
||||
for n in data.get("nodes", []):
|
||||
if not isinstance(n, dict) or n.get("id") is None:
|
||||
continue
|
||||
nid = str(n["id"])
|
||||
id_set[nid] = nid
|
||||
node_by_id[nid] = n
|
||||
label = n.get("label")
|
||||
if label is not None:
|
||||
label_to_ids.setdefault(str(label), []).append(nid)
|
||||
return id_set, label_to_ids, node_by_id
|
||||
|
||||
|
||||
def _resolve_canonical_id(cited: str, id_set: dict[str, str],
|
||||
label_to_ids: dict[str, list[str]]) -> str | None:
|
||||
"""Resolve a cited node (a label OR an id) to a single canonical node id.
|
||||
|
||||
Returns None if the citation is unresolved (stale — gone from the graph) or
|
||||
ambiguous (a label shared by >1 node id). Such citations can't be displayed
|
||||
against a single node, so the caller skips them.
|
||||
"""
|
||||
if cited in id_set:
|
||||
return id_set[cited]
|
||||
ids = label_to_ids.get(cited)
|
||||
if ids and len(ids) == 1:
|
||||
return ids[0]
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_source_path(src: str, graph_path: Path) -> Path | None:
|
||||
"""Locate a node's ``source_file`` on disk, returning an existing file or None.
|
||||
|
||||
``source_file`` is stored relative to the PROJECT root, but graph.json may
|
||||
live in ``<root>/graphify-out/`` (so its own dir is not the root) or directly
|
||||
at the root (``extract --out .``). Resolve the root in the most-likely order
|
||||
and return the first candidate where the file actually exists, so a defeated
|
||||
heuristic or a stale marker can never strand the file (every node would then
|
||||
look "changed"). The same search runs at write and read time, so the writer
|
||||
and reader resolve to the same file.
|
||||
|
||||
Order: the committed ``.graphify_root`` marker (#686/#1423 — authoritative for
|
||||
an absolute/elsewhere ``GRAPHIFY_OUT`` override); then the layout-appropriate
|
||||
root *first* — graph.json's parent's parent for the ``graphify-out`` layout,
|
||||
or graph.json's own dir for a flat layout — which avoids matching a same-named
|
||||
file one directory up; then the other of the two; then the cwd.
|
||||
"""
|
||||
if not src:
|
||||
return None
|
||||
p = Path(src)
|
||||
if p.is_absolute():
|
||||
return p if p.is_file() else None
|
||||
gp = Path(graph_path)
|
||||
out_dir = gp.parent
|
||||
candidates: list[Path] = []
|
||||
try:
|
||||
recorded = (out_dir / ".graphify_root").read_text(encoding="utf-8").strip()
|
||||
if recorded:
|
||||
candidates.append(Path(recorded))
|
||||
except (OSError, ValueError):
|
||||
pass # unreadable/non-UTF-8 marker -> fall through (best-effort)
|
||||
# Layout-appropriate root first (precision), then the other (robustness).
|
||||
if out_dir.name == GRAPHIFY_OUT_NAME:
|
||||
candidates += [out_dir.parent, out_dir]
|
||||
else:
|
||||
candidates += [out_dir, out_dir.parent]
|
||||
candidates.append(Path("."))
|
||||
seen: set[str] = set()
|
||||
for base in candidates:
|
||||
key = str(base)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
cand = base / p
|
||||
if cand.is_file():
|
||||
return cand
|
||||
return None
|
||||
|
||||
|
||||
def _content_hash(path: Path) -> str:
|
||||
"""SHA256 of file CONTENT only (no path mixed in), so the fingerprint is
|
||||
independent of which root resolved the file — write and read agree, and a
|
||||
committed sidecar stays valid across machines/checkouts."""
|
||||
import hashlib
|
||||
try:
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
|
||||
def _code_fingerprint(node: dict[str, Any] | None, graph_path: Path) -> str:
|
||||
"""Content hash of the node's ``source_file``, or '' if unavailable.
|
||||
|
||||
Coarse on purpose — a file-level hash over-flags (any edit to the file marks
|
||||
every node in it stale) rather than under-flags, which is the safe direction
|
||||
for a "re-verify" hint.
|
||||
"""
|
||||
if not node:
|
||||
return ""
|
||||
sp = _resolve_source_path(node.get("source_file") or "", graph_path)
|
||||
return _content_hash(sp) if sp is not None else ""
|
||||
|
||||
|
||||
def _provenance_for(node: str, prov_map: dict[str, list],
|
||||
fallback_outcome: str) -> list[dict[str, str]]:
|
||||
"""Most-recent-first, capped provenance entries for a node.
|
||||
|
||||
``prov_map`` is the aggregate's private per-node (date, question, outcome)
|
||||
trail. ``fallback_outcome`` covers an entry with no recorded trail (shouldn't
|
||||
happen for preferred/tentative/contested, which all have ≥1 positive event).
|
||||
"""
|
||||
events = prov_map.get(node, [])
|
||||
# Sort recent-first; (date desc, then question for a stable tiebreak).
|
||||
ordered = sorted(events, key=lambda e: (e[0], e[1]), reverse=True)
|
||||
out: list[dict[str, str]] = []
|
||||
for date, question, outcome in ordered[:_PROVENANCE_CAP]:
|
||||
out.append({"q": question, "date": date, "outcome": outcome})
|
||||
return out
|
||||
|
||||
|
||||
def build_learning_overlay(agg: dict[str, Any], graph_path: Path,
|
||||
*, now: datetime | None = None) -> dict[str, Any]:
|
||||
"""Project the reflect aggregate into the sidecar's ``{version, generated_at,
|
||||
nodes}`` structure, keyed by canonical node id.
|
||||
|
||||
Built from preferred + tentative + contested (NOT dead_ends — those stay
|
||||
query-scoped, surfaced only in the report). Citations that don't resolve to
|
||||
exactly one node id are skipped.
|
||||
"""
|
||||
if now is None:
|
||||
now = datetime.now(timezone.utc)
|
||||
elif now.tzinfo is None:
|
||||
now = now.replace(tzinfo=timezone.utc)
|
||||
|
||||
graph_path = Path(graph_path)
|
||||
id_set, label_to_ids, node_by_id = _build_id_label_maps(graph_path)
|
||||
prov_map = agg.get("_node_provenance", {})
|
||||
|
||||
# id -> entry; a canonical id can be cited under both its id and label form,
|
||||
# but the aggregate dedups per node string, so collisions here are benign and
|
||||
# resolved deterministically by iteration order (preferred, tentative, contested).
|
||||
nodes_out: dict[str, dict[str, Any]] = {}
|
||||
|
||||
def _add(entry_src: dict[str, Any], status: str) -> None:
|
||||
cited = entry_src["node"]
|
||||
cid = _resolve_canonical_id(cited, id_set, label_to_ids)
|
||||
if cid is None:
|
||||
return # ambiguous or stale — can't display against a single node
|
||||
if cid in nodes_out:
|
||||
return # first status wins (preferred > tentative > contested order)
|
||||
node = node_by_id.get(cid)
|
||||
out: dict[str, Any] = {
|
||||
"status": status,
|
||||
"score": entry_src["score"],
|
||||
"uses": entry_src.get("n", entry_src.get("pos", 0)),
|
||||
"last": entry_src.get("last", ""),
|
||||
"label": str(node.get("label", cited)) if node else str(cited),
|
||||
"source_file": str(node.get("source_file") or "") if node else "",
|
||||
"code_fingerprint": _code_fingerprint(node, graph_path),
|
||||
"provenance": _provenance_for(cited, prov_map, status),
|
||||
}
|
||||
if status == "contested":
|
||||
out["verdict"] = entry_src.get("verdict", "even")
|
||||
out["neg"] = entry_src.get("neg", 0)
|
||||
else:
|
||||
# preferred/tentative carry no contested verdict; derive `last` from
|
||||
# provenance if the finalizer didn't (positive-only buckets do track it
|
||||
# via node_last for contested only).
|
||||
if not out["last"] and out["provenance"]:
|
||||
out["last"] = out["provenance"][0]["date"]
|
||||
nodes_out[cid] = out
|
||||
|
||||
for e in agg.get("preferred", []):
|
||||
_add(e, "preferred")
|
||||
for e in agg.get("tentative", []):
|
||||
_add(e, "tentative")
|
||||
for e in agg.get("contested", []):
|
||||
_add(e, "contested")
|
||||
|
||||
return {
|
||||
"version": _LEARNING_SCHEMA_VERSION,
|
||||
"generated_at": now.isoformat(),
|
||||
"nodes": nodes_out,
|
||||
}
|
||||
|
||||
|
||||
def write_learning_sidecar(agg: dict[str, Any], graph_path: Path,
|
||||
*, now: datetime | None = None) -> Path:
|
||||
"""Write ``.graphify_learning.json`` next to ``graph_path`` deterministically.
|
||||
|
||||
Sorted keys + indent=2 so re-runs on identical input (and a fixed ``now``)
|
||||
are byte-identical. Returns the sidecar path.
|
||||
"""
|
||||
overlay = build_learning_overlay(agg, graph_path, now=now)
|
||||
sidecar = Path(graph_path).parent / LEARNING_SIDECAR_NAME
|
||||
sidecar.write_text(
|
||||
json.dumps(overlay, indent=2, sort_keys=True, ensure_ascii=False) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
return sidecar
|
||||
|
||||
|
||||
def load_learning_overlay(graph_path: Path) -> dict[str, dict[str, Any]]:
|
||||
"""Load the sidecar next to ``graph_path`` and return ``{node_id -> entry}``
|
||||
with a recomputed ``stale: bool`` per entry. Best-effort -> {} on any error.
|
||||
|
||||
Staleness: recompute ``file_hash(source_file)`` and compare to the entry's
|
||||
stored ``code_fingerprint``. Matching fingerprints -> not stale. Differing,
|
||||
missing-but-recomputable, or a vanished file -> stale (the safe, over-flagging
|
||||
direction). An entry with no stored fingerprint AND no current file is not
|
||||
marked stale (nothing to re-verify).
|
||||
"""
|
||||
sidecar = Path(graph_path).parent / LEARNING_SIDECAR_NAME
|
||||
try:
|
||||
data = json.loads(sidecar.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
nodes = data.get("nodes")
|
||||
if not isinstance(nodes, dict):
|
||||
return {}
|
||||
out: dict[str, dict[str, Any]] = {}
|
||||
for nid, entry in nodes.items():
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
merged = dict(entry)
|
||||
merged["stale"] = _is_stale(entry, graph_path)
|
||||
out[str(nid)] = merged
|
||||
return out
|
||||
|
||||
|
||||
def _is_stale(entry: dict[str, Any], graph_path: Path) -> bool:
|
||||
"""True if the node's source file changed (or vanished) since the fingerprint
|
||||
was taken. Uses the same file resolution + content hash as the writer, so a
|
||||
freshly-written verdict on unchanged code is never spuriously stale."""
|
||||
src = entry.get("source_file", "")
|
||||
if not src:
|
||||
# No file to track — nothing to re-verify.
|
||||
return False
|
||||
sp = _resolve_source_path(src, graph_path)
|
||||
if sp is None:
|
||||
return True # file gone / unfindable — re-verify
|
||||
stored = entry.get("code_fingerprint", "")
|
||||
if not stored:
|
||||
return True # had a file but never fingerprinted it -> can't trust -> stale
|
||||
return _content_hash(sp) != stored
|
||||
+171
-22
@@ -1,9 +1,73 @@
|
||||
# generate GRAPH_REPORT.md — the human-readable audit trail
|
||||
# generate GRAPH_REPORT.md - the human-readable audit trail
|
||||
from __future__ import annotations
|
||||
import re
|
||||
from datetime import date
|
||||
import networkx as nx
|
||||
|
||||
|
||||
def _safe_community_name(label: str) -> str:
|
||||
"""Mirrors export.safe_name so community hub filenames and report wikilinks always agree."""
|
||||
cleaned = re.sub(r'[\\/*?:"<>|#^[\]]', "", label.replace("\r\n", " ").replace("\r", " ").replace("\n", " ")).strip()
|
||||
cleaned = re.sub(r"\.(md|mdx|markdown)$", "", cleaned, flags=re.IGNORECASE)
|
||||
return cleaned or "unnamed"
|
||||
|
||||
|
||||
def load_learning_for_report(graph_path) -> dict | None:
|
||||
"""Assemble the report's work-memory inputs from sibling artifacts.
|
||||
|
||||
Reads the ``.graphify_learning.json`` overlay (preferred sources) next to
|
||||
``graph_path`` and re-aggregates the memory docs for the query-scoped
|
||||
dead-ends. Best-effort: returns None if neither is available, so the report
|
||||
simply omits the section. Never raises.
|
||||
"""
|
||||
from pathlib import Path as _Path
|
||||
try:
|
||||
gp = _Path(graph_path)
|
||||
from graphify.reflect import load_learning_overlay, load_memory_docs, aggregate_lessons
|
||||
overlay = load_learning_overlay(gp)
|
||||
dead_ends: list[dict] = []
|
||||
mem = gp.parent / "memory"
|
||||
if mem.is_dir():
|
||||
agg = aggregate_lessons(load_memory_docs(mem))
|
||||
dead_ends = agg.get("dead_ends", [])
|
||||
if not overlay and not dead_ends:
|
||||
return None
|
||||
return {"overlay": overlay, "dead_ends": dead_ends}
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _learning_section(lines: list, learning: dict | None, top_n: int = 10) -> None:
|
||||
"""Append the ``## Work-memory lessons`` section, or nothing when empty."""
|
||||
if not learning:
|
||||
return
|
||||
overlay = learning.get("overlay") or {}
|
||||
dead_ends = learning.get("dead_ends") or []
|
||||
preferred = [
|
||||
(nid, e) for nid, e in overlay.items()
|
||||
if isinstance(e, dict) and e.get("status") == "preferred"
|
||||
]
|
||||
# Most-corroborated first (uses desc), then by score, then id for stability.
|
||||
preferred.sort(key=lambda kv: (-kv[1].get("uses", 0),
|
||||
-float(kv[1].get("score", 0) or 0), kv[0]))
|
||||
if not preferred and not dead_ends:
|
||||
return
|
||||
lines += ["", "## Work-memory lessons"]
|
||||
if preferred:
|
||||
lines += ["", "**Preferred sources** — corroborated by past sessions; start here."]
|
||||
for nid, e in preferred[:top_n]:
|
||||
label = e.get("label") or nid
|
||||
stale = " _(code changed — re-verify)_" if e.get("stale") else ""
|
||||
lines.append(f"- `{label}` ({e.get('uses', 0)}× useful, "
|
||||
f"score={e.get('score', 0)}){stale}")
|
||||
if dead_ends:
|
||||
lines += ["", "**Known dead ends** — questions that led nowhere; don't re-derive."]
|
||||
for d in dead_ends:
|
||||
nodes = ", ".join(f"`{n}`" for n in d.get("nodes", []))
|
||||
lines.append(f"- \"{d.get('question', '')}\""
|
||||
+ (f" -> {nodes}" if nodes else ""))
|
||||
|
||||
|
||||
def generate(
|
||||
G: nx.Graph,
|
||||
communities: dict[int, list[str]],
|
||||
@@ -15,17 +79,28 @@ def generate(
|
||||
token_cost: dict,
|
||||
root: str,
|
||||
suggested_questions: list[dict] | None = None,
|
||||
min_community_size: int = 3,
|
||||
built_at_commit: str | None = None,
|
||||
learning: dict | None = None,
|
||||
) -> str:
|
||||
today = date.today().isoformat()
|
||||
|
||||
# JSON deserialization produces string keys; normalize to int so .get(cid) works.
|
||||
if community_labels:
|
||||
community_labels = {int(k) if isinstance(k, str) else k: v for k, v in community_labels.items()}
|
||||
|
||||
confidences = [d.get("confidence", "EXTRACTED") for _, _, d in G.edges(data=True)]
|
||||
total = len(confidences) or 1
|
||||
ext_pct = round(confidences.count("EXTRACTED") / total * 100)
|
||||
inf_pct = round(confidences.count("INFERRED") / total * 100)
|
||||
amb_pct = round(confidences.count("AMBIGUOUS") / total * 100)
|
||||
|
||||
inf_edges = [(u, v, d) for u, v, d in G.edges(data=True) if d.get("confidence") == "INFERRED"]
|
||||
inf_scores = [d.get("confidence_score", 0.5) for _, _, d in inf_edges]
|
||||
inf_avg = round(sum(inf_scores) / len(inf_scores), 2) if inf_scores else None
|
||||
|
||||
lines = [
|
||||
f"# Graph Report — {root} ({today})",
|
||||
f"# Graph Report - {root} ({today})",
|
||||
"",
|
||||
"## Corpus Check",
|
||||
]
|
||||
@@ -37,17 +112,49 @@ def generate(
|
||||
"- Verdict: corpus is large enough that graph structure adds value.",
|
||||
]
|
||||
|
||||
from .analyze import _is_file_node as _ifn
|
||||
non_empty = {cid: nodes for cid, nodes in communities.items()
|
||||
if any(not _ifn(G, n) for n in nodes)}
|
||||
thin_count_summary = sum(
|
||||
1 for nodes in communities.values()
|
||||
if 0 < sum(1 for n in nodes if not _ifn(G, n)) < min_community_size
|
||||
)
|
||||
shown_count = len(communities) - thin_count_summary
|
||||
|
||||
lines += [
|
||||
"",
|
||||
"## Summary",
|
||||
f"- {G.number_of_nodes()} nodes · {G.number_of_edges()} edges · {len(communities)} communities detected",
|
||||
f"- Extraction: {ext_pct}% EXTRACTED · {inf_pct}% INFERRED · {amb_pct}% AMBIGUOUS",
|
||||
f"- {G.number_of_nodes()} nodes · {G.number_of_edges()} edges · {len(communities)} communities"
|
||||
+ (f" ({shown_count} shown, {thin_count_summary} thin omitted)" if thin_count_summary else ""),
|
||||
f"- Extraction: {ext_pct}% EXTRACTED · {inf_pct}% INFERRED · {amb_pct}% AMBIGUOUS"
|
||||
+ (f" · INFERRED: {len(inf_edges)} edges (avg confidence: {inf_avg})" if inf_avg is not None else ""),
|
||||
f"- Token cost: {token_cost.get('input', 0):,} input · {token_cost.get('output', 0):,} output",
|
||||
]
|
||||
|
||||
if built_at_commit:
|
||||
lines += [
|
||||
"",
|
||||
"## Graph Freshness",
|
||||
f"- Built from commit: `{built_at_commit[:8]}`",
|
||||
"- Run `git rev-parse HEAD` and compare to check if the graph is stale.",
|
||||
"- Run `graphify update .` after code changes (no API cost).",
|
||||
]
|
||||
|
||||
# Community hub navigation - links to _COMMUNITY_*.md files in the Obsidian vault.
|
||||
# Without these, GRAPH_REPORT.md is a dead-end and the vault splits into disconnected components.
|
||||
if non_empty:
|
||||
lines += ["", "## Community Hubs (Navigation)"]
|
||||
for cid in non_empty:
|
||||
label = community_labels.get(cid, f"Community {cid}")
|
||||
safe = _safe_community_name(label)
|
||||
lines.append(f"- [[_COMMUNITY_{safe}|{label}]]")
|
||||
|
||||
lines += [
|
||||
"",
|
||||
"## God Nodes (most connected — your core abstractions)",
|
||||
"## God Nodes (most connected - your core abstractions)",
|
||||
]
|
||||
for i, node in enumerate(god_node_list, 1):
|
||||
lines.append(f"{i}. `{node['label']}` — {node['edges']} edges")
|
||||
lines.append(f"{i}. `{node['label']}` - {node['degree']} edges")
|
||||
|
||||
lines += ["", "## Surprising Connections (you probably didn't know these)"]
|
||||
if surprise_list:
|
||||
@@ -55,32 +162,67 @@ def generate(
|
||||
relation = s.get("relation", "related_to")
|
||||
note = s.get("note", "")
|
||||
files = s.get("source_files", ["", ""])
|
||||
conf = s.get("confidence", "EXTRACTED")
|
||||
cscore = s.get("confidence_score")
|
||||
if conf == "INFERRED" and cscore is not None:
|
||||
conf_tag = f"INFERRED {cscore:.2f}"
|
||||
else:
|
||||
conf_tag = conf
|
||||
sem_tag = " [semantically similar]" if relation == "semantically_similar_to" else ""
|
||||
lines += [
|
||||
f"- `{s['source']}` --{relation}--> `{s['target']}` [{s['confidence']}]",
|
||||
f"- `{s['source']}` --{relation}--> `{s['target']}` [{conf_tag}]{sem_tag}",
|
||||
f" {files[0]} → {files[1]}" + (f" _{note}_" if note else ""),
|
||||
]
|
||||
else:
|
||||
lines.append("- None detected — all connections are within the same source files.")
|
||||
lines.append("- None detected - all connections are within the same source files.")
|
||||
|
||||
lines += ["", "## Communities"]
|
||||
from .analyze import _is_file_node as _ifn
|
||||
# Circular imports surfaced from file-level dependency graph.
|
||||
from .analyze import find_import_cycles
|
||||
cycles = find_import_cycles(G)
|
||||
lines += ["", "## Import Cycles"]
|
||||
if cycles:
|
||||
for c in cycles:
|
||||
cycle = c.get("cycle", [])
|
||||
length = c.get("length", len(cycle))
|
||||
if not cycle:
|
||||
continue
|
||||
cycle_path = " -> ".join(cycle + [cycle[0]])
|
||||
lines.append(f"- {length}-file cycle: `{cycle_path}`")
|
||||
else:
|
||||
lines.append("- None detected.")
|
||||
|
||||
hyperedges = G.graph.get("hyperedges", [])
|
||||
if hyperedges:
|
||||
lines += ["", "## Hyperedges (group relationships)"]
|
||||
for h in hyperedges:
|
||||
node_labels = ", ".join(h.get("nodes", []))
|
||||
conf = h.get("confidence", "INFERRED")
|
||||
cscore = h.get("confidence_score")
|
||||
conf_tag = f"{conf} {cscore:.2f}" if cscore is not None else conf
|
||||
lines.append(f"- **{h.get('label', h.get('id', ''))}** — {node_labels} [{conf_tag}]")
|
||||
|
||||
lines += ["", f"## Communities ({len(communities)} total, {thin_count_summary} thin omitted)"]
|
||||
for cid, nodes in communities.items():
|
||||
label = community_labels.get(cid, f"Community {cid}")
|
||||
score = cohesion_scores.get(cid, 0.0)
|
||||
# Filter method/function stubs from display — they're structural noise
|
||||
# Filter method/function stubs from display - they're structural noise
|
||||
real_nodes = [n for n in nodes if not _ifn(G, n)]
|
||||
if not real_nodes:
|
||||
continue
|
||||
if len(real_nodes) < min_community_size:
|
||||
continue
|
||||
display = [G.nodes[n].get("label", n) for n in real_nodes[:8]]
|
||||
suffix = f" (+{len(real_nodes)-8} more)" if len(real_nodes) > 8 else ""
|
||||
lines += [
|
||||
"",
|
||||
f"### Community {cid} — \"{label}\"",
|
||||
f"Cohesion: {score}",
|
||||
f"### Community {cid} - \"{label}\"",
|
||||
f"Cohesion: {score:.2f}",
|
||||
f"Nodes ({len(real_nodes)}): {', '.join(display)}{suffix}",
|
||||
]
|
||||
|
||||
ambiguous = [(u, v, d) for u, v, d in G.edges(data=True) if d.get("confidence") == "AMBIGUOUS"]
|
||||
if ambiguous:
|
||||
lines += ["", "## Ambiguous Edges — Review These"]
|
||||
lines += ["", "## Ambiguous Edges - Review These"]
|
||||
for u, v, d in ambiguous:
|
||||
ul = G.nodes[u].get("label", u)
|
||||
vl = G.nodes[v].get("label", v)
|
||||
@@ -94,10 +236,14 @@ def generate(
|
||||
|
||||
isolated = [
|
||||
n for n in G.nodes()
|
||||
if G.degree(n) <= 1 and not _is_file_node(G, n) and not _is_concept_node(G, n)
|
||||
if G.degree(n) <= 1
|
||||
and not _is_file_node(G, n)
|
||||
and not _is_concept_node(G, n)
|
||||
and G.nodes[n].get("file_type") != "rationale"
|
||||
]
|
||||
thin_communities = {
|
||||
cid: nodes for cid, nodes in communities.items() if len(nodes) < 3
|
||||
cid: nodes for cid, nodes in communities.items()
|
||||
if 0 < sum(1 for n in nodes if not _is_file_node(G, n)) < 3
|
||||
}
|
||||
gap_count = len(isolated) + len(thin_communities)
|
||||
|
||||
@@ -107,16 +253,19 @@ def generate(
|
||||
isolated_labels = [G.nodes[n].get("label", n) for n in isolated[:5]]
|
||||
suffix = f" (+{len(isolated)-5} more)" if len(isolated) > 5 else ""
|
||||
lines.append(f"- **{len(isolated)} isolated node(s):** {', '.join(f'`{l}`' for l in isolated_labels)}{suffix}")
|
||||
lines.append(" These have ≤1 connection — possible missing edges or undocumented components.")
|
||||
lines.append(" These have ≤1 connection - possible missing edges or undocumented components.")
|
||||
if thin_communities:
|
||||
for cid, nodes in thin_communities.items():
|
||||
label = community_labels.get(cid, f"Community {cid}")
|
||||
node_labels = [G.nodes[n].get("label", n) for n in nodes]
|
||||
lines.append(f"- **Thin community `{label}`** ({len(nodes)} nodes): {', '.join(f'`{l}`' for l in node_labels)}")
|
||||
lines.append(" Too small to be a meaningful cluster — may be noise or needs more connections extracted.")
|
||||
lines.append(f"- **{len(thin_communities)} thin communities (<{min_community_size} nodes) omitted from report** — run `graphify query` to explore isolated nodes.")
|
||||
if amb_pct > 20:
|
||||
lines.append(f"- **High ambiguity: {amb_pct}% of edges are AMBIGUOUS.** Review the Ambiguous Edges section above.")
|
||||
|
||||
# --- Work-memory lessons (derived overlay) ---
|
||||
# Preferred sources come from the .graphify_learning.json sidecar; the
|
||||
# query-scoped dead-ends come from the reflect aggregate. Section omitted
|
||||
# entirely when neither is present, so a graph with no work-memory is
|
||||
# byte-identical to the pre-feature report.
|
||||
_learning_section(lines, learning)
|
||||
|
||||
if suggested_questions:
|
||||
lines += ["", "## Suggested Questions"]
|
||||
no_signal = len(suggested_questions) == 1 and suggested_questions[0].get("type") == "no_signal"
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Registry for cross-file, language-specific resolution passes.
|
||||
|
||||
Some call/reference edges can only be resolved with language-specific knowledge
|
||||
(receiver typing, qualified member calls, framework conventions). Historically
|
||||
these ran as a hand-wired sequence of suffix-gated
|
||||
``if <lang>_paths: try: _resolve_<lang>(...)`` blocks at the tail of
|
||||
``extract.extract()``. That pattern is the de-facto extension point for
|
||||
per-language resolution; this module formalizes it so a new language plugs in by
|
||||
registering one ``LanguageResolver`` instead of editing ``extract()``'s body.
|
||||
|
||||
This module deliberately knows nothing about any specific language — languages
|
||||
register themselves (see ``extract.py``), keeping the dependency direction one
|
||||
way (``extract`` → ``resolver_registry``) and this seam small and reviewable on
|
||||
its own, separate from the multi-thousand-line ``extract`` module.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
_LOG = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LanguageResolver:
|
||||
"""One cross-file, language-specific resolution pass.
|
||||
|
||||
``resolve`` has the signature ``(per_file, all_nodes, all_edges) -> None`` and
|
||||
mutates ``all_nodes`` / ``all_edges`` in place, matching the existing
|
||||
member-call resolvers. ``suffixes`` gates activation: the pass runs only when
|
||||
the corpus contains at least one file with one of these extensions.
|
||||
"""
|
||||
|
||||
name: str
|
||||
suffixes: frozenset
|
||||
resolve: Callable
|
||||
|
||||
|
||||
# Module-level registry, populated by callers via register(). Ordered: resolvers
|
||||
# run in registration order, preserving any required sequencing between passes.
|
||||
_REGISTRY: list[LanguageResolver] = []
|
||||
|
||||
|
||||
def register(resolver: LanguageResolver) -> LanguageResolver:
|
||||
"""Append a resolver to the global registry and return it (for inline use)."""
|
||||
_REGISTRY.append(resolver)
|
||||
return resolver
|
||||
|
||||
|
||||
def registered_resolvers() -> list[LanguageResolver]:
|
||||
"""Return a copy of the registered resolvers, in registration order."""
|
||||
return list(_REGISTRY)
|
||||
|
||||
|
||||
def run_language_resolvers(
|
||||
paths: Sequence[Path],
|
||||
per_file: list[dict],
|
||||
all_nodes: list[dict],
|
||||
all_edges: list[dict],
|
||||
*,
|
||||
resolvers: Sequence[LanguageResolver] | None = None,
|
||||
) -> None:
|
||||
"""Run every resolver whose suffix appears in ``paths``.
|
||||
|
||||
Behaviorally identical to the prior hand-wired sequence of suffix-gated,
|
||||
try/except-wrapped passes: same activation rule (suffix present), same
|
||||
failure handling (log a warning and continue to the next pass), same
|
||||
execution order (registration order).
|
||||
|
||||
``resolvers`` defaults to the global registry; tests pass an explicit list to
|
||||
exercise the driver in isolation.
|
||||
"""
|
||||
active = _REGISTRY if resolvers is None else resolvers
|
||||
suffixes_present = {p.suffix for p in paths}
|
||||
for resolver in active:
|
||||
if not (resolver.suffixes & suffixes_present):
|
||||
continue
|
||||
try:
|
||||
resolver.resolve(per_file, all_nodes, all_edges)
|
||||
except Exception as exc:
|
||||
_LOG.warning("%s resolution failed, skipping: %s", resolver.name, exc)
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Type-aware cross-file resolution for Ruby member calls.
|
||||
|
||||
Ruby has no type annotations and reuses method names heavily, so resolving
|
||||
``obj.method()`` by globally-unique name is both lossy (drops on collision) and
|
||||
unsafe (can attach to the wrong same-named method). This resolver instead uses
|
||||
the receiver's *type*, inferred at extraction time from local
|
||||
``var = ClassName.new`` bindings and carried on each member-call raw_call as
|
||||
``receiver_type``.
|
||||
|
||||
It resolves two shapes, both at EXTRACTED (1.0) confidence and only when the
|
||||
target is certain (single owning class, single owned method) — bail otherwise:
|
||||
|
||||
* ``Processor.new`` -> a ``calls`` edge to the ``Processor`` class
|
||||
* ``p.run`` where ``p`` is a ``Processor`` -> a ``calls`` edge to ``Processor#run``
|
||||
|
||||
Registered into graphify.resolver_registry and run by extract() after id
|
||||
disambiguation, so node ids and raw_call caller_nids are final.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
|
||||
def _key(label: str) -> str:
|
||||
"""Normalize a class/method label to a comparison key (drop punctuation)."""
|
||||
return re.sub(r"[^a-zA-Z0-9]+", "", str(label)).lower()
|
||||
|
||||
|
||||
def _ruby_raw_calls(per_file: list[dict]) -> list[dict]:
|
||||
calls: list[dict] = []
|
||||
for result in per_file:
|
||||
if not isinstance(result, dict):
|
||||
continue
|
||||
for rc in result.get("raw_calls", []):
|
||||
if not isinstance(rc, dict):
|
||||
continue
|
||||
sf = str(rc.get("source_file", ""))
|
||||
if sf.endswith(".rb"):
|
||||
calls.append(rc)
|
||||
return calls
|
||||
|
||||
|
||||
def resolve_ruby_member_calls(
|
||||
per_file: list[dict],
|
||||
all_nodes: list[dict],
|
||||
all_edges: list[dict],
|
||||
) -> None:
|
||||
"""Resolve Ruby ``Class.new`` and typed ``var.method`` calls by receiver type.
|
||||
|
||||
Purely additive: only emits edges the shared (name-based) call pass skips
|
||||
because they are member calls. Each emission requires a single owning class
|
||||
(god-node guard) so an ambiguous class name resolves to nothing rather than a
|
||||
wrong edge.
|
||||
"""
|
||||
node_by_id: dict[str, dict] = {n.get("id"): n for n in all_nodes}
|
||||
|
||||
# class label key -> [class node ids]; (class_node_id, method_key) -> method id
|
||||
class_def_nids: dict[str, list[str]] = {}
|
||||
method_index: dict[tuple[str, str], str] = {}
|
||||
for e in all_edges:
|
||||
if e.get("relation") != "method":
|
||||
continue
|
||||
src, tgt = e.get("source"), e.get("target")
|
||||
cnode = node_by_id.get(src)
|
||||
if cnode is not None:
|
||||
class_def_nids.setdefault(_key(cnode.get("label", "")), []).append(str(src))
|
||||
tnode = node_by_id.get(tgt)
|
||||
if tnode is not None:
|
||||
method_index[(str(src), _key(tnode.get("label", "")))] = str(tgt)
|
||||
for k in list(class_def_nids):
|
||||
class_def_nids[k] = sorted(set(class_def_nids[k]))
|
||||
|
||||
existing_pairs = {(e.get("source"), e.get("target")) for e in all_edges}
|
||||
|
||||
def _unique_class(name: str) -> str | None:
|
||||
nids = class_def_nids.get(_key(name), [])
|
||||
return nids[0] if len(nids) == 1 else None
|
||||
|
||||
def _emit(caller: str, target: str, rc: dict[str, Any]) -> None:
|
||||
if not caller or not target or caller == target:
|
||||
return
|
||||
if (caller, target) in existing_pairs:
|
||||
return
|
||||
existing_pairs.add((caller, target))
|
||||
all_edges.append({
|
||||
"source": caller,
|
||||
"target": target,
|
||||
"relation": "calls",
|
||||
"context": "call",
|
||||
"confidence": "EXTRACTED",
|
||||
"confidence_score": 1.0,
|
||||
"source_file": rc.get("source_file", ""),
|
||||
"source_location": rc.get("source_location"),
|
||||
"weight": 1.0,
|
||||
})
|
||||
|
||||
for rc in _ruby_raw_calls(per_file):
|
||||
if not rc.get("is_member_call"):
|
||||
continue
|
||||
caller = str(rc.get("caller_nid", ""))
|
||||
callee = rc.get("callee")
|
||||
if not caller or not callee:
|
||||
continue
|
||||
|
||||
# `Processor.new` -> instantiation edge to the class.
|
||||
receiver = rc.get("receiver")
|
||||
if callee == "new" and receiver and str(receiver)[:1].isupper():
|
||||
class_nid = _unique_class(str(receiver))
|
||||
if class_nid is not None:
|
||||
_emit(caller, class_nid, rc)
|
||||
continue
|
||||
|
||||
# `p.run` where p's type is known -> edge to that class's method.
|
||||
receiver_type = rc.get("receiver_type")
|
||||
if not receiver_type:
|
||||
continue
|
||||
class_nid = _unique_class(str(receiver_type))
|
||||
if class_nid is None:
|
||||
continue
|
||||
method_nid = method_index.get((class_nid, _key(str(callee))))
|
||||
if method_nid is None:
|
||||
continue
|
||||
_emit(caller, method_nid, rc)
|
||||
Loaded 100 of 664 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user