-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
1353 lines (1278 loc) · 38.9 KB
/
index.ts
File metadata and controls
1353 lines (1278 loc) · 38.9 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
import normalizeUrl from "normalize-url";
import { existsSync, mkdirSync } from "fs";
import { join } from "path";
import chalk from "chalk";
import { cpus } from "os";
import ora, { type Ora } from "ora";
import { extractJsonFromString, jsonParser } from "extract-json-from-string-y";
import { minimatch } from "minimatch";
import yargs from "yargs";
import { hideBin } from "yargs/helpers";
import { Context7 } from "@upstash/context7-sdk";
const argv = await yargs(hideBin(process.argv))
.option("repo", {
alias: "r",
type: "string",
description: "GitHub repository URL",
demandOption: false,
})
.option("ignore", {
alias: "i",
type: "array",
description: "Patterns to ignore (glob syntax)",
default: [],
})
.help()
.parse();
const REPO_URL = argv.repo || Bun.env.REPO_URL;
if (!REPO_URL) {
console.error(
chalk.red(
"Error: Repository URL is required. Use --repo flag or set REPO_URL environment variable.",
),
);
process.exit(1);
}
const BASE_URL = Bun.env.BASE_URL;
const API_KEY = Bun.env.API_KEY;
const MODEL = Bun.env.MODEL;
if (!BASE_URL || !API_KEY || !MODEL) {
console.error(
chalk.red(
"Error: BASE_URL, API_KEY, and MODEL environment variables are required.",
),
);
process.exit(1);
}
const IGNORE_PATTERNS = [
...(argv.ignore as string[]),
...(Bun.env.IGNORE_PATTERNS?.split(",") || []),
];
const FILES_PER_BATCH = 5;
const MAX_FILE_SIZE = 100000;
const CPU_COUNT = cpus().length;
const REASONING_EFFORT = Bun.env.REASONING_EFFORT || "medium";
const REASONING_EFFORT_FULL = Bun.env.REASONING_EFFORT_FULL || "high";
const ENABLE_CONTEXT7 = Bun.env.ENABLE_CONTEXT7 === "true";
let context7Client: Context7 | null = null;
if (ENABLE_CONTEXT7) {
try {
context7Client = new Context7();
} catch (error) {
console.log(
chalk.yellow(
"Failed to initialize Context7 client, disabling Context7 feature",
),
);
}
}
const fixBaseURL = (baseURL: string) => {
const url = normalizeUrl(baseURL);
return url.endsWith("/v1") ? url : `${url}/v1`;
};
type FileEntry = {
path: string;
sha: string;
content: string;
analyzed: boolean;
};
type FileDependencies = {
imports: string[];
exports: string[];
relatedFiles: string[];
};
type FileAnalysisResult = {
file: FileEntry;
bugs: BugData[];
dependencies: FileDependencies;
};
type CacheData = {
lastCommit: string;
branch: string;
files: Record<string, FileEntry>;
timestamp: number;
};
type Severity = "MAJOR" | "MEDIUM" | "CVE" | "MINOR" | "UNKNOWN";
type CVEInfo = {
score: number;
affected: string[];
description: string;
};
type BugData = {
path: string;
description: string;
severity: Severity;
diff: string;
reasoning?: string;
cve?: CVEInfo;
};
type TreeItem = {
path: string;
mode: string;
type: string;
sha: string;
size?: number;
url: string;
};
type TreeResponse = {
sha: string;
url: string;
tree: TreeItem[];
truncated: boolean;
};
type DependencyGraph = {
[filePath: string]: FileDependencies;
};
type StrategicBatch = {
reason: string;
files: string[];
};
const SEVERITY_COLORS: Record<Severity, chalk.Chalk> = {
MAJOR: chalk.bold.red,
MEDIUM: chalk.hex("#FFA500"),
CVE: chalk.hex("#8B0000").bold,
MINOR: chalk.blue,
UNKNOWN: chalk.gray,
};
const SYSTEM_PROMPT = `You are an expert code analyzer. Key behaviors:
1. Tone: Direct, technical, no fluff
2. Confidence: Only report bugs you're 90%+ certain about
3. Formatting: Minimal - only use structure when essential
4. Reasoning: Think step-by-step before concluding
When analyzing code:
- Assume the developer is competent
- Don't report style issues or potential edge cases
- Focus on runtime failures in normal execution
- Validate your findings before reporting`;
const ANALYSIS_INSTRUCTIONS = `Analyze the following code files for finding the bugs.
Task:
Identify bugs that will cause the code to fail in normal execution flow.
Calibration:
- Confidence threshold:
- MAJOR: 90%+ If you'd use words like "might", "could", or "if", don't report as MAJOR.
- MEDIUM: 75%+
- CVE: Security vulnerabilities (injection, XSS, auth bypass, etc.)
- MINOR: 35%+
- UNKNOWN: use for unknown cases
What is a bug:
- Logic errors: inverted conditions, wrong operators, off-by-one errors, infinite loops
- Async flow failures: missing await when value is needed, awaiting non-promises
- Type mismatches: incorrect type usage that breaks runtime
- Reference errors: undefined variables, accessing undefined properties
- Control flow bugs: unreachable code, incorrect branching
- Security vulnerabilities: SQL injection, XSS, authentication bypass, path traversal, etc.
What is NOT a bug:
- Style issues, missing documentation
- Potential edge cases without proof of failure
- Missing error handling unless it causes immediate crash
- Architecture suggestions
${
ENABLE_CONTEXT7
? `
Documentation Lookup:
When uncertain about technical details (syntax, features, versions, APIs), request documentation:
<need_docs>library_name: your search query here</need_docs>
Examples:
- <need_docs>rust: edition 2024</need_docs>
- <need_docs>clap: derive macro version 4.5</need_docs>
- <need_docs>svelte: runes syntax</need_docs>
Documentation will be provided automatically. Continue analysis after receiving it.
IMPORTANT: Only request docs when confidence < 95%. Don't request for obvious things.
`
: ""
}
Context:
- Today is ${new Date().toLocaleDateString()}
Output format:
You MUST provide valid JSON. Think carefully, then output ONLY the JSON array.
Wrap your JSON response in a code block with the dailybugs language identifier:
\`\`\`dailybugs
[
{
"path": "file/path.ts",
"description": "clear bug description",
"severity": "MAJOR | MEDIUM | CVE | MINOR | UNKNOWN",
"diff": "--- a/file\\n+++ b/file\\n-old line\\n+new line",
"cve": {
"score": 8.5,
"affected": ["authentication", "data integrity"],
"description": "SQL injection vulnerability allows attackers to bypass authentication"
}
}
]
\`\`\`
CRITICAL:
- Every bug object MUST have: path, description, severity, and diff.
- CVE severity bugs MUST include cve object with score (0-10), affected areas, and description.
- If diff is not applicable, use "N/A" as the value.
Return empty array if no bugs found:
\`\`\`dailybugs
[]
\`\`\``;
const DEPENDENCY_EXTRACTION_PROMPT = `Analyze this file and extract its dependencies.
File: {filePath}
Content:
\`\`\`
{fileContent}
\`\`\`
Task:
Extract all file imports/dependencies from this code. Focus on LOCAL files only (not npm packages or standard library).
Output format (JSON):
\`\`\`json
{
"imports": ["relative/path/to/file.ts", "another/file.js"],
"exports": ["functionName", "ClassName"],
"relatedFiles": ["files/that/might/use/this.ts"]
}
\`\`\`
Rules:
- imports: Local file paths this file imports FROM (e.g., "./utils.ts", "../lib/db.js")
- exports: Named exports this file provides (functions, classes, constants)
- relatedFiles: Files that likely import THIS file (based on exports and file purpose)
- Normalize paths (remove ./, ../, file extensions if ambiguous)
- Return empty arrays if none found
- DO NOT include npm packages or standard library imports
Output ONLY the JSON, no explanations.`;
const BATCH_STRATEGY_PROMPT = `Given this codebase dependency graph, create strategic analysis batches.
Dependency Graph:
{dependencyGraph}
Task:
Group related files into batches for cross-file bug analysis.
Rules:
- Group files that import each other
- Group API routes with their services/utils/models
- Group components with their hooks/contexts
- Max 5 files per batch
- Prioritize high-coupling files (many imports/exports)
- Each file should appear in at most one batch
- Create 3-8 batches total
Output format (JSON):
\`\`\`json
[
{
"reason": "Auth flow - route + JWT + user service",
"files": ["routes/auth.ts", "lib/jwt.ts", "services/user.ts"]
},
{
"reason": "Database layer - models + queries",
"files": ["models/user.ts", "lib/db.ts", "lib/query.ts"]
}
]
\`\`\`
Output ONLY the JSON array, no explanations.`;
const shouldIgnoreFile = (filePath: string): boolean => {
return IGNORE_PATTERNS.some((pattern) => minimatch(filePath, pattern));
};
const getCacheDir = (
repoUrl: string,
): { cacheDir: string; cacheFile: string; bugFile: string } => {
const { owner, repo } = parseRepoURL(repoUrl);
const cacheDir = join(process.cwd(), ".cache", "dailybugs", owner, repo);
const cacheFile = join(cacheDir, "codebase.json");
const bugFile = join(cacheDir, "bugs.json");
return { cacheDir, cacheFile, bugFile };
};
const parseRepoURL = (
url: string,
): { owner: string; repo: string; branch?: string } => {
const cleanURL = url.replace("https://github.com/", "");
const parts = cleanURL.split("/");
if (parts.length < 2) {
throw new Error("Invalid repository URL");
}
const owner = parts[0];
const repo = parts[1];
let branch: string | undefined = undefined;
if (parts.length >= 4 && parts[2] === "tree") {
branch = parts.slice(3).join("/");
}
return { owner, repo, branch };
};
const fetchDefaultBranch = async (
owner: string,
repo: string,
): Promise<string> => {
const response = await fetch(
`https://api.github.com/repos/${owner}/${repo}`,
{
headers: getGitHubHeaders(),
},
);
if (!response.ok) {
throw new Error(
`GitHub API error: ${response.status} ${await response.text()}`,
);
}
const data = await response.json();
return data.default_branch;
};
const getGitHubHeaders = () => {
const headers: Record<string, string> = {
accept: "application/vnd.github.v3+json",
"user-agent": "DailyBugs",
};
if (Bun.env.GH_TOKEN) {
headers.authorization = `Bearer ${Bun.env.GH_TOKEN}`;
}
return headers;
};
const validateBugData = (bug: any): bug is BugData => {
if (typeof bug !== "object" || bug === null) return false;
if (typeof bug.path !== "string" || bug.path.length === 0) return false;
if (typeof bug.description !== "string" || bug.description.length === 0)
return false;
if (typeof bug.severity !== "string") return false;
if (typeof bug.diff !== "string") return false;
if (bug.severity === "CVE") {
if (!bug.cve || typeof bug.cve !== "object") return false;
if (
typeof bug.cve.score !== "number" ||
bug.cve.score < 0 ||
bug.cve.score > 10
)
return false;
if (!Array.isArray(bug.cve.affected) || bug.cve.affected.length === 0)
return false;
if (
typeof bug.cve.description !== "string" ||
bug.cve.description.length === 0
)
return false;
}
return true;
};
const loadCache = async (cacheFile: string): Promise<CacheData | null> => {
if (!existsSync(cacheFile)) return null;
try {
const data = Bun.file(cacheFile, { type: "application/json" });
return await data.json();
} catch (e) {
console.error(e);
return null;
}
};
const loadBugs = async (bugFile: string): Promise<BugData[]> => {
if (!existsSync(bugFile)) return [];
try {
const data = Bun.file(bugFile, { type: "application/json" });
const bugs = await data.json();
if (!Array.isArray(bugs)) return [];
return bugs.filter(validateBugData);
} catch (e) {
console.error(e);
return [];
}
};
const saveCache = async (
cacheFile: string,
cacheDir: string,
cache: CacheData,
): Promise<void> => {
if (!existsSync(cacheDir)) {
mkdirSync(cacheDir, { recursive: true });
}
await Bun.write(cacheFile, JSON.stringify(cache));
};
const saveBugs = async (
bugFile: string,
cacheDir: string,
bugs: BugData[],
): Promise<void> => {
if (!existsSync(cacheDir)) {
mkdirSync(cacheDir, { recursive: true });
}
const validBugs = bugs.filter(validateBugData);
await Bun.write(bugFile, JSON.stringify(validBugs, null, 2));
};
const fetchRepoTree = async (
owner: string,
repo: string,
branch: string,
): Promise<TreeItem[]> => {
const branchResponse = await fetch(
`https://api.github.com/repos/${owner}/${repo}/branches/${branch}`,
{
headers: getGitHubHeaders(),
},
);
if (!branchResponse.ok) {
throw new Error(
`GitHub branch API error: ${branchResponse.status} ${await branchResponse.text()}`,
);
}
const branchData = await branchResponse.json();
const sha = branchData.commit.sha;
const response = await fetch(
`https://api.github.com/repos/${owner}/${repo}/git/trees/${sha}?recursive=1`,
{
headers: getGitHubHeaders(),
},
);
if (!response.ok) {
throw new Error(
`GitHub tree API error: ${response.status} ${await response.text()}`,
);
}
const data = (await response.json()) as TreeResponse;
return data.tree.filter(
(item) =>
item.type === "blob" &&
!item.path.match(
/\.(lock|min\.js|map|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot)$/,
) &&
!shouldIgnoreFile(item.path),
);
};
const fetchFileContent = async (
owner: string,
repo: string,
path: string,
branch: string,
): Promise<string> => {
const response = await fetch(
`https://api.github.com/repos/${owner}/${repo}/contents/${path}?ref=${branch}`,
{
headers: {
...getGitHubHeaders(),
accept: "application/vnd.github.v3.raw",
},
},
);
if (!response.ok) {
throw new Error(`GitHub content API error: ${response.status}`);
}
return await response.text();
};
const fetchLatestCommit = async (
owner: string,
repo: string,
branch: string,
): Promise<string> => {
const response = await fetch(
`https://api.github.com/repos/${owner}/${repo}/commits?sha=${branch}&per_page=1`,
{
headers: getGitHubHeaders(),
},
);
if (!response.ok) {
throw new Error(`GitHub commits API error: ${response.status}`);
}
const data = await response.json();
return data[0].sha;
};
const context7Cache = new Map<string, string>();
const searchContext7 = async (
libraryName: string,
query: string,
): Promise<string> => {
if (!context7Client) {
return `\n[Context7 not available]`;
}
const cacheKey = `${libraryName}:${query}`;
if (context7Cache.has(cacheKey)) {
if (Bun.env.DEBUG_CONTEXT7 === "true") {
console.log(chalk.cyan(`\n[Context7] Cache hit for: ${cacheKey}`));
}
return context7Cache.get(cacheKey)!;
}
try {
if (Bun.env.DEBUG_CONTEXT7 === "true") {
console.log(chalk.cyan(`\n[Context7] Searching library: ${libraryName}`));
}
const libraries = await context7Client.searchLibrary(query, libraryName);
if (libraries.length === 0) {
const result = `[No library found for: ${libraryName}]`;
context7Cache.set(cacheKey, result);
return result;
}
const library = libraries[0];
if (Bun.env.DEBUG_CONTEXT7 === "true") {
console.log(
chalk.cyan(
`\n[Context7] Found library: ${library.name} (${library.id})`,
),
);
}
const context = await context7Client.getContext(query, library.id, {
type: "txt",
});
const result = context.slice(0, 3000);
context7Cache.set(cacheKey, result);
return result;
} catch (error) {
console.log(chalk.yellow(`\n[Context7] Error: ${error}`));
return `[Documentation lookup failed for: ${libraryName}]`;
}
};
const extractJSON = (content: string): any[] => {
try {
const extracted = extractJsonFromString(content, jsonParser);
if (extracted.length > 0) {
const result = Array.isArray(extracted[0]) ? extracted[0] : extracted;
return result;
}
} catch (error) {
if (Bun.env.DEBUG_PARSING === "true") {
console.log(
chalk.red("\nFailed to parse JSON with extract-json-from-string-y"),
);
console.log(chalk.gray(content));
}
}
const codeBlockMatch = content.match(/```(?:json|dailybugs)\s*([\s\S]*?)```/);
if (codeBlockMatch) {
try {
return JSON.parse(codeBlockMatch[1].trim());
} catch (error) {
if (Bun.env.DEBUG_PARSING === "true") {
console.log(chalk.red("Failed to parse JSON from code block"));
console.log(chalk.gray(codeBlockMatch[1]));
}
}
}
const jsonArrayMatch = content.match(/\[[\s\S]*?\]/);
if (jsonArrayMatch) {
try {
return JSON.parse(jsonArrayMatch[0]);
} catch (error) {
if (Bun.env.DEBUG_PARSING === "true") {
console.log(chalk.red("Failed to parse JSON array"));
console.log(chalk.gray(jsonArrayMatch[0]));
}
}
}
return [];
};
const extractJSONObject = (content: string): any => {
try {
const extracted = extractJsonFromString(content, jsonParser);
if (extracted.length > 0) {
return extracted[0];
}
} catch (error) {
if (Bun.env.DEBUG_PARSING === "true") {
console.log(chalk.red("\nFailed to parse JSON object"));
}
}
const codeBlockMatch = content.match(/```(?:json)\s*([\s\S]*?)```/);
if (codeBlockMatch) {
try {
return JSON.parse(codeBlockMatch[1].trim());
} catch (error) {
if (Bun.env.DEBUG_PARSING === "true") {
console.log(chalk.red("Failed to parse JSON from code block"));
}
}
}
const jsonMatch = content.match(/\{[\s\S]*\}/);
if (jsonMatch) {
try {
return JSON.parse(jsonMatch[0]);
} catch (error) {
if (Bun.env.DEBUG_PARSING === "true") {
console.log(chalk.red("Failed to parse JSON object"));
}
}
}
return null;
};
const callAIWithDocs = async (
messages: Array<{ role: string; content: string }>,
reasoningEffort: string,
maxIterations: number = 3,
): Promise<{ content: string; reasoning?: string }> => {
if (!ENABLE_CONTEXT7) {
const response = await fetch(fixBaseURL(BASE_URL) + "/chat/completions", {
method: "POST",
headers: {
authorization: `Bearer ${API_KEY}`,
"content-type": "application/json",
},
body: JSON.stringify({
model: MODEL,
messages,
stream: false,
reasoning: {
effort: reasoningEffort,
exclude: false,
},
}),
});
if (!response.ok) {
throw new Error(`AI error: ${response.status} ${await response.text()}`);
}
const { choices } = (await response.json()) as any;
const message = choices[0].message;
return {
content: message.content,
reasoning: message.reasoning || message.reasoning_content || null,
};
}
const seenQueries = new Set<string>();
for (let iterations = 0; iterations < maxIterations; iterations++) {
const response = await fetch(fixBaseURL(BASE_URL) + "/chat/completions", {
method: "POST",
headers: {
authorization: `Bearer ${API_KEY}`,
"content-type": "application/json",
},
body: JSON.stringify({
model: MODEL,
messages,
stream: false,
reasoning: {
effort: reasoningEffort,
exclude: false,
},
}),
});
if (!response.ok) {
throw new Error(`AI error: ${response.status} ${await response.text()}`);
}
const { choices } = (await response.json()) as any;
const message = choices[0].message;
const reasoning = message.reasoning || message.reasoning_content || null;
const docsNeeded = message.content.match(
/<need_docs>([^:]+):\s*(.*?)<\/need_docs>/g,
);
if (!docsNeeded) {
return { content: message.content, reasoning };
}
const queries = docsNeeded
.map((tag) => {
const match = tag.match(/<need_docs>([^:]+):\s*(.*?)<\/need_docs>/);
if (match) {
return { library: match[1].trim(), query: match[2].trim() };
}
return null;
})
.filter(Boolean) as { library: string; query: string }[];
const newQueries = queries.filter((q) => {
const key = `${q.library}:${q.query}`;
if (seenQueries.has(key)) return false;
seenQueries.add(key);
return true;
});
if (newQueries.length === 0) {
if (Bun.env.DEBUG_CONTEXT7 === "true") {
console.log(
chalk.yellow(
"\n[Context7] AI keeps requesting same docs, breaking loop",
),
);
}
return { content: message.content, reasoning };
}
if (Bun.env.DEBUG_CONTEXT7 === "true") {
console.log(
chalk.cyan(
`\n[Context7] Fetching docs for ${newQueries.length} queries`,
),
);
}
const docsResults = await Promise.all(
newQueries.map((q) => searchContext7(q.library, q.query)),
);
const originalUserMessage = messages[messages.length - 1];
let newContent = originalUserMessage.content;
newQueries.forEach((query, i) => {
const docs = `\n\n[Documentation for "${query.library}: ${query.query}"]\n${docsResults[i]}\n`;
newContent += docs;
});
messages = [
...messages.slice(0, -1),
{
role: "user",
content: newContent,
},
];
if (Bun.env.DEBUG_CONTEXT7 === "true") {
console.log(
chalk.cyan(
`\n[Context7] Re-analyzing with docs (iteration ${iterations + 1})`,
),
);
}
}
if (Bun.env.DEBUG_CONTEXT7 === "true") {
console.log(
chalk.yellow(
"\n[Context7] Max iterations reached, returning last response",
),
);
}
const finalResponse = await fetch(
fixBaseURL(BASE_URL) + "/chat/completions",
{
method: "POST",
headers: {
authorization: `Bearer ${API_KEY}`,
"content-type": "application/json",
},
body: JSON.stringify({
model: MODEL,
messages,
stream: false,
reasoning: {
effort: reasoningEffort,
exclude: false,
},
}),
},
);
if (!finalResponse.ok) {
throw new Error(
`AI error: ${finalResponse.status} ${await finalResponse.text()}`,
);
}
const { choices } = (await finalResponse.json()) as any;
const message = choices[0].message;
return {
content: message.content.replace(/<need_docs>.*?<\/need_docs>/g, "").trim(),
reasoning: message.reasoning || message.reasoning_content || null,
};
};
const extractDependencies = async (
file: FileEntry,
): Promise<FileDependencies> => {
try {
const prompt = DEPENDENCY_EXTRACTION_PROMPT.replace(
"{filePath}",
file.path,
).replace("{fileContent}", file.content.slice(0, 5000));
const response = await fetch(fixBaseURL(BASE_URL) + "/chat/completions", {
method: "POST",
headers: {
authorization: `Bearer ${API_KEY}`,
"content-type": "application/json",
},
body: JSON.stringify({
model: MODEL,
messages: [{ role: "user", content: prompt }],
stream: false,
temperature: 0.3,
}),
});
if (!response.ok) {
throw new Error(`AI error: ${response.status}`);
}
const { choices } = (await response.json()) as any;
const result = extractJSONObject(choices[0].message.content);
if (!result) {
return { imports: [], exports: [], relatedFiles: [] };
}
return {
imports: Array.isArray(result.imports) ? result.imports : [],
exports: Array.isArray(result.exports) ? result.exports : [],
relatedFiles: Array.isArray(result.relatedFiles)
? result.relatedFiles
: [],
};
} catch (error) {
if (Bun.env.DEBUG_DEPS === "true") {
console.log(
chalk.yellow(
`Failed to extract dependencies for ${file.path}: ${error}`,
),
);
}
return { imports: [], exports: [], relatedFiles: [] };
}
};
const createStrategicBatches = async (
graph: DependencyGraph,
allFiles: FileEntry[],
): Promise<StrategicBatch[]> => {
try {
const graphSummary = Object.entries(graph)
.map(([path, deps]) => ({
file: path,
imports: deps.imports.slice(0, 5),
exports: deps.exports.slice(0, 5),
}))
.slice(0, 100);
const prompt = BATCH_STRATEGY_PROMPT.replace(
"{dependencyGraph}",
JSON.stringify(graphSummary, null, 2),
);
const response = await fetch(fixBaseURL(BASE_URL) + "/chat/completions", {
method: "POST",
headers: {
authorization: `Bearer ${API_KEY}`,
"content-type": "application/json",
},
body: JSON.stringify({
model: MODEL,
messages: [{ role: "user", content: prompt }],
stream: false,
temperature: 0.5,
}),
});
if (!response.ok) {
throw new Error(`AI error: ${response.status}`);
}
const { choices } = (await response.json()) as any;
const batches = extractJSON(choices[0].message.content);
if (!Array.isArray(batches) || batches.length === 0) {
throw new Error("Invalid batch strategy response");
}
return batches
.filter((b) => b.reason && Array.isArray(b.files) && b.files.length > 0)
.map((b) => ({
reason: b.reason,
files: b.files.slice(0, 5),
}));
} catch (error) {
console.log(chalk.yellow(`Failed to create strategic batches: ${error}`));
return [];
}
};
const analyzeSingleFile = async (
file: FileEntry,
useSystemPrompt: boolean,
reasoningEffort: string,
): Promise<BugData[]> => {
const fileContent = `### ${file.path}\n\`\`\`\n${file.content}\n\`\`\``;
let messages: Array<{ role: string; content: string }>;
if (useSystemPrompt) {
messages = [
{ role: "system", content: SYSTEM_PROMPT },
{ role: "user", content: `${ANALYSIS_INSTRUCTIONS}\n\n${fileContent}` },
];
} else {
messages = [
{
role: "user",
content: `${SYSTEM_PROMPT}\n\n${ANALYSIS_INSTRUCTIONS}\n\n${fileContent}`,
},
];
}
const { content, reasoning } = await callAIWithDocs(
messages,
reasoningEffort,
);
const extractedBugs = extractJSON(content);
const validBugs = extractedBugs.filter(validateBugData);
const bugs = validBugs.map((bug) => ({
path: bug.path,
description: bug.description,
severity: (bug.severity?.toUpperCase() || "UNKNOWN") as Severity,
diff: bug.diff || "N/A",
reasoning: reasoning ? reasoning.slice(0, 500) : undefined,
cve: bug.cve,
}));
return bugs;
};
const analyzeFileBatch = async (
files: FileEntry[],
conversationHistory: Array<{ role: string; content: string }>,
useSystemPrompt: boolean,
reasoningEffort: string,
): Promise<{
bugs: BugData[];
history: Array<{ role: string; content: string }>;
}> => {
const filesContent = files
.map((file) => `### ${file.path}\n\`\`\`\n${file.content}\n\`\`\``)
.join("\n\n");
let messages: Array<{ role: string; content: string }>;
if (useSystemPrompt) {
messages = [
{ role: "system", content: SYSTEM_PROMPT },
...conversationHistory,
{ role: "user", content: `${ANALYSIS_INSTRUCTIONS}\n\n${filesContent}` },
];
} else {
messages = [
...conversationHistory,
{
role: "user",
content: `${SYSTEM_PROMPT}\n\n${ANALYSIS_INSTRUCTIONS}\n\n${filesContent}`,
},
];
}
const { content, reasoning } = await callAIWithDocs(
messages,
reasoningEffort,
);
const updatedHistory = [
...conversationHistory,
{
role: "user",
content: useSystemPrompt
? `${ANALYSIS_INSTRUCTIONS}\n\n${filesContent}`
: messages[messages.length - 1].content,
},
{ role: "assistant", content },
];
const extractedBugs = extractJSON(content);
const validBugs = extractedBugs.filter(validateBugData);
const bugs = validBugs.map((bug) => ({
path: bug.path,
description: bug.description,
severity: (bug.severity?.toUpperCase() || "UNKNOWN") as Severity,
diff: bug.diff || "N/A",
reasoning: reasoning ? reasoning.slice(0, 500) : undefined,
cve: bug.cve,
}));
return { bugs, history: updatedHistory };
};
const chunkArray = <T>(array: T[], size: number): T[][] => {
const chunks: T[][] = [];
for (let i = 0; i < array.length; i += size) {
chunks.push(array.slice(i, i + size));
}
return chunks;
};
const renderDiff = (text: string) => {
if (!text || typeof text !== "string" || text === "N/A") {
return chalk.gray("(no diff provided)");
}