-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
412 lines (346 loc) · 11.7 KB
/
Copy pathmain.go
File metadata and controls
412 lines (346 loc) · 11.7 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
package main
import (
"bufio"
"fmt"
"os"
"strings"
"path/filepath"
"github.com/devthedeveloper/codebase-agent/internal/ollama"
"github.com/devthedeveloper/codebase-agent/internal/pentest"
"github.com/devthedeveloper/codebase-agent/internal/scanner"
"github.com/devthedeveloper/codebase-agent/internal/security"
"github.com/devthedeveloper/codebase-agent/internal/understand"
)
const version = "0.1.0"
const maxContextChars = 120_000 // ~30k tokens
const systemPrompt = `You are a codebase onboarding expert. You help developers understand unfamiliar codebases quickly and accurately.
You have been given the full context of a repository including file structure and source code. Use this to answer questions about:
- Architecture and design patterns
- How specific features work
- Where to find specific functionality
- Data flow and control flow
- Dependencies and relationships between components
- Where to add new features or make changes
Guidelines:
- Always cite file paths and line numbers when referencing code
- Be concise but thorough
- If you're unsure, say so and suggest what to look at
- Think about the codebase holistically, not just individual files`
func main() {
if len(os.Args) < 2 {
printUsage()
os.Exit(1)
}
switch os.Args[1] {
case "ask":
if len(os.Args) < 3 {
fmt.Println("Usage: codebase-agent ask <repo-path> [-q \"question\"]")
os.Exit(1)
}
cmdAsk(os.Args[2], os.Args[3:])
case "understand":
if len(os.Args) < 3 {
fmt.Println("Usage: codebase-agent understand <repo-path> [--exclude dir1,dir2] [--include dir1,dir2]")
os.Exit(1)
}
cmdUnderstand(os.Args[2], os.Args[3:])
case "pentest":
if len(os.Args) < 3 {
fmt.Println("Usage: codebase-agent pentest <repo-path> [--local] [--exclude dir1,dir2]")
os.Exit(1)
}
cmdPentest(os.Args[2], os.Args[3:])
case "security":
if len(os.Args) < 3 {
fmt.Println("Usage: codebase-agent security <repo-path> [--local] [--exclude dir1,dir2]")
os.Exit(1)
}
cmdSecurity(os.Args[2], os.Args[3:])
case "scan":
if len(os.Args) < 3 {
fmt.Println("Usage: codebase-agent scan <repo-path>")
os.Exit(1)
}
cmdScan(os.Args[2])
case "version", "--version", "-v":
fmt.Printf("codebase-agent v%s\n", version)
case "help", "--help", "-h":
printUsage()
default:
fmt.Printf("Unknown command: %s\n\n", os.Args[1])
printUsage()
os.Exit(1)
}
}
func printUsage() {
fmt.Printf(`codebase-agent v%s — Understand any codebase in minutes
Usage:
codebase-agent pentest <repo-path> AI penetration test with PoC exploits
codebase-agent security <repo-path> Security scan + threat model + vuln report
codebase-agent understand <repo-path> Generate docs + interactive HTML
codebase-agent understand <repo-path> --exclude dir1,dir2 Skip specific directories
codebase-agent understand <repo-path> --include src,lib Only scan specific directories
codebase-agent ask <repo-path> Interactive Q&A
codebase-agent ask <repo-path> -q "question" Single question
codebase-agent scan <repo-path> Show repo stats
Flags:
--local Use local Ollama instead of cloud (requires ollama + model)
--exclude Comma-separated directories to skip
--include Comma-separated directories to scan (only these)
Examples:
codebase-agent pentest ./my-project
codebase-agent security ./my-project
codebase-agent understand ./my-project
codebase-agent ask ./my-project -q "How does auth work?"
`, version)
}
func cmdUnderstand(repoPath string, args []string) {
// Parse flags
var opts *scanner.ScanOptions
useLocal := false
for i, arg := range args {
if opts == nil {
opts = &scanner.ScanOptions{}
}
if arg == "--exclude" && i+1 < len(args) {
opts.ExcludeDirs = strings.Split(args[i+1], ",")
}
if arg == "--include" && i+1 < len(args) {
opts.IncludeDirs = strings.Split(args[i+1], ",")
}
if arg == "--local" {
useLocal = true
}
}
fmt.Printf("⏳ Scanning %s...\n", repoPath)
if opts != nil && len(opts.ExcludeDirs) > 0 {
fmt.Printf(" Excluding: %s\n", strings.Join(opts.ExcludeDirs, ", "))
}
if opts != nil && len(opts.IncludeDirs) > 0 {
fmt.Printf(" Including only: %s\n", strings.Join(opts.IncludeDirs, ", "))
}
summary, err := scanner.ScanRepoWithOptions(repoPath, opts)
if err != nil {
fmt.Printf("❌ Error: %v\n", err)
os.Exit(1)
}
fmt.Printf("✅ Loaded %d files (%d lines) across %d languages\n\n",
summary.TotalFiles, summary.TotalLines, len(summary.Languages))
absPath, _ := filepath.Abs(repoPath)
outDir := filepath.Join(absPath, "understanding")
fmt.Printf("📝 Generating code understanding docs → %s/\n\n", outDir)
gen := understand.NewGenerator(summary, outDir, useLocal)
if useLocal {
fmt.Println(" Using local Ollama")
} else {
fmt.Println(" Using Ollama Cloud")
}
if err := gen.Generate(); err != nil {
fmt.Printf("\n❌ Error: %v\n", err)
os.Exit(1)
}
fmt.Printf("\n🎉 Done! Check the understanding/ directory:\n")
fmt.Printf(" 📄 understanding/INDEX.md — Start here\n")
fmt.Printf(" 📄 understanding/README.md — Project overview\n")
fmt.Printf(" 📄 understanding/architecture.md — System diagrams\n")
fmt.Printf(" 📄 understanding/data-flow.md — Data flow analysis\n")
fmt.Printf(" 📄 understanding/module-map.md — Module relationships\n")
fmt.Printf(" 🌐 understanding/index.html — Interactive website\n")
fmt.Printf("\n Open in browser: file://%s/index.html\n", outDir)
}
func cmdPentest(repoPath string, args []string) {
var opts *scanner.ScanOptions
useLocal := false
for i, arg := range args {
if opts == nil {
opts = &scanner.ScanOptions{}
}
if arg == "--exclude" && i+1 < len(args) {
opts.ExcludeDirs = strings.Split(args[i+1], ",")
}
if arg == "--include" && i+1 < len(args) {
opts.IncludeDirs = strings.Split(args[i+1], ",")
}
if arg == "--local" {
useLocal = true
}
}
fmt.Printf("⚔️ Penetration test: %s\n", repoPath)
summary, err := scanner.ScanRepoWithOptions(repoPath, opts)
if err != nil {
fmt.Printf("❌ Error: %v\n", err)
os.Exit(1)
}
fmt.Printf("✅ Loaded %d files (%d lines) across %d languages\n\n",
summary.TotalFiles, summary.TotalLines, len(summary.Languages))
absPath, _ := filepath.Abs(repoPath)
outDir := filepath.Join(absPath, "pentest-report")
fmt.Printf("📝 Generating pentest report → %s/\n\n", outDir)
gen := pentest.NewGenerator(summary, outDir, useLocal)
if err := gen.Generate(); err != nil {
fmt.Printf("\n❌ Error: %v\n", err)
os.Exit(1)
}
fmt.Printf("\n⚔️ Pentest report complete!\n")
fmt.Printf(" 💉 pentest-report/injection-report.md — Injection attacks + PoC payloads\n")
fmt.Printf(" 🔓 pentest-report/auth-attack-report.md — Auth bypass + session attacks\n")
fmt.Printf(" 📡 pentest-report/data-exposure-report.md — Data leakage + extraction\n")
fmt.Printf(" 🧠 pentest-report/business-logic-report.md — Logic flaws + race conditions\n")
fmt.Printf(" 🌐 pentest-report/index.html — Interactive report\n")
fmt.Printf("\n ⚠️ CONFIDENTIAL — Contains exploit payloads\n")
fmt.Printf(" Open in browser: file://%s/index.html\n", outDir)
}
func cmdSecurity(repoPath string, args []string) {
var opts *scanner.ScanOptions
useLocal := false
for i, arg := range args {
if opts == nil {
opts = &scanner.ScanOptions{}
}
if arg == "--exclude" && i+1 < len(args) {
opts.ExcludeDirs = strings.Split(args[i+1], ",")
}
if arg == "--include" && i+1 < len(args) {
opts.IncludeDirs = strings.Split(args[i+1], ",")
}
if arg == "--local" {
useLocal = true
}
}
fmt.Printf("🔒 Security scan: %s\n", repoPath)
summary, err := scanner.ScanRepoWithOptions(repoPath, opts)
if err != nil {
fmt.Printf("❌ Error: %v\n", err)
os.Exit(1)
}
fmt.Printf("✅ Loaded %d files (%d lines) across %d languages\n\n",
summary.TotalFiles, summary.TotalLines, len(summary.Languages))
absPath, _ := filepath.Abs(repoPath)
outDir := filepath.Join(absPath, "security-report")
fmt.Printf("📝 Generating security report → %s/\n\n", outDir)
gen := security.NewGenerator(summary, outDir, useLocal)
if err := gen.Generate(); err != nil {
fmt.Printf("\n❌ Error: %v\n", err)
os.Exit(1)
}
fmt.Printf("\n🎉 Security report complete!\n")
fmt.Printf(" 🎯 security-report/threat-model.md — STRIDE threat model\n")
fmt.Printf(" 🐛 security-report/vulnerabilities.md — Vulnerability findings\n")
fmt.Printf(" 🔑 security-report/secrets-audit.md — Secrets & data exposure\n")
fmt.Printf(" 🛡️ security-report/security-architecture.md — Security design review\n")
fmt.Printf(" 🌐 security-report/index.html — Interactive report\n")
fmt.Printf("\n Open in browser: file://%s/index.html\n", outDir)
}
func cmdScan(repoPath string) {
fmt.Printf("⏳ Scanning %s...\n", repoPath)
summary, err := scanner.ScanRepo(repoPath)
if err != nil {
fmt.Printf("❌ Error: %v\n", err)
os.Exit(1)
}
fmt.Printf("\n📁 %s\n", summary.Name)
fmt.Printf(" Files: %d\n", summary.TotalFiles)
fmt.Printf(" Lines: %d\n", summary.TotalLines)
fmt.Printf(" Languages:\n")
for lang, count := range summary.Languages {
fmt.Printf(" %s: %d files\n", lang, count)
}
fmt.Printf("\n📄 File tree:\n")
for _, f := range summary.Files {
fmt.Printf(" %s (%d lines)\n", f.RelPath, f.LineCount)
}
}
func cmdAsk(repoPath string, args []string) {
// Parse flags
var singleQuestion string
useLocal := false
for i, arg := range args {
if arg == "-q" && i+1 < len(args) {
singleQuestion = args[i+1]
}
if arg == "--local" {
useLocal = true
}
}
fmt.Printf("⏳ Scanning %s...\n", repoPath)
summary, err := scanner.ScanRepo(repoPath)
if err != nil {
fmt.Printf("❌ Error: %v\n", err)
os.Exit(1)
}
fmt.Printf("✅ Loaded %d files (%d lines) across %d languages\n",
summary.TotalFiles, summary.TotalLines, len(summary.Languages))
// Build context
context := scanner.BuildContext(summary, maxContextChars)
var client *ollama.Client
if useLocal {
client = ollama.NewLocalClient()
} else {
client = ollama.NewClient()
}
// System message with repo context
messages := []ollama.Message{
{
Role: "system",
Content: systemPrompt + "\n\n" + context,
},
}
if singleQuestion != "" {
// Single question mode
fmt.Printf("\n🤔 Thinking...\n\n")
messages = append(messages, ollama.Message{
Role: "user",
Content: singleQuestion,
})
_, err := client.ChatStream(messages, func(chunk string) {
fmt.Print(chunk)
})
fmt.Println()
if err != nil {
fmt.Printf("\n❌ Error: %v\n", err)
os.Exit(1)
}
return
}
// Interactive mode
fmt.Printf("\n💬 Ask anything about %s\n", summary.Name)
fmt.Printf(" Type your question and press Enter. Type 'quit' to exit.\n\n")
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("→ ")
input, err := reader.ReadString('\n')
if err != nil {
break
}
input = strings.TrimSpace(input)
if input == "" {
continue
}
if input == "quit" || input == "exit" || input == "q" {
fmt.Println("Bye!")
break
}
messages = append(messages, ollama.Message{
Role: "user",
Content: input,
})
fmt.Println()
response, err := client.ChatStream(messages, func(chunk string) {
fmt.Print(chunk)
})
fmt.Println("\n")
if err != nil {
fmt.Printf("❌ Error: %v\n\n", err)
continue
}
// Add assistant response to history
messages = append(messages, ollama.Message{
Role: "assistant",
Content: response,
})
// Keep history manageable (system + last 20 messages)
if len(messages) > 21 {
messages = append(messages[:1], messages[len(messages)-20:]...)
}
}
}