-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathmain.go
More file actions
7036 lines (6053 loc) · 213 KB
/
main.go
File metadata and controls
7036 lines (6053 loc) · 213 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
package main
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"io"
"log/slog"
"math/rand"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/charmbracelet/bubbles/spinner"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/joho/godotenv"
_ "github.com/mattn/go-sqlite3"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/pkg/browser"
"github.com/shurcooL/githubv4"
"golang.org/x/oauth2"
)
// Database schema version GUID - change this on any schema modification
const SCHEMA_GUID = "b8f3c2a1-9e7d-4f6b-8c5a-3d2e1f0a9b8c"
// OAuth App Client ID (public, safe to embed)
// Scopes: read:org repo
// Register at: https://github.com/settings/developers
const GitHubClientID = "Ov23ctgXe80Z1KsXE3vJ"
// Version information (set via ldflags at build time)
var (
Version = "dev"
BuildDate = "unknown"
)
// Global variables for rate limit handling and status tracking
var (
rateLimitMutex sync.Mutex
rateLimitHit bool
rateLimitResetTime time.Time
secondaryRateLimitHit bool
secondaryResetTime time.Time
backoffDuration time.Duration = 5 * time.Second // Increased from 1s to 5s for better handling
maxBackoffDuration time.Duration = 10 * time.Minute // Keep at 10 minutes max
// Rate limit information from headers
currentRateLimit RateLimitInfo = RateLimitInfo{Limit: -1, Remaining: -1, Used: -1} // Initialize with -1 for unknown
rateLimitInfoMutex sync.RWMutex
// Status code counters
statusCounters StatusCounters
statusMutex sync.Mutex
)
// UI Colors - semantic names for ANSI 256 colors
var (
borderColor = lipgloss.AdaptiveColor{Light: "#874BFD", Dark: "#7D56F4"} // Purple
accentColor = lipgloss.Color("12") // Bright blue
dimColor = lipgloss.Color("240") // Gray
successColor = lipgloss.Color("10") // Bright green
errorColor = lipgloss.Color("9") // Bright red
warnColor = lipgloss.Color("220") // Gold/yellow
)
// UI Styles - defined once, used throughout
var (
titleStyle = lipgloss.NewStyle().Bold(true)
dimStyle = lipgloss.NewStyle().Foreground(dimColor)
successStyle = lipgloss.NewStyle().Foreground(successColor)
errorStyle = lipgloss.NewStyle().Foreground(errorColor)
accentStyle = lipgloss.NewStyle().Foreground(accentColor)
selectedStyle = lipgloss.NewStyle().Foreground(accentColor).Bold(true)
selectorStyle = lipgloss.NewStyle().Foreground(accentColor)
)
// boxStyle creates a standard box with rounded border
func boxStyle(width int) lipgloss.Style {
return lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).
BorderForeground(borderColor).
Padding(0, 1).
Width(width)
}
// renderTitleBar renders a title bar with left title and right-aligned user status
func renderTitleBar(screen, username, organization string, innerWidth int) string {
leftTitle := fmt.Sprintf("GitHub Brain / %s", screen)
// Build right side: @username · 🏢 org · version
var rightParts []string
if username != "" {
rightParts = append(rightParts, fmt.Sprintf("👤 @%s", username))
}
if organization != "" {
rightParts = append(rightParts, fmt.Sprintf("🏢 %s", organization))
}
// Join parts with separator
rightStatus := strings.Join(rightParts, " · ")
if rightStatus != "" {
rightStatus += " · "
}
leftWidth := lipgloss.Width(leftTitle)
versionText := Version
versionWidth := lipgloss.Width(versionText)
rightWidth := lipgloss.Width(rightStatus) + versionWidth
spacing := innerWidth - leftWidth - rightWidth
if spacing < 1 {
spacing = 1
}
return titleStyle.Render(leftTitle) + strings.Repeat(" ", spacing) + titleStyle.Render(rightStatus) + dimStyle.Render(versionText)
}
// Removed ConsoleHandler - not needed with Bubble Tea
// BubbleTeaHandler is a custom slog handler that routes logs to Bubble Tea UI
type BubbleTeaHandler struct {
program *tea.Program
}
// NewBubbleTeaHandler creates a new slog handler that sends logs to Bubble Tea
func NewBubbleTeaHandler(program *tea.Program) *BubbleTeaHandler {
return &BubbleTeaHandler{program: program}
}
func (h *BubbleTeaHandler) Enabled(_ context.Context, _ slog.Level) bool {
return true
}
func (h *BubbleTeaHandler) Handle(_ context.Context, r slog.Record) error {
// Build message with attributes
var b strings.Builder
b.WriteString(r.Message)
// Add structured attributes as key=value pairs
if r.NumAttrs() > 0 {
first := true
r.Attrs(func(a slog.Attr) bool {
if first {
b.WriteString(" ")
first = false
} else {
b.WriteString(", ")
}
b.WriteString(fmt.Sprintf("%s=%v", a.Key, a.Value))
return true
})
}
// Send to Bubble Tea
if h.program != nil {
h.program.Send(logMsg(b.String()))
}
return nil
}
func (h *BubbleTeaHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return h // Simplified - we don't need to accumulate attrs
}
func (h *BubbleTeaHandler) WithGroup(name string) slog.Handler {
return h // Simplified - we don't need group support
}
// RateLimitInfo holds rate limit information from GitHub API headers
type RateLimitInfo struct {
Limit int // x-ratelimit-limit (default -1 for unknown)
Remaining int // x-ratelimit-remaining (default -1 for unknown)
Used int // x-ratelimit-used (default -1 for unknown)
Reset time.Time // x-ratelimit-reset (Unix timestamp)
}
// StatusCounters tracks HTTP response status codes
type StatusCounters struct {
Success2XX int // 2XX status codes
Error4XX int // 4XX status codes
Error5XX int // 5XX status codes
}
// addRequestDelay adds a delay between API requests to help avoid secondary rate limits
func addRequestDelay() {
// Check if we're in a secondary rate limit state - if so, use longer delays
rateLimitMutex.Lock()
inSecondaryLimit := secondaryRateLimitHit
inPrimaryLimit := rateLimitHit
rateLimitMutex.Unlock()
var delay time.Duration
if inSecondaryLimit {
// Much longer delay when we're recovering from secondary rate limits
delay = time.Duration(7000+rand.Intn(3000)) * time.Millisecond // 7-10 seconds
} else if inPrimaryLimit {
// Longer delay when recovering from primary rate limits
delay = time.Duration(5000+rand.Intn(3000)) * time.Millisecond // 5-8 seconds
} else {
// Check current rate limit status for adaptive delays based on points utilization
rateLimitInfoMutex.RLock()
remaining := currentRateLimit.Remaining
limit := currentRateLimit.Limit
rateLimitInfoMutex.RUnlock()
if remaining > 0 && limit > 0 {
// Calculate points utilization (GitHub's rate limiting is points-based)
pointsUsed := float64(limit-remaining) / float64(limit)
if pointsUsed > 0.9 { // Above 90% points used
// Very conservative delay when close to rate limit
delay = time.Duration(3000+rand.Intn(2000)) * time.Millisecond // 3-5 seconds
} else if pointsUsed > 0.7 { // Above 70% points used
// More conservative delay
delay = time.Duration(2000+rand.Intn(1000)) * time.Millisecond // 2-3 seconds
} else if pointsUsed > 0.5 { // Above 50% points used
// Moderate delay
delay = time.Duration(1000+rand.Intn(1000)) * time.Millisecond // 1-2 seconds
} else {
// Normal delay (GitHub recommends 1+ second between mutations)
delay = time.Duration(1000+rand.Intn(500)) * time.Millisecond // 1-1.5 seconds
}
} else {
// Default delay when rate limit info is unknown - be conservative
delay = time.Duration(1500+rand.Intn(1000)) * time.Millisecond // 1.5-2.5 seconds
}
}
time.Sleep(delay)
}
// updateRateLimitInfo updates the global rate limit information from HTTP headers
func updateRateLimitInfo(headers http.Header) {
rateLimitInfoMutex.Lock()
defer rateLimitInfoMutex.Unlock()
if val, ok := parseHeaderInt(headers, "x-ratelimit-limit"); ok {
currentRateLimit.Limit = val
}
if val, ok := parseHeaderInt(headers, "x-ratelimit-remaining"); ok {
currentRateLimit.Remaining = val
}
if val, ok := parseHeaderInt(headers, "x-ratelimit-used"); ok {
currentRateLimit.Used = val
}
if reset := headers.Get("x-ratelimit-reset"); reset != "" {
if val, err := strconv.ParseInt(reset, 10, 64); err == nil {
currentRateLimit.Reset = time.Unix(val, 0)
}
}
}
// updateStatusCounter increments the appropriate status code counter
func updateStatusCounter(statusCode int) {
statusMutex.Lock()
defer statusMutex.Unlock()
switch {
case statusCode >= 200 && statusCode < 300:
statusCounters.Success2XX++
case statusCode >= 400 && statusCode < 500:
statusCounters.Error4XX++
case statusCode >= 500:
statusCounters.Error5XX++
}
}
// CustomTransport wraps the default HTTP transport to capture response headers and status codes
type CustomTransport struct {
wrapped http.RoundTripper
}
func (ct *CustomTransport) RoundTrip(req *http.Request) (*http.Response, error) {
resp, err := ct.wrapped.RoundTrip(req)
if resp != nil {
// Update status counters
updateStatusCounter(resp.StatusCode)
// Update rate limit info from headers
updateRateLimitInfo(resp.Header)
// Handle 429 status code (rate limit) with Retry-After header
if resp.StatusCode == 429 {
retryAfter := resp.Header.Get("Retry-After")
rateLimitMutex.Lock()
defer rateLimitMutex.Unlock()
// Check if this is secondary rate limit (abuse detection)
// GitHub secondary rate limits typically have abuse detection messages
if retryAfter != "" {
if retryAfterInt, parseErr := strconv.Atoi(retryAfter); parseErr == nil {
waitDuration := time.Duration(retryAfterInt) * time.Second
// Cap the wait time to prevent excessive waiting
maxWaitTime := 10 * time.Minute
if waitDuration > maxWaitTime {
slog.Warn("Capping excessive Retry-After duration", "from", waitDuration, "to", maxWaitTime)
waitDuration = maxWaitTime
}
// Set secondary rate limit if this appears to be abuse detection
// (typically longer wait times indicate secondary rate limits)
if waitDuration > 60*time.Second {
secondaryRateLimitHit = true
secondaryResetTime = time.Now().Add(waitDuration)
slog.Info("GitHub API secondary rate limit (429) detected", "retry_after", waitDuration.String(), "until", secondaryResetTime.Format(time.RFC3339))
} else {
// Shorter wait times are likely primary rate limits
rateLimitHit = true
rateLimitResetTime = time.Now().Add(waitDuration)
slog.Info("GitHub API primary rate limit (429) detected", "retry_after", waitDuration.String(), "until", rateLimitResetTime.Format(time.RFC3339))
}
}
} else {
// No Retry-After header, assume secondary rate limit with default backoff
secondaryRateLimitHit = true
waitDuration := backoffDuration
// Increase backoff for next time (exponential backoff)
backoffDuration = backoffDuration * 2
if backoffDuration > maxBackoffDuration {
backoffDuration = maxBackoffDuration
}
secondaryResetTime = time.Now().Add(waitDuration)
slog.Info("GitHub API secondary rate limit (429) detected without Retry-After", "backoff", waitDuration.String(), "until", secondaryResetTime.Format(time.RFC3339))
}
}
}
return resp, err
}
func init() {
// No need to seed the random number generator in Go 1.20+
// It's automatically seeded with a random value
}
// Config holds all application configuration
type Config struct {
GithubToken string
Organization string
HomeDir string // GitHub Brain home directory (default: ~/.github-brain)
DBDir string // SQLite database path, constructed as <HomeDir>/db
Items []string // Items to pull (repositories, discussions, issues, pull-requests)
Force bool // Remove all data before pulling
ExcludedRepositories []string // Comma-separated list of repositories to exclude from the pull of discussions, issues, and pull-requests
}
// LoadConfig creates a config from command line arguments and environment variables
// Command line arguments take precedence over environment variables
func LoadConfig(args []string) *Config {
// Get default home directory with expansion
defaultHomeDir := os.Getenv("HOME")
if defaultHomeDir == "" {
defaultHomeDir = "."
}
defaultHomeDir = defaultHomeDir + "/.github-brain"
config := &Config{
HomeDir: defaultHomeDir,
}
// Load from environment variables first
config.GithubToken = os.Getenv("GITHUB_TOKEN")
config.Organization = os.Getenv("ORGANIZATION")
if excludedRepos := os.Getenv("EXCLUDED_REPOSITORIES"); excludedRepos != "" {
config.ExcludedRepositories = splitItems(excludedRepos)
}
// Command line args override environment variables
for i := 0; i < len(args); i++ {
switch args[i] {
case "-o":
if i+1 < len(args) {
config.Organization = args[i+1]
i++
}
case "-m":
if i+1 < len(args) {
homeDir := args[i+1]
// Expand ~ to home directory
if strings.HasPrefix(homeDir, "~/") {
userHomeDir := os.Getenv("HOME")
if userHomeDir != "" {
homeDir = userHomeDir + homeDir[1:]
}
}
config.HomeDir = homeDir
i++
}
case "-i":
if i+1 < len(args) {
config.Items = splitItems(args[i+1])
i++
}
case "-e":
if i+1 < len(args) {
config.ExcludedRepositories = splitItems(args[i+1])
i++
}
case "-f":
config.Force = true
}
}
// Construct DBDir from HomeDir after all arguments are parsed
config.DBDir = config.HomeDir + "/db"
return config
}
// isRepositoryExcluded checks if a repository is in the excluded list
func isRepositoryExcluded(repoName string, excludedRepos []string) bool {
for _, excluded := range excludedRepos {
if strings.TrimSpace(excluded) == strings.TrimSpace(repoName) {
return true
}
}
return false
}
// splitItems splits a comma-separated items list
func splitItems(items string) []string {
if items == "" {
return nil
}
itemNames := strings.Split(items, ",")
for i, name := range itemNames {
itemNames[i] = strings.TrimSpace(name)
}
return itemNames
}
// Removed Console struct - Bubble Tea handles all rendering
// formatNumber formats numbers with comma separators for better readability
func formatNumber(n int) string {
if n < 1000 {
return strconv.Itoa(n)
}
str := strconv.Itoa(n)
var result strings.Builder
for i, digit := range str {
if i > 0 && (len(str)-i)%3 == 0 {
result.WriteString(",")
}
result.WriteRune(digit)
}
return result.String()
}
// formatTimeRemaining formats duration in human-friendly format
func formatTimeRemaining(resetTime time.Time) string {
if resetTime.IsZero() {
return "?"
}
remaining := time.Until(resetTime)
if remaining <= 0 {
return "now"
}
hours := int(remaining.Hours())
minutes := int(remaining.Minutes()) % 60
seconds := int(remaining.Seconds()) % 60
if hours > 0 {
if minutes > 0 {
return fmt.Sprintf("%dh %dm", hours, minutes)
}
return fmt.Sprintf("%dh", hours)
} else if minutes > 0 {
return fmt.Sprintf("%dm", minutes)
} else {
return fmt.Sprintf("%ds", seconds)
}
}
// max returns the maximum of two integers
// capitalize first letter of a string
func capitalize(s string) string {
if s == "" {
return ""
}
// Handle special cases for display names
switch s {
case "pull-requests":
return "Pull Requests"
default:
return strings.ToUpper(s[:1]) + s[1:]
}
}
// visibleLength calculates the visible length of a string, ignoring ANSI escape codes
// This handles all CSI (Control Sequence Introducer) escape sequences
func visibleLength(s string) int {
length := 0
i := 0
runes := []rune(s)
for i < len(runes) {
if runes[i] == '\033' && i+1 < len(runes) && runes[i+1] == '[' {
// Skip CSI sequence: ESC [ ... (terminated by a letter)
i += 2
for i < len(runes) && (runes[i] < 'A' || runes[i] > 'Z') && (runes[i] < 'a' || runes[i] > 'z') {
i++
}
i++ // Skip the terminating letter
} else if runes[i] == '\033' {
// Skip other escape sequences (ESC followed by one char)
i += 2
} else {
// Count display width (emojis are typically 2 columns wide)
if isWideChar(runes[i]) {
length += 2
} else {
length++
}
i++
}
}
return length
}
// isWideChar returns true if the rune is a wide character (emoji or CJK)
func isWideChar(r rune) bool {
// Common emoji ranges and wide characters
return (r >= 0x1F300 && r <= 0x1F9FF) || // Misc Symbols and Pictographs, Emoticons, etc.
(r >= 0x2600 && r <= 0x26FF) || // Misc symbols
(r >= 0x2700 && r <= 0x27BF) || // Dingbats
(r >= 0xFE00 && r <= 0xFE0F) || // Variation Selectors
(r >= 0x1F000 && r <= 0x1F02F) || // Mahjong Tiles, Domino Tiles
(r >= 0x1F0A0 && r <= 0x1F0FF) || // Playing Cards
(r >= 0x1F100 && r <= 0x1F64F) || // Enclosed characters, Emoticons
(r >= 0x1F680 && r <= 0x1F6FF) || // Transport and Map Symbols
(r >= 0x1F900 && r <= 0x1F9FF) || // Supplemental Symbols and Pictographs
(r >= 0x3000 && r <= 0x303F) || // CJK Symbols and Punctuation
(r >= 0x3040 && r <= 0x309F) || // Hiragana
(r >= 0x30A0 && r <= 0x30FF) || // Katakana
(r >= 0x4E00 && r <= 0x9FFF) || // CJK Unified Ideographs
(r >= 0xAC00 && r <= 0xD7AF) // Hangul Syllables
}
// Old Progress struct and Console removed - now using Bubble Tea for UI rendering
// See ProgressInterface and UIProgress below after DB section
// DB represents the database connection
type DB struct {
db *sql.DB
}
// QueryRow is a wrapper for sql.DB.QueryRow
func (d *DB) QueryRow(query string, args ...interface{}) *sql.Row {
return d.db.QueryRow(query, args...)
}
// Query is a wrapper for sql.DB.Query
func (d *DB) Query(query string, args ...interface{}) (*sql.Rows, error) {
return d.db.Query(query, args...)
}
// Exec is a wrapper for sql.DB.Exec
func (d *DB) Exec(query string, args ...interface{}) (sql.Result, error) {
return d.db.Exec(query, args...)
}
// Close is a wrapper for sql.DB.Close
func (d *DB) Close() error {
return d.db.Close()
}
// Repository represents a GitHub repository
type Repository struct {
Name string `json:"name"` // Repository name without organization prefix
UpdatedAt time.Time `json:"updated_at"` // Last update timestamp
HasIssuesEnabled bool `json:"has_issues_enabled"` // Whether issues are enabled for this repository
HasDiscussionsEnabled bool `json:"has_discussions_enabled"` // Whether discussions are enabled for this repository
}
// Discussion represents a GitHub discussion
type Discussion struct {
URL string `json:"url"` // Primary key
Title string `json:"title"` // Discussion title
Body string `json:"body"` // Discussion content
CreatedAt time.Time `json:"created_at"` // Creation timestamp
UpdatedAt time.Time `json:"updated_at"` // Last update timestamp
Repository string `json:"repository"` // Repository name without organization prefix
Author string `json:"author"` // Username
}
// Issue represents a GitHub issue
type Issue struct {
URL string `json:"url"` // Primary key
Title string `json:"title"` // Issue title
Body string `json:"body"` // Issue content
CreatedAt time.Time `json:"created_at"` // Creation timestamp
UpdatedAt time.Time `json:"updated_at"` // Last update timestamp
ClosedAt *time.Time `json:"closed_at"` // Close timestamp (null if open)
Repository string `json:"repository"` // Repository name without organization prefix
Author string `json:"author"` // Username
}
// PullRequest represents a GitHub pull request
type PullRequest struct {
URL string `json:"url"` // Primary key
Title string `json:"title"` // Pull request title
Body string `json:"body"` // Pull request content
CreatedAt time.Time `json:"created_at"` // Creation timestamp
UpdatedAt time.Time `json:"updated_at"` // Last update timestamp
MergedAt *time.Time `json:"merged_at"` // Merge timestamp (null if not merged)
ClosedAt *time.Time `json:"closed_at"` // Close timestamp (null if open)
Repository string `json:"repository"` // Repository name without organization prefix
Author string `json:"author"` // Username
}
// MCPRequest represents an MCP request
type MCPRequest struct {
Name string `json:"name"`
Parameters json.RawMessage `json:"parameters"`
}
// MCPResponse represents an MCP response
type MCPResponse struct {
Result interface{} `json:"result"`
Error string `json:"error,omitempty"`
}
// ListDiscussionsParams represents parameters for list_discussions
type ListDiscussionsParams struct {
Repository string `json:"repository"`
CreatedFrom string `json:"created_from,omitempty"`
CreatedTo string `json:"created_to,omitempty"`
Authors []string `json:"authors,omitempty"`
Fields []string `json:"fields,omitempty"`
}
// ListIssuesParams represents parameters for list_issues
type ListIssuesParams struct {
Repository string `json:"repository"`
CreatedFrom string `json:"created_from,omitempty"`
CreatedTo string `json:"created_to,omitempty"`
ClosedFrom string `json:"closed_from,omitempty"`
ClosedTo string `json:"closed_to,omitempty"`
Authors []string `json:"authors,omitempty"`
Fields []string `json:"fields,omitempty"`
}
// ListPullRequestsParams represents parameters for list_pull_requests
type ListPullRequestsParams struct {
Repository string `json:"repository"`
CreatedFrom string `json:"created_from,omitempty"`
CreatedTo string `json:"created_to,omitempty"`
ClosedFrom string `json:"closed_from,omitempty"`
ClosedTo string `json:"closed_to,omitempty"`
MergedFrom string `json:"merged_from,omitempty"`
MergedTo string `json:"merged_to,omitempty"`
Authors []string `json:"authors,omitempty"`
Fields []string `json:"fields,omitempty"`
}
// InitDB initializes the database
// getDBPath returns the database path for a specific organization
func getDBPath(dbDir, organization string) string {
return fmt.Sprintf("%s/%s.db", dbDir, organization)
}
// checkSchemaVersion checks if the database schema version matches current SCHEMA_GUID
// Returns true if schema is current, false if database needs recreation
func checkSchemaVersion(db *sql.DB, progress ProgressInterface) (bool, error) {
// Check if schema_version table exists
var tableExists int
err := db.QueryRow("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='schema_version'").Scan(&tableExists)
if err != nil {
return false, fmt.Errorf("failed to check schema_version table existence: %w", err)
}
if tableExists == 0 {
if progress != nil {
progress.Log("No schema_version table found - database recreation needed")
} else {
slog.Info("No schema_version table found - database recreation needed")
}
return false, nil
}
// Read stored GUID
var storedGUID string
err = db.QueryRow("SELECT guid FROM schema_version LIMIT 1").Scan(&storedGUID)
if err != nil {
if err == sql.ErrNoRows {
if progress != nil {
progress.Log("No schema version GUID found - database recreation needed")
} else {
slog.Info("No schema version GUID found - database recreation needed")
}
return false, nil
}
return false, fmt.Errorf("failed to read schema version: %w", err)
}
// Compare GUIDs
if storedGUID != SCHEMA_GUID {
if progress != nil {
progress.Log("Schema version mismatch (stored: %s, current: %s) - database recreation needed", storedGUID, SCHEMA_GUID)
} else {
slog.Info("Schema version mismatch - database recreation needed", "stored", storedGUID, "current", SCHEMA_GUID)
}
return false, nil
}
if progress != nil {
progress.Log("Schema version matches - using existing database")
} else {
slog.Info("Schema version matches - using existing database")
}
return true, nil
}
// createAllTables creates all database tables and indexes
func createAllTables(db *sql.DB, progress ProgressInterface) error {
// Create schema_version table and store current GUID
_, err := db.Exec(`
CREATE TABLE schema_version (
guid TEXT PRIMARY KEY
)
`)
if err != nil {
return fmt.Errorf("failed to create schema_version table: %w", err)
}
// Store current schema GUID
_, err = db.Exec("INSERT INTO schema_version (guid) VALUES (?)", SCHEMA_GUID)
if err != nil {
return fmt.Errorf("failed to store schema version: %w", err)
}
// Create repositories table
_, err = db.Exec(`
CREATE TABLE repositories (
name TEXT PRIMARY KEY,
has_discussions_enabled BOOLEAN DEFAULT 0,
has_issues_enabled BOOLEAN DEFAULT 0,
updated_at DATETIME
)
`)
if err != nil {
return fmt.Errorf("failed to create repositories table: %w", err)
}
// Create performance index for repositories table
_, err = db.Exec("CREATE INDEX idx_repositories_updated_at ON repositories (updated_at)")
if err != nil {
return fmt.Errorf("failed to create updated_at index on repositories table: %w", err)
}
// Create discussions table
_, err = db.Exec(`
CREATE TABLE discussions (
url TEXT PRIMARY KEY,
title TEXT NOT NULL,
body TEXT NOT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
repository TEXT NOT NULL,
author TEXT NOT NULL
)
`)
if err != nil {
return fmt.Errorf("failed to create discussions table: %w", err)
}
// Create indexes for discussions table
_, err = db.Exec("CREATE INDEX idx_discussions_repository ON discussions (repository)")
if err != nil {
return fmt.Errorf("failed to create repository index on discussions table: %w", err)
}
_, err = db.Exec("CREATE INDEX idx_discussions_author ON discussions (author)")
if err != nil {
return fmt.Errorf("failed to create author index on discussions table: %w", err)
}
// Create performance indexes for discussions table
_, err = db.Exec("CREATE INDEX idx_discussions_created_at ON discussions (created_at)")
if err != nil {
return fmt.Errorf("failed to create created_at index on discussions table: %w", err)
}
_, err = db.Exec("CREATE INDEX idx_discussions_updated_at ON discussions (updated_at)")
if err != nil {
return fmt.Errorf("failed to create updated_at index on discussions table: %w", err)
}
// Composite index for common query patterns: repository + created_at
_, err = db.Exec("CREATE INDEX idx_discussions_repo_created ON discussions (repository, created_at)")
if err != nil {
return fmt.Errorf("failed to create repository+created_at index on discussions table: %w", err)
}
// Create issues table
_, err = db.Exec(`
CREATE TABLE issues (
url TEXT PRIMARY KEY,
title TEXT NOT NULL,
body TEXT NOT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
closed_at DATETIME,
repository TEXT NOT NULL,
author TEXT NOT NULL
)
`)
if err != nil {
return fmt.Errorf("failed to create issues table: %w", err)
}
// Create indexes for issues table
_, err = db.Exec("CREATE INDEX idx_issues_repository ON issues (repository)")
if err != nil {
return fmt.Errorf("failed to create repository index on issues table: %w", err)
}
_, err = db.Exec("CREATE INDEX idx_issues_author ON issues (author)")
if err != nil {
return fmt.Errorf("failed to create author index on issues table: %w", err)
}
// Create performance indexes for issues table
_, err = db.Exec("CREATE INDEX idx_issues_created_at ON issues (created_at)")
if err != nil {
return fmt.Errorf("failed to create created_at index on issues table: %w", err)
}
_, err = db.Exec("CREATE INDEX idx_issues_updated_at ON issues (updated_at)")
if err != nil {
return fmt.Errorf("failed to create updated_at index on issues table: %w", err)
}
_, err = db.Exec("CREATE INDEX idx_issues_closed_at ON issues (closed_at)")
if err != nil {
return fmt.Errorf("failed to create closed_at index on issues table: %w", err)
}
// Composite index for common query patterns: repository + created_at
_, err = db.Exec("CREATE INDEX idx_issues_repo_created ON issues (repository, created_at)")
if err != nil {
return fmt.Errorf("failed to create repository+created_at index on issues table: %w", err)
}
// Create pull_requests table
_, err = db.Exec(`
CREATE TABLE pull_requests (
url TEXT PRIMARY KEY,
title TEXT NOT NULL,
body TEXT NOT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
merged_at DATETIME,
closed_at DATETIME,
repository TEXT NOT NULL,
author TEXT NOT NULL
)
`)
if err != nil {
return fmt.Errorf("failed to create pull_requests table: %w", err)
}
// Create indexes for pull_requests table
_, err = db.Exec("CREATE INDEX idx_pull_requests_repository ON pull_requests (repository)")
if err != nil {
return fmt.Errorf("failed to create repository index on pull_requests table: %w", err)
}
_, err = db.Exec("CREATE INDEX idx_pull_requests_author ON pull_requests (author)")
if err != nil {
return fmt.Errorf("failed to create author index on pull_requests table: %w", err)
}
// Create performance indexes for pull_requests table
_, err = db.Exec("CREATE INDEX idx_pull_requests_created_at ON pull_requests (created_at)")
if err != nil {
return fmt.Errorf("failed to create created_at index on pull_requests table: %w", err)
}
_, err = db.Exec("CREATE INDEX idx_pull_requests_updated_at ON pull_requests (updated_at)")
if err != nil {
return fmt.Errorf("failed to create updated_at index on pull_requests table: %w", err)
}
_, err = db.Exec("CREATE INDEX idx_pull_requests_closed_at ON pull_requests (closed_at)")
if err != nil {
return fmt.Errorf("failed to create closed_at index on pull_requests table: %w", err)
}
// Composite index for common query patterns: repository + created_at
_, err = db.Exec("CREATE INDEX idx_pull_requests_repo_created ON pull_requests (repository, created_at)")
if err != nil {
return fmt.Errorf("failed to create repository+created_at index on pull_requests table: %w", err)
}
// Create merged_at index
_, err = db.Exec("CREATE INDEX idx_pull_requests_merged_at ON pull_requests (merged_at)")
if err != nil {
return fmt.Errorf("failed to create merged_at index on pull_requests table: %w", err)
}
// Create lock table
_, err = db.Exec(`
CREATE TABLE lock (
id INTEGER PRIMARY KEY CHECK (id = 1),
locked INTEGER NOT NULL DEFAULT 0,
locked_at DATETIME
)
`)
if err != nil {
return fmt.Errorf("failed to create lock table: %w", err)
}
// Ensure single row exists in lock table
_, _ = db.Exec(`INSERT INTO lock (id, locked, locked_at) VALUES (1, 0, NULL)`)
// Create search table (FTS5) for full-text search
_, err = db.Exec(`
CREATE VIRTUAL TABLE search USING fts5(
type, title, body, url, repository, author, created_at UNINDEXED, state UNINDEXED, boost UNINDEXED
)
`)
if err != nil {
return fmt.Errorf("FTS5 not available in SQLite - rebuild with FTS5 support: %w", err)
}
return nil
}
func InitDB(dbDir, organization string, progress ProgressInterface) (*DB, error) {
dbPath := getDBPath(dbDir, organization)
// Log the full database file path being opened
if progress != nil {
progress.Log("Opening database at path: %s", dbPath)
} else {
slog.Info("Opening database at path", "path", dbPath)
}
// Extract directory from dbPath
lastSlash := strings.LastIndex(dbPath, "/")
if lastSlash != -1 {
dir := dbPath[:lastSlash]
// Create db directory if it doesn't exist
if _, err := os.Stat(dir); os.IsNotExist(err) {
if err := os.MkdirAll(dir, 0755); err != nil {
if progress != nil {
progress.Log("Error creating database directory %s: %v", dir, err)
} else {
slog.Error("Failed to create database directory", "dir", dir, "error", err)
}
return nil, fmt.Errorf("failed to create database directory %s: %w", dir, err)
}
}
}
// Check if database file exists and if schema version matches
needsRecreation := true
if _, err := os.Stat(dbPath); err == nil {
// Database exists, check schema version
tempDB, err := sql.Open("sqlite3", dbPath)
if err == nil {
defer func() {
if closeErr := tempDB.Close(); closeErr != nil {
slog.Warn("Failed to close temp database", "error", closeErr)
}
}()
schemaMatches, checkErr := checkSchemaVersion(tempDB, progress)
if checkErr != nil {
if progress != nil {
progress.Log("Error checking schema version: %v - recreating database", checkErr)
} else {
slog.Warn("Error checking schema version - recreating database", "error", checkErr)
}
} else if schemaMatches {
needsRecreation = false
}
}
}