-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdgat.cpp
More file actions
3303 lines (2841 loc) · 108 KB
/
Copy pathdgat.cpp
File metadata and controls
3303 lines (2841 loc) · 108 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <cstdio>
#ifdef _WIN32
#define popen _popen
#define pclose _pclose
#endif
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <cctype>
#include <regex>
#include <filesystem>
#include <thread>
#include <mutex>
#include <atomic>
#include <functional>
#include <future>
#include <queue>
#include <chrono>
#include <memory>
#include <limits>
#include <optional>
#include <variant>
#include "inja.hpp"
#include "json.hpp"
#include "httplib.h"
#include "xxhash.h"
using namespace std;
using json = nlohmann::json;
namespace fs = std::filesystem;
class ThreadPool {
private:
vector<thread> workers;
queue<function<void()>> tasks;
mutex queue_mutex;
condition_variable condition;
bool stop_flag;
public:
explicit ThreadPool(size_t num_threads) : stop_flag(false) {
for (size_t i = 0; i < num_threads; ++i) {
workers.emplace_back([this] {
while (true) {
function<void()> task;
{
unique_lock<mutex> lock(this->queue_mutex);
this->condition.wait(lock, [this] {
return this->stop_flag || !this->tasks.empty();
});
if (this->stop_flag && this->tasks.empty()) return;
task = move(this->tasks.front());
this->tasks.pop();
}
task();
}
});
}
}
template<typename F>
auto enqueue(F&& f) -> future<typename result_of<F()>::type> {
using return_type = typename result_of<F()>::type;
auto task = make_shared<packaged_task<return_type()>>(forward<F>(f));
future<return_type> result = task->get_future();
{
unique_lock<mutex> lock(queue_mutex);
if (stop_flag) throw runtime_error("Enqueue on stopped ThreadPool");
tasks.emplace([task]() { (*task)(); });
}
condition.notify_one();
return result;
}
~ThreadPool() {
{
unique_lock<mutex> lock(queue_mutex);
stop_flag = true;
}
condition.notify_all();
for (thread& worker : workers) {
worker.join();
}
}
};
string get_language_from_ext(const string& file_path);
bool is_likely_binary_file(const string& file_path);
bool matches_dgatignore(const string& rel_path);
string sanitize_utf8(const string& input);
vector<string> extract_imports(const string& file_path, const string& content);
vector<string> extract_imports_fallback(const string& content, const string& lang);
vector<string> extract_imports_via_tree_sitter(const string& file_path, const string& content);
string normalize_import_path(const string& imp, const string& src_file);
bool is_path_in_gitignore(const string& rel_path);
string extract_assistant_text(const json& response_json);
string trim_copy(const string& input);
// using XXH128_hash_t (two uint64_t)
using digest_t = XXH128_hash_t;
digest_t fast_fingerprint(const string& file_content){
XXH3_state_t* state = XXH3_createState();
if (!state) {
throw std::runtime_error("Failed to create XXH3 state");
}
XXH3_128bits_reset(state);
XXH3_128bits_update(state, file_content.data(), file_content.size());
digest_t digest = XXH3_128bits_digest(state);
XXH3_freeState(state);
return digest;
}
void print_digest(const digest_t& d) {
std::cout << std::hex << std::setfill('0')
<< std::setw(16) << d.high64
<< std::setw(16) << d.low64
<< std::dec << "\n";
}
bool check_digests(const digest_t& d1, const digest_t& d2) {
if (d1.high64 == d2.high64 && d1.low64 == d2.low64) return true;
return false;
}
struct TreeNode {
string name;
int version; // id i use while writing dot nodes
digest_t hash; // can be used later to track file version changes, chnaged to digest_t for better hashing
string abs_path; // full path in system
string rel_path; // path from project root (this one is key)
vector<unique_ptr<TreeNode>> children;
bool is_file; // true = file, false = folder
vector<json> error_traces; // like [{"error": "...", "timestamp": "...", "solution": "..."}]
string description; // extra file context if needed later
vector<string> depends_on; // files this file depends on
vector<string> depended_by; // files that depend on this file
TreeNode(const string& name,
const string& abs_path,
const string& rel_path,
bool is_file)
: name(name),
version(0),
abs_path(abs_path),
rel_path(rel_path),
is_file(is_file) {}
};
struct DepNode {
string name;
string rel_path;
string abs_path;
string description;
bool is_file;
bool is_gitignored;
string hash;
vector<string> depends_on;
vector<string> depended_by;
DepNode() : is_file(true), is_gitignored(false) {}
};
struct DepEdge {
string from_path;
string to_path;
string import_stmt;
string description;
};
struct DepGraph {
vector<DepNode> nodes;
vector<DepEdge> edges;
unordered_map<string, int> path_to_node;
};
// notebook cell stuff — tracks individual cells and their relationships
struct NotebookCell {
int index;
string cell_type; // "code", "markdown", "raw"
string source; // concatenated source lines
int execution_count; // -1 if not executed
bool has_been_executed;
vector<string> imports; // extracted imports from this cell
vector<string> defines; // functions, classes, variables defined
vector<string> uses; // variables/functions used from other cells
vector<int> depends_on_cells; // cell indices this cell depends on
};
// parsed notebook container — holds all cells and aggregated metadata
struct ParsedNotebook {
vector<NotebookCell> cells;
int nbformat;
string kernel_name;
string language;
string code_content; // concatenated code cells only
string markdown_content; // concatenated markdown cells only
vector<string> all_imports;
bool is_valid;
string error_message;
ParsedNotebook() : nbformat(0), is_valid(false) {}
};
// forward decls for notebook parsing
ParsedNotebook parse_notebook_file(const string& abs_path);
vector<string> extract_cell_definitions(const string& source);
vector<string> extract_cell_uses(const string& source, const vector<string>& defined_in_cell);
void build_cell_dependencies(ParsedNotebook& notebook);
vector<string> extract_notebook_imports(const ParsedNotebook& notebook);
string notebook_to_description_content(const ParsedNotebook& notebook);
string extract_notebook_source_for_imports(const ParsedNotebook& notebook);
// normalize notebook source field — can be array of strings or single string
static string normalize_notebook_source(const json& source_field) {
if (source_field.is_array()) {
string result;
for (const auto& line : source_field) {
if (line.is_string()) result += line.get<string>();
}
return result;
}
if (source_field.is_string()) return source_field.get<string>();
return "";
}
// parse a .ipynb file into our ParsedNotebook struct
ParsedNotebook parse_notebook_file(const string& abs_path) {
ParsedNotebook nb;
try {
ifstream f(abs_path);
if (!f.is_open()) {
nb.error_message = "could not open file";
return nb;
}
json root = json::parse(f);
f.close();
nb.nbformat = root.value("nbformat", 0);
// grab kernel/language from metadata
if (root.contains("metadata") && root["metadata"].is_object()) {
auto& meta = root["metadata"];
if (meta.contains("kernelspec") && meta["kernelspec"].is_object()) {
nb.kernel_name = meta["kernelspec"].value("name", "");
}
if (meta.contains("language_info") && meta["language_info"].is_object()) {
nb.language = meta["language_info"].value("name", "");
}
}
if (!root.contains("cells") || !root["cells"].is_array()) {
nb.error_message = "no cells array found";
return nb;
}
for (size_t i = 0; i < root["cells"].size(); i++) {
const auto& cell = root["cells"][i];
if (!cell.is_object()) continue;
NotebookCell nc;
nc.index = static_cast<int>(i);
nc.cell_type = cell.value("cell_type", "code");
nc.source = normalize_notebook_source(cell.value("source", json("")));
// execution count — default -1 if missing
if (cell.contains("execution_count") && cell["execution_count"].is_number_integer()) {
nc.execution_count = cell["execution_count"].get<int>();
nc.has_been_executed = nc.execution_count > 0;
} else {
nc.execution_count = -1;
nc.has_been_executed = false;
}
// skip empty cells
if (trim_copy(nc.source).empty()) continue;
nb.cells.push_back(nc);
}
if (nb.cells.empty()) {
nb.error_message = "no non-empty cells";
return nb;
}
// build code_content and markdown_content
string code_acc, md_acc;
for (auto& c : nb.cells) {
if (c.cell_type == "code") {
if (!code_acc.empty()) code_acc += "\n\n";
code_acc += "# --- cell " + to_string(c.index) + " ---\n" + c.source;
} else if (c.cell_type == "markdown") {
if (!md_acc.empty()) md_acc += "\n\n";
md_acc += c.source;
}
}
nb.code_content = code_acc;
nb.markdown_content = md_acc;
// extract imports and definitions per code cell
for (auto& c : nb.cells) {
if (c.cell_type != "code") continue;
c.imports = extract_imports_fallback(c.source, "python");
c.defines = extract_cell_definitions(c.source);
}
// aggregate all imports
{
unordered_set<string> seen;
for (const auto& c : nb.cells) {
for (const auto& imp : c.imports) {
if (!seen.count(imp)) {
seen.insert(imp);
nb.all_imports.push_back(imp);
}
}
}
}
// build cross-cell dependencies
build_cell_dependencies(nb);
nb.is_valid = true;
} catch (const exception& e) {
nb.error_message = string("parse error: ") + e.what();
}
return nb;
}
// extract top-level definitions from a code cell source
vector<string> extract_cell_definitions(const string& source) {
vector<string> defs;
istringstream iss(source);
string line;
unordered_set<string> seen;
while (getline(iss, line)) {
line = trim_copy(line);
// skip comments and blank lines
if (line.empty() || line.rfind("#", 0) == 0) continue;
// def func_name(
if (line.rfind("def ", 0) == 0) {
size_t paren = line.find('(');
if (paren != string::npos) {
string name = trim_copy(line.substr(4, paren - 4));
if (!name.empty() && !seen.count(name)) {
seen.insert(name);
defs.push_back(name);
}
}
}
// class ClassName
else if (line.rfind("class ", 0) == 0) {
size_t paren = line.find('(');
size_t colon = line.find(':');
size_t end_pos = (paren != string::npos) ? min(paren, colon) : colon;
if (end_pos != string::npos && end_pos > 6) {
string name = trim_copy(line.substr(6, end_pos - 6));
if (!name.empty() && !seen.count(name)) {
seen.insert(name);
defs.push_back(name);
}
}
}
// top-level variable assignment: name = ...
else {
size_t eq = line.find('=');
if (eq != string::npos && eq > 0 && (eq + 1 < line.size()) && line[eq + 1] != '=') {
// check it's top-level (no leading whitespace)
if (!isspace(static_cast<unsigned char>(line[0]))) {
string name = trim_copy(line.substr(0, eq));
// strip possible tuple unpacking: a, b = ... → take first
size_t comma = name.find(',');
if (comma != string::npos) name = trim_copy(name.substr(0, comma));
// must be a valid identifier
if (!name.empty() && isalpha(static_cast<unsigned char>(name[0])) && !seen.count(name)) {
seen.insert(name);
defs.push_back(name);
}
}
}
}
}
return defs;
}
// simple python keyword/builtin set for filtering
static const unordered_set<string> python_keywords_builtins = {
"if", "else", "elif", "for", "while", "return", "yield", "break", "continue",
"pass", "raise", "try", "except", "finally", "with", "as", "import", "from",
"class", "def", "lambda", "global", "nonlocal", "assert", "del", "in", "not",
"and", "or", "is", "True", "False", "None", "self", "print", "len", "range",
"int", "str", "float", "list", "dict", "set", "tuple", "bool", "type",
"isinstance", "issubclass", "hasattr", "getattr", "setattr", "delattr",
"super", "property", "staticmethod", "classmethod", "abs", "all", "any",
"bin", "callable", "chr", "compile", "complex", "dir", "divmod", "enumerate",
"eval", "exec", "filter", "format", "frozenset", "hash", "help", "hex",
"id", "input", "iter", "locals", "map", "max", "min", "next", "object",
"oct", "open", "ord", "pow", "repr", "reversed", "round", "slice", "sorted",
"sum", "vars", "zip", "__name__", "__file__", "__doc__", "__init__",
};
// extract identifiers used in source that aren't defined in this cell
vector<string> extract_cell_uses(const string& source, const vector<string>& defined_in_cell) {
unordered_set<string> local_defs(defined_in_cell.begin(), defined_in_cell.end());
unordered_set<string> uses;
vector<string> result;
// simple word-boundary scan — collect identifiers
string current;
auto flush_word = [&]() {
if (current.size() >= 2 && isalpha(static_cast<unsigned char>(current[0]))) {
// skip keywords/builtins and local defs
if (!python_keywords_builtins.count(current) && !local_defs.count(current)) {
if (!uses.count(current)) {
uses.insert(current);
result.push_back(current);
}
}
}
current.clear();
};
for (char c : source) {
if (isalnum(static_cast<unsigned char>(c)) || c == '_') {
current += c;
} else {
flush_word();
}
}
flush_word();
return result;
}
// build cross-cell dependency links
void build_cell_dependencies(ParsedNotebook& notebook) {
// collect defines per cell index for quick lookup
unordered_map<int, vector<string>> defines_by_idx;
for (const auto& c : notebook.cells) {
if (c.cell_type == "code") {
defines_by_idx[c.index] = c.defines;
}
}
for (size_t i = 0; i < notebook.cells.size(); i++) {
auto& c = notebook.cells[i];
if (c.cell_type != "code") continue;
c.uses = extract_cell_uses(c.source, c.defines);
// check each use against defines from earlier cells
unordered_set<int> dep_set;
for (const auto& use : c.uses) {
for (size_t j = 0; j < i; j++) {
if (notebook.cells[j].cell_type != "code") continue;
const auto& defs = defines_by_idx[notebook.cells[j].index];
if (find(defs.begin(), defs.end(), use) != defs.end()) {
dep_set.insert(notebook.cells[j].index);
}
}
}
c.depends_on_cells.assign(dep_set.begin(), dep_set.end());
sort(c.depends_on_cells.begin(), c.depends_on_cells.end());
}
}
// aggregate all imports from code cells
vector<string> extract_notebook_imports(const ParsedNotebook& notebook) {
return notebook.all_imports;
}
// build a structured string for the LLM description prompt
string notebook_to_description_content(const ParsedNotebook& notebook) {
if (!notebook.is_valid) return "";
// count cells by type
size_t code_count = 0, md_count = 0, executed = 0;
for (const auto& c : notebook.cells) {
if (c.cell_type == "code") { code_count++; if (c.has_been_executed) executed++; }
else if (c.cell_type == "markdown") md_count++;
}
string out = "[notebook: " + to_string(code_count) + " code cells, "
+ to_string(md_count) + " markdown cells, "
+ to_string(executed) + " executed";
if (!notebook.kernel_name.empty()) out += ", kernel: " + notebook.kernel_name;
if (!notebook.language.empty()) out += ", lang: " + notebook.language;
out += "]\n\n";
// cell dependency summary
bool has_deps = false;
for (const auto& c : notebook.cells) {
if (c.cell_type == "code" && !c.depends_on_cells.empty()) {
has_deps = true;
break;
}
}
if (has_deps) {
out += "cell dependencies:\n";
for (const auto& c : notebook.cells) {
if (c.cell_type == "code" && !c.depends_on_cells.empty()) {
out += " cell " + to_string(c.index) + " depends on cells: ";
for (size_t j = 0; j < c.depends_on_cells.size(); j++) {
if (j > 0) out += ", ";
out += to_string(c.depends_on_cells[j]);
}
out += "\n";
}
}
out += "\n";
}
// render cells
for (const auto& c : notebook.cells) {
out += "## cell " + to_string(c.index) + " (" + c.cell_type;
if (c.cell_type == "code") {
if (c.has_been_executed) out += ", executed";
else out += ", not executed";
}
out += ")\n";
out += trim_copy(c.source) + "\n\n";
}
return out;
}
// extract concatenated code cell source for import extraction
string extract_notebook_source_for_imports(const ParsedNotebook& notebook) {
return notebook.code_content;
}
void print_dep_graph(const DepGraph& graph) {
cout << "\n========================================" << endl;
cout << " DEPENDENCY GRAPH SUMMARY" << endl;
cout << "========================================" << endl;
cout << "Total Nodes: " << graph.nodes.size() << endl;
cout << "Total Edges: " << graph.edges.size() << endl;
cout << "----------------------------------------" << endl;
cout << "Nodes:" << endl;
for (size_t i = 0; i < graph.nodes.size(); i++) {
const auto& node = graph.nodes[i];
cout << " [" << i << "] " << node.name;
if (node.is_gitignored) cout << " (gitignored)";
cout << endl;
cout << " Path: " << node.rel_path << endl;
cout << " Desc: " << node.description << endl;
}
if (graph.nodes.empty()) {
cout << " (no nodes)" << endl;
}
cout << "----------------------------------------" << endl;
cout << "Edges:" << endl;
for (size_t i = 0; i < graph.edges.size(); i++) {
const auto& edge = graph.edges[i];
cout << " [" << i << "] " << edge.from_path << " -> " << edge.to_path << endl;
if (!edge.import_stmt.empty()) {
cout << " Import: " << edge.import_stmt << endl;
}
}
if (graph.edges.empty()) {
cout << " (no edges)" << endl;
}
cout << "========================================\n" << endl;
}
vector<string> dep_files_to_skip = {
"requirements.txt", "requirements-dev.txt", "requirements-test.txt",
"Pipfile", "Pipfile.lock", "pyproject.toml", "poetry.lock", "setup.py", "setup.cfg",
"package.json", "package-lock.json", "yarn.lock", "pnpm-lock.yaml", "bun.lockb",
"go.mod", "go.sum",
"Cargo.toml", "Cargo.lock",
"pom.xml", "build.gradle", "build.gradle.kts", "settings.gradle", "gradle.properties",
"composer.json", "composer.lock",
"Gemfile", "Gemfile.lock",
"mix.exs", "mix.lock",
"pubspec.yaml", "pubspec.lock",
"CMakeLists.txt", "conanfile.txt", "vcpkg.json",
"rebar.config", "rebar.lock",
};
vector<string> build_artifacts_to_skip = {
"build", "dist", "target", "out", "bin", "obj",
"CMakeCache.txt", "CMakeFiles", "cmake_install.cmake",
"Makefile", "GNUmakefile",
".cmake", "CMakeError.log", "CMakeOutput.log",
"compile_commands.json",
};
unordered_set<string> python_stdlib = {
"os", "sys", "re", "json", "math", "time", "datetime", "random", "collections",
"itertools", "functools", "operator", "string", "pathlib", "typing", "abc",
"io", "csv", "logging", "warnings", "threading", "multiprocessing", "asyncio",
"socket", "ssl", "http", "urllib", "email", "html", "xml", "webbrowser",
"dataclasses", "enum", "copy", "pprint", "textwrap", "unittest", "doctest",
"argparse", "optparse", "getopt", "shutil", "glob", "fnmatch", "tempfile",
"platform", "errno", "ctypes", "weakref", "gc", "inspect", "traceback",
"code", "codeop", "subprocess", "popen2", "signal", "mmap", "msvcrt",
"posixpath", "ntpath", "genericpath", "posix", "nt", "_thread", "_io",
"hashlib", "hmac", "secrets", "base64", "binascii", "struct", "codecs",
"encodings", "codec_info", "locale", "gettext", "parser", "ast", "symtable",
"keyword", "token", "tokenize", "astroid", "py_compile", "compileall",
"dis", "pickle", "shelve", "marshal", "dbm", "gdbm", "sqlite3",
"csv", "tarfile", "zipfile", "zlib", "gzip", "bz2", "lzma", "zipimport",
"configparser", "plistlib", "netrc", "xdrlib", "robotparser", "mimetypes",
"MimeWriter", "mhlib", "mailbox", "mailcap", "multifile", "fileinput",
"stat", "statvfs", "stat_cache", "filecmp", "dircache", "linecache",
"cmd", "code", "readline", "rlcompleter", "getpass", "curses", "termios",
"tty", "pty", "fcntl", "pipes", "resource", "nis", "optik", "opus",
"audioop", "imageop", "aifc", "sunau", "wave", "chunk", "sndhdr",
"imghdr", "ossaudiodev", "sunaudiodev", "vorbis", "flac", "oggsize",
"xxsubtype", "formatter", "simplejson", "ujson", "orjson", "msgpack",
"cffi", "cython", "numpy", "pandas", "six", "future", "builtins",
};
bool is_stdlib_import(const string& imp, const string& lang) {
if (lang == "python") {
size_t dot = imp.find('.');
string module = (dot != string::npos) ? imp.substr(0, dot) : imp;
return python_stdlib.count(module) > 0;
}
return false;
}
vector<string> languages = {
"python", "cpp", "java", "javascript", "typescript", "go", "rust", "ruby", "php", "csharp", "dart", "kotlin", "swift", "scala", "elixir", "haskell", "clojure", "lua", "bash", "sh", "shell", "zsh", "powershell", "ps1", "pt"
};
vector<string> known_extensionless_filenames = {
"Dockerfile",
"Makefile",
"GNUmakefile",
"README",
"LICENSE",
"Procfile",
"Rakefile",
"Gemfile",
"Pipfile",
"Vagrantfile",
"Jenkinsfile",
};
// quick heuristic helper, keeping it for later use
bool is_probably_file(const string& name) {
if (find(known_extensionless_filenames.begin(),
known_extensionless_filenames.end(),
name) != known_extensionless_filenames.end()) {
return true;
}
return name.find('.') != string::npos;
}
bool matches_gitignore(const string& name);
vector<string> gitignore_patterns;
// core tree build from filesystem only (no parsing nonsense)
unique_ptr<TreeNode> build_tree(const fs::path& current_path,
const fs::path& root_path) {
string fname = current_path.filename().string();
if (fname == ".git") {
return nullptr;
}
if (find(dep_files_to_skip.begin(), dep_files_to_skip.end(), fname) != dep_files_to_skip.end()) {
return nullptr;
}
if (find(build_artifacts_to_skip.begin(), build_artifacts_to_skip.end(), fname) != build_artifacts_to_skip.end()) {
return nullptr;
}
string rel_path = fs::relative(current_path, root_path).generic_string();
if (rel_path.empty()) rel_path = ".";
if (!gitignore_patterns.empty() && is_path_in_gitignore(rel_path)) {
return nullptr;
}
string name = (current_path == root_path)
? fs::absolute(root_path).filename().string()
: current_path.filename().string();
if (name.empty()) name = "root";
string abs_path = fs::absolute(current_path).string();
bool is_file = fs::is_regular_file(current_path);
auto node = make_unique<TreeNode>(name, abs_path, rel_path, is_file);
// symlink loop guard (avoid recursive trap)
if (fs::is_symlink(current_path)) return node;
// if folder, recurse children in stable order
if (fs::is_directory(current_path)) {
vector<fs::directory_entry> entries;
for (const auto& entry : fs::directory_iterator(current_path)) {
entries.push_back(entry);
}
sort(entries.begin(), entries.end(),
[](const auto& a, const auto& b) {
return a.path().filename().string() < b.path().filename().string();
});
for (const auto& entry : entries) {
auto child = build_tree(entry.path(), root_path);
if (child) node->children.push_back(move(child));
}
node->is_file = false;
}
return node;
}
void print_tree(TreeNode* node) {
if (!node) return;
if (!node->children.empty()) {
cout << node->name << " -> ";
for (size_t i = 0; i < node->children.size(); i++) {
cout << node->children[i]->name;
if (i != node->children.size() - 1) cout << ", ";
}
cout << endl;
}
for (const auto& child : node->children) {
print_tree(child.get());
}
}
void collect_source_files(TreeNode* node, unordered_map<string, string>& contents, unordered_map<string, TreeNode*>& files, bool skip_dgatignore) {
if (!node) return;
if (node->is_file) {
if (skip_dgatignore && matches_dgatignore(node->rel_path)) {
return;
}
string lang = get_language_from_ext(node->rel_path);
if (!lang.empty()) {
files[node->rel_path] = node;
if (lang == "ipython") {
// parse notebook and store structured content instead of raw json
ParsedNotebook nb = parse_notebook_file(node->abs_path);
if (nb.is_valid) {
contents[node->rel_path] = notebook_to_description_content(nb);
}
} else if (!is_likely_binary_file(node->abs_path)) {
ifstream infile(node->abs_path);
if (infile.is_open()) {
stringstream buffer;
buffer << infile.rdbuf();
contents[node->rel_path] = sanitize_utf8(buffer.str());
}
}
}
}
for (const auto& child : node->children) collect_source_files(child.get(), contents, files, skip_dgatignore);
}
TreeNode* find_node_by_path(TreeNode* node, const string& rel_path) {
if (!node) return nullptr;
if (node->rel_path == rel_path) return node;
for (auto& child : node->children) {
TreeNode* found = find_node_by_path(child.get(), rel_path);
if (found) return found;
}
return nullptr;
}
DepGraph build_dep_graph(TreeNode* root) {
DepGraph graph;
if (!root) return graph;
unordered_map<string, string> contents;
unordered_map<string, TreeNode*> files;
collect_source_files(root, contents, files, true);
unordered_set<string> known_files;
for (const auto& [rel_path, _] : contents) {
known_files.insert(rel_path);
}
const size_t NUM_THREADS = 8;
mutex graph_mutex;
atomic<int> processed{0};
atomic<int> total{static_cast<int>(contents.size())};
cout << "[DGAT] Processing " << contents.size() << " files with " << NUM_THREADS << " workers..." << endl;
ThreadPool pool(NUM_THREADS);
vector<future<void>> futures;
for (const auto& [rel_path, content] : contents) {
futures.push_back(pool.enqueue([&]() {
string lang = get_language_from_ext(rel_path);
vector<string> imports;
if (lang == "ipython") {
// notebooks need abs_path to read from disk
auto it = files.find(rel_path);
if (it != files.end()) {
ParsedNotebook nb = parse_notebook_file(it->second->abs_path);
if (nb.is_valid) {
// try tree-sitter on concatenated code cells first
string code = nb.code_content;
vector<string> ts_imports = extract_imports_via_tree_sitter(rel_path, code);
if (!ts_imports.empty()) {
imports = ts_imports;
} else {
// fallback to manual extraction per cell
imports = extract_notebook_imports(nb);
}
}
}
} else {
imports = extract_imports(rel_path, content);
}
vector<pair<string, string>> local_edges;
for (const string& imp : imports) {
// skip stdlib imports
if (is_stdlib_import(imp, lang)) {
continue;
}
// skip system includes marker
if (imp.rfind("__SYSTEM_INCLUDE__:", 0) == 0) {
continue;
}
string norm = normalize_import_path(imp, rel_path);
if (norm.empty()) continue;
// try exact path first, then common extensions, then barrel index files
// this covers: "@/lib/utils" → "frontend/src/lib/utils.ts"
// "../components/Foo" → ".../Foo.tsx"
// "some/module" → "some/module/index.ts" (barrel)
bool is_internal = false;
{
static const vector<string> try_exts = {
"", ".py", ".tsx", ".ts", ".jsx", ".js", ".css", ".scss", ".h", ".hpp"
};
static const vector<string> index_exts = {
".tsx", ".ts", ".jsx", ".js"
};
static const vector<string> init_exts = {
"/__init__.py"
};
for (auto& ext : try_exts) {
if (known_files.count(norm + ext)) {
norm = norm + ext;
is_internal = true;
break;
}
}
// barrel import — try norm/index.*
if (!is_internal) {
for (auto& ext : index_exts) {
string candidate = norm + "/index" + ext;
if (known_files.count(candidate)) {
norm = candidate;
is_internal = true;
break;
}
}
}
// Python package init — try norm/__init__.py
if (!is_internal) {
for (auto& ext : init_exts) {
string candidate = norm + ext;
if (known_files.count(candidate)) {
norm = candidate;
is_internal = true;
break;
}
}
}
}
// last resort: match by filename only (catches c/cpp header-only scenarios)
if (!is_internal) {
string imp_name = fs::path(imp).filename().string();
for (const auto& [file_path, _] : contents) {
string fname = fs::path(file_path).filename().string();
if (fname == imp_name || fname == imp_name + ".h" || fname == imp_name + ".hpp") {
norm = file_path;
is_internal = true;
break;
}
}
}
// only add edge if file exists in tree - skip external
if (is_internal) {
local_edges.emplace_back(norm, imp);
}
}
{
lock_guard<mutex> lock(graph_mutex);
for (const auto& [to_path, import_stmt] : local_edges) {
if (!graph.path_to_node.count(to_path)) {
bool gitignored = is_path_in_gitignore(to_path);
DepNode node;
node.name = fs::path(to_path).filename().string();
node.rel_path = to_path;
node.description = gitignored ? "Gitignored dependency" : "External dependency";
node.is_gitignored = gitignored;
graph.path_to_node[to_path] = graph.nodes.size();
graph.nodes.push_back(node);
}
DepEdge edge;
edge.from_path = rel_path;
edge.to_path = to_path;
edge.import_stmt = import_stmt;
graph.edges.push_back(edge);
}
int count = ++processed;
if (count % 10 == 0 || count == total) {
float pct = (float)count / total * 100;
cout << "\r[DGAT] Processing: " << count << "/" << total
<< " (" << fixed << setprecision(1) << pct << "%)" << flush;
}
}
}));
}
for (auto& f : futures) {
f.get();
}
cout << "\r[DGAT] Processing complete!" << endl;
unordered_set<string> all_node_ids;
for (const auto& node : graph.nodes) {
all_node_ids.insert(node.rel_path);
}
for (const auto& edge : graph.edges) {
if (!all_node_ids.count(edge.from_path)) {
DepNode node;
node.name = fs::path(edge.from_path).filename().string();
node.rel_path = edge.from_path;
node.is_file = true;
node.is_gitignored = false;
TreeNode* tn = find_node_by_path(root, edge.from_path);
if (tn) {
node.abs_path = tn->abs_path;
node.description = tn->description;
ostringstream oss;
oss << std::hex << std::setfill('0')
<< std::setw(16) << tn->hash.high64
<< std::setw(16) << tn->hash.low64;
node.hash = oss.str();
} else {
node.abs_path = "";
node.description = "Source file";
node.hash = "";
}
graph.path_to_node[edge.from_path] = graph.nodes.size();
graph.nodes.push_back(node);
all_node_ids.insert(edge.from_path);
}
}
for (auto& node : graph.nodes) {
for (const auto& edge : graph.edges) {
if (edge.from_path == node.rel_path) {
node.depends_on.push_back(edge.to_path);
}
if (edge.to_path == node.rel_path) {
node.depended_by.push_back(edge.from_path);
}
}
}
return graph;
}
void populate_dependency_descriptions(DepGraph& graph) {
if (graph.nodes.empty()) return;
unordered_map<string, vector<string>> importers;
for (const auto& edge : graph.edges) {
importers[edge.to_path].push_back(edge.from_path);