-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathunified_processor_v2.go
More file actions
1686 lines (1430 loc) · 58.9 KB
/
unified_processor_v2.go
File metadata and controls
1686 lines (1430 loc) · 58.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
package api
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
"time"
mrmodel "github.com/livereview/cmd/mrmodel/lib"
"github.com/livereview/internal/aiconnectors"
"github.com/livereview/internal/aisanitize"
coreprocessor "github.com/livereview/internal/core_processor"
"github.com/livereview/internal/learnings"
bitbucketmentions "github.com/livereview/internal/providers/bitbucket"
githubmentions "github.com/livereview/internal/providers/github"
gitlabmentions "github.com/livereview/internal/providers/gitlab"
gl "github.com/livereview/internal/providers/gitlab"
"github.com/livereview/internal/reviewmodel"
)
// Phase 7.1: Unified processor for provider-agnostic LLM processing
// Extracted from webhook_handler.go - provider-independent AI response generation
// UnifiedProcessorV2Impl implements the UnifiedProcessorV2 interface
type UnifiedProcessorV2Impl struct {
server *Server // For accessing database operations and AI infrastructure
}
type bitbucketParentComment struct {
User struct {
Username string `json:"username"`
AccountID string `json:"account_id"`
UUID string `json:"uuid"`
} `json:"user"`
}
// NewUnifiedProcessorV2 creates a new unified processor instance
func NewUnifiedProcessorV2(server *Server) UnifiedProcessorV2 {
return &UnifiedProcessorV2Impl{
server: server,
}
}
func normalizeIdentifier(value string) string {
if value == "" {
return ""
}
trimmed := strings.TrimSpace(value)
trimmed = strings.Trim(trimmed, "{}")
return strings.ToLower(trimmed)
}
// CheckResponseWarrant determines if an event warrants an AI response (provider-agnostic)
// Extracted from checkAIResponseWarrant, checkUnifiedAIResponseWarrant
func (p *UnifiedProcessorV2Impl) CheckResponseWarrant(event UnifiedWebhookEventV2, botInfo *UnifiedBotUserInfoV2) (bool, ResponseScenarioV2) {
hardFailure := func(reason, missing string) (bool, ResponseScenarioV2) {
metadata := map[string]interface{}{
"provider": event.Provider,
}
if missing != "" {
metadata["missing"] = missing
}
log.Printf("[ERROR] Response warrant precondition failed: %s", reason)
return false, ResponseScenarioV2{
Type: "hard_failure",
Reason: reason,
Confidence: 0.0,
Metadata: metadata,
}
}
if event.Comment == nil {
return hardFailure("comment payload absent in webhook event", "event.comment")
}
commentBody := strings.TrimSpace(event.Comment.Body)
if commentBody == "" {
return hardFailure("comment body empty; cannot evaluate warrant", "event.comment.body")
}
if botInfo == nil {
return hardFailure("bot user info unavailable for warrant evaluation", "bot_info")
}
if strings.TrimSpace(botInfo.Username) == "" && strings.TrimSpace(botInfo.UserID) == "" {
return hardFailure("bot user info missing identifiers", "bot_info.identifiers")
}
log.Printf("[DEBUG] Checking AI response warrant for comment by %s", event.Comment.Author.Username)
log.Printf("[DEBUG] Comment content: %s", commentBody)
log.Printf("[DEBUG] Bot info available: Username=%s, UserID=%s, Name=%s, Metadata=%v", botInfo.Username, botInfo.UserID, botInfo.Name, botInfo.Metadata)
if event.Comment.InReplyToID != nil {
log.Printf("[DEBUG] Comment is a reply, InReplyToID=%s", *event.Comment.InReplyToID)
} else {
log.Printf("[DEBUG] Comment is not a reply (InReplyToID is nil)")
}
if event.Comment.DiscussionID != nil && *event.Comment.DiscussionID != "" {
log.Printf("[DEBUG] Comment discussion ID: %s", *event.Comment.DiscussionID)
}
contentType := p.classifyContentTypeV2(commentBody)
responseType := p.determineResponseTypeV2(commentBody)
makeMetadata := func() map[string]interface{} {
return map[string]interface{}{
"content_type": contentType,
"response_type": responseType,
}
}
if p.isCommentAuthoredByBot(event, botInfo) {
log.Printf("[DEBUG] Comment authored by registered bot user, skipping")
metadata := makeMetadata()
metadata["reason"] = "authored_by_bot"
return false, ResponseScenarioV2{
Type: "no_response",
Reason: "comment authored by bot",
Confidence: 0.0,
Metadata: metadata,
}
}
// Replies take precedence to prevent missed follow-ups.
isReply := event.Comment.InReplyToID != nil && *event.Comment.InReplyToID != ""
if isReply {
replyToBot, err := p.isReplyToBotComment(event, botInfo)
if err != nil {
log.Printf("[WARN] Failed to verify reply parent for provider %s: %v", event.Provider, err)
}
if replyToBot {
metadata := makeMetadata()
if event.Comment.InReplyToID != nil {
metadata["in_reply_to"] = *event.Comment.InReplyToID
}
log.Printf("[DEBUG] Reply to AI bot comment detected")
return true, ResponseScenarioV2{
Type: "bot_reply",
Reason: fmt.Sprintf("Reply to bot comment by %s", event.Comment.Author.Username),
Confidence: 0.90,
Metadata: metadata,
}
}
}
isDirectMention := p.checkDirectBotMentionV2(event, botInfo)
if isDirectMention {
log.Printf("[DEBUG] Direct bot mention detected in comment")
metadata := makeMetadata()
return true, ResponseScenarioV2{
Type: "direct_mention",
Reason: fmt.Sprintf("Direct mention of bot by %s", event.Comment.Author.Username),
Confidence: 0.95,
Metadata: metadata,
}
}
if !isReply {
log.Printf("[DEBUG] Top-level comment without direct mention, skipping per warrant policy")
metadata := makeMetadata()
metadata["reason"] = "top_level_not_addressed_to_bot"
return false, ResponseScenarioV2{
Type: "no_response",
Reason: "comment not directed at bot",
Confidence: 0.0,
Metadata: metadata,
}
}
log.Printf("[DEBUG] Reply present but parent not bot and no direct mention; skipping")
metadata := makeMetadata()
metadata["reason"] = "reply_not_directed_to_bot"
return false, ResponseScenarioV2{
Type: "no_response",
Reason: "comment not directed at bot",
Confidence: 0.0,
Metadata: metadata,
}
}
func (p *UnifiedProcessorV2Impl) isCommentAuthoredByBot(event UnifiedWebhookEventV2, botInfo *UnifiedBotUserInfoV2) bool {
if botInfo == nil || event.Comment == nil {
return false
}
botIdentifiers := map[string]string{}
if botInfo.UserID != "" {
botIdentifiers[normalizeIdentifier(botInfo.UserID)] = botInfo.UserID
}
if botInfo.Metadata != nil {
if accountID, ok := botInfo.Metadata["account_id"].(string); ok && accountID != "" {
botIdentifiers[normalizeIdentifier(accountID)] = accountID
}
if uuid, ok := botInfo.Metadata["uuid"].(string); ok && uuid != "" {
botIdentifiers[normalizeIdentifier(uuid)] = uuid
}
}
authorIdentifiers := map[string]string{}
if event.Comment.Author.ID != "" {
authorIdentifiers[normalizeIdentifier(event.Comment.Author.ID)] = event.Comment.Author.ID
}
if event.Comment.Author.Metadata != nil {
if accountID, ok := event.Comment.Author.Metadata["account_id"].(string); ok && accountID != "" {
authorIdentifiers[normalizeIdentifier(accountID)] = accountID
}
if uuid, ok := event.Comment.Author.Metadata["uuid"].(string); ok && uuid != "" {
authorIdentifiers[normalizeIdentifier(uuid)] = uuid
}
}
if event.Comment.Metadata != nil {
if accountID, ok := event.Comment.Metadata["account_id"].(string); ok && accountID != "" {
authorIdentifiers[normalizeIdentifier(accountID)] = accountID
}
if uuid, ok := event.Comment.Metadata["user_uuid"].(string); ok && uuid != "" {
authorIdentifiers[normalizeIdentifier(uuid)] = uuid
}
}
for normalizedAuthor, rawAuthor := range authorIdentifiers {
if normalizedAuthor == "" {
continue
}
if rawBot, found := botIdentifiers[normalizedAuthor]; found {
log.Printf("[DEBUG] Author matches bot identifier (%s vs %s)", rawAuthor, rawBot)
return true
}
}
if botInfo.Username != "" && strings.EqualFold(event.Comment.Author.Username, botInfo.Username) {
log.Printf("[DEBUG] Author username %s matches bot username", event.Comment.Author.Username)
return true
}
return false
}
// ProcessCommentReply processes comment reply flow using original working logic
func (p *UnifiedProcessorV2Impl) ProcessCommentReply(ctx context.Context, event UnifiedWebhookEventV2, timeline *UnifiedTimelineV2, orgID int64) (string, *LearningMetadataV2, error) {
if event.Comment == nil {
return "", nil, fmt.Errorf("no comment in event for reply processing")
}
log.Printf("[INFO] Processing comment reply for %s provider using original contextual logic", event.Provider)
// Build artifact for context (Phase 1 + Phase A + Phase B)
var artifact *mrmodel.UnifiedArtifact
if p.server.DB() != nil {
provider := strings.ToLower(event.Provider)
switch provider {
case "gitlab":
log.Printf("[DEBUG] Building GitLab artifact for contextual response")
var err error
artifact, err = p.buildGitLabArtifactFromEvent(ctx, event, orgID)
if err != nil {
return "", nil, fmt.Errorf("failed to build GitLab artifact: %w", err)
}
case "github":
log.Printf("[DEBUG] Building GitHub artifact for contextual response")
var err error
artifact, err = p.buildGitHubArtifactFromEvent(ctx, event, orgID)
if err != nil {
return "", nil, fmt.Errorf("failed to build GitHub artifact: %w", err)
}
case "bitbucket":
log.Printf("[DEBUG] Building Bitbucket artifact for contextual response")
var err error
artifact, err = p.buildBitbucketArtifactFromEvent(ctx, event, orgID)
if err != nil {
return "", nil, fmt.Errorf("failed to build Bitbucket artifact: %w", err)
}
}
}
// Use the original sophisticated contextual response logic
response, learning := p.buildContextualResponseWithLearningV2(ctx, event, timeline, orgID, artifact)
return response, learning, nil
}
// buildCommentReplyPromptWithLearning creates LLM prompt with learning instructions
func (p *UnifiedProcessorV2Impl) buildCommentReplyPromptWithLearning(event UnifiedWebhookEventV2, timeline *UnifiedTimelineV2, artifact *mrmodel.UnifiedArtifact) string {
staticPrompt := &strings.Builder{}
// Core context
staticPrompt.WriteString("You are LiveReviewBot, an AI code review assistant.\n\n")
staticPrompt.WriteString("CONTEXT:\n")
staticPrompt.WriteString(fmt.Sprintf("- Repository: %s\n", event.Repository.Name))
if event.MergeRequest != nil {
staticPrompt.WriteString(fmt.Sprintf("- MR/PR title: %s\n", event.MergeRequest.Title))
}
// Build timeline section separately
timelineSection := &strings.Builder{}
if timeline != nil && len(timeline.Items) > 0 {
timelineSection.WriteString("\nRECENT CONVERSATION ACROSS THREAD (for context only, do not respond to prior messages unless they are referenced in the current comment):\n")
for _, item := range timeline.Items {
if item.Comment != nil {
content := item.Comment.Body
if len(content) > 100 {
content = content[:100]
}
timelineSection.WriteString(fmt.Sprintf("- %s: %s\n", item.Comment.Author.Username, content))
}
}
}
// Build instructions section
instructionsSection := &strings.Builder{}
instructionsSection.WriteString("\nCURRENT COMMENT (reply only to this message unless explicitly asked otherwise):\n")
instructionsSection.WriteString(fmt.Sprintf("@%s wrote: %s\n", event.Comment.Author.Username, event.Comment.Body))
if event.Repository.Name != "" {
instructionsSection.WriteString(fmt.Sprintf("Repository path: %s\n", event.Repository.FullName))
}
// Add code context if this is an inline comment
if event.Comment.Position != nil {
instructionsSection.WriteString("\nCode context:\n")
instructionsSection.WriteString(fmt.Sprintf("- File: %s\n", event.Comment.Position.FilePath))
instructionsSection.WriteString(fmt.Sprintf("- Line: %d\n", event.Comment.Position.LineNumber))
if event.Comment.Position.LineType != "" {
instructionsSection.WriteString(fmt.Sprintf("- Line type: %s\n", event.Comment.Position.LineType))
}
// Extract actual code lines from artifact diffs if available
if artifact != nil {
codeLines := p.extractCodeLinesFromDiff(artifact, event.Comment.Position.FilePath, event.Comment.Position.LineNumber)
if len(codeLines) > 0 {
instructionsSection.WriteString("\nCode snippet:\n```\n")
for _, line := range codeLines {
instructionsSection.WriteString(line)
instructionsSection.WriteString("\n")
}
instructionsSection.WriteString("```\n")
}
}
}
instructionsSection.WriteString("\nTASK:\n")
instructionsSection.WriteString("Answer the CURRENT COMMENT directly. Keep the reply focused on the exact question or concern that was raised. Reference surrounding code or prior discussion only when it improves the specific answer.\n")
instructionsSection.WriteString("- Do not summarise unrelated feedback or earlier conversations unless the user explicitly asked for it.\n")
instructionsSection.WriteString("- If the user asks \"what is this about?\" or similar, explain the referenced code fragment plainly and briefly.\n")
instructionsSection.WriteString("- Stay concise, professional, and actionable.\n\n")
// LEARNING INSTRUCTIONS
instructionsSection.WriteString("LEARNING EXTRACTION:\n")
instructionsSection.WriteString("IMPORTANT: Look for team policies, coding standards, and preferences that should be remembered for future interactions.\n\n")
instructionsSection.WriteString("EXTRACT LEARNING when you see phrases like:\n")
instructionsSection.WriteString("- \"our team prefers...\", \"we generally...\", \"in our team...\"\n")
instructionsSection.WriteString("- \"we don't use...\", \"we always...\", \"our standard is...\"\n")
instructionsSection.WriteString("- \"team policy\", \"coding standard\", \"house rule\"\n")
instructionsSection.WriteString("- User correcting you about team practices\n")
instructionsSection.WriteString("- Specific technology choices: \"we use X instead of Y\"\n\n")
instructionsSection.WriteString("LEARNING EXAMPLES:\n")
instructionsSection.WriteString("✓ \"our team prefers assertion-based error management\" → Extract team policy about assertions\n")
instructionsSection.WriteString("✓ \"we don't use magic numbers, always use constants\" → Extract coding standard\n")
instructionsSection.WriteString("✓ \"in our codebase, we use TypeScript instead of JavaScript\" → Extract technology preference\n")
instructionsSection.WriteString("✗ \"this code has a bug\" → No learning (just reporting an issue)\n")
instructionsSection.WriteString("✗ \"can you explain this function?\" → No learning (just asking for help)\n\n")
instructionsSection.WriteString("If you identify a learning, add this JSON block at the end of your response:\n")
instructionsSection.WriteString("```learning\n")
instructionsSection.WriteString("{\n")
instructionsSection.WriteString(` "type": "team_policy|coding_standard|preference|rule",` + "\n")
instructionsSection.WriteString(` "title": "Brief descriptive title of what you learned",` + "\n")
instructionsSection.WriteString(` "content": "Full description of the team's practice, preference, or rule",` + "\n")
instructionsSection.WriteString(` "tags": ["relevant", "keywords", "for_searching"],` + "\n")
instructionsSection.WriteString(` "scope": "org|repo",` + "\n")
instructionsSection.WriteString(` "confidence": <integer 1-5, where 5=very confident this is a team standard, 1=uncertain>` + "\n")
instructionsSection.WriteString("}\n```\n\n")
instructionsSection.WriteString("Only include learning block if there's genuinely something worth learning. Most responses won't have learnings. Never repeat a previously acknowledged learning unless this comment introduces new guidance.\n\n")
instructionsSection.WriteString("RESPONSE:\n")
// Calculate tokens for static parts
staticText := staticPrompt.String()
timelineText := timelineSection.String()
instructionsText := instructionsSection.String()
staticTokens := estimateTokens(staticText)
timelineTokens := estimateTokens(timelineText)
instructionsTokens := estimateTokens(instructionsText)
// Build final prompt with MR context that uses remaining budget
prompt := &strings.Builder{}
prompt.WriteString(staticText)
// Add MR context from artifact if available
if artifact != nil {
log.Printf("[DEBUG] Injecting MR context from artifact into prompt")
// Pass the calculated static costs to formatArtifactForPrompt
mrContext := p.formatArtifactForPromptWithBudget(artifact, staticTokens+timelineTokens+instructionsTokens)
if mrContext != "" {
prompt.WriteString("\n")
prompt.WriteString(mrContext)
prompt.WriteString("\n")
}
}
prompt.WriteString(timelineText)
prompt.WriteString(instructionsText)
if event.Comment != nil {
builder := coreprocessor.UnifiedContextBuilderV2{}
if codeContext, err := builder.ExtractCodeContext(*event.Comment, event.Provider); err == nil && codeContext != "" {
prompt.WriteString("\nHere is the full MR context:\n")
prompt.WriteString("\nFull Code and Comments CONTEXT for the MR:\n")
prompt.WriteString(codeContext)
prompt.WriteString("\n")
}
}
return prompt.String()
}
// buildContextualResponseWithLearningV2 creates response using LLM with learning instructions
func (p *UnifiedProcessorV2Impl) buildContextualResponseWithLearningV2(ctx context.Context, event UnifiedWebhookEventV2, timeline *UnifiedTimelineV2, orgID int64, artifact *mrmodel.UnifiedArtifact) (string, *LearningMetadataV2) {
prompt := p.buildCommentReplyPromptWithLearning(event, timeline, artifact)
var relevantLearnings []*learnings.Learning
if orgID != 0 {
repoID := event.Repository.FullName
if repoID == "" {
repoID = event.Repository.Name
}
title := ""
description := ""
if event.MergeRequest != nil {
title = event.MergeRequest.Title
description = event.MergeRequest.Description
}
fetched, err := p.fetchRelevantLearnings(ctx, orgID, repoID, nil, title, description)
if err != nil {
log.Printf("[WARN] Failed to fetch relevant learnings: %v", err)
} else {
relevantLearnings = fetched
}
}
prompt = p.appendLearningsToPrompt(prompt, relevantLearnings)
// write the prompt into a file for debugging
err := os.WriteFile("debug_prompt.txt", []byte(prompt), 0644)
if err != nil {
log.Printf("[WARN] Failed to write debug prompt to file: %v", err)
}
if ctx == nil {
ctx = context.Background()
}
llmResponse, learning, err := p.generateLLMResponseWithLearning(ctx, prompt, event, orgID)
if err != nil {
log.Printf("[ERROR] LLM generation failed: %v - cannot provide response", err)
return fmt.Sprintf("I'm sorry, I'm unable to generate a response right now. Please try again later. (Error: %v)", err), nil
}
return llmResponse, learning
}
func (p *UnifiedProcessorV2Impl) fetchRelevantLearnings(ctx context.Context, orgID int64, repoID string, changedFiles []string, title, description string) ([]*learnings.Learning, error) {
if p.server == nil || p.server.learningsService == nil || orgID == 0 {
return nil, nil
}
if ctx == nil {
ctx = context.Background()
}
return p.server.learningsService.ListActiveByOrg(ctx, orgID)
}
func (p *UnifiedProcessorV2Impl) appendLearningsToPrompt(prompt string, items []*learnings.Learning) string {
if len(items) == 0 {
return prompt
}
section := p.formatLearningsSection(items)
if section == "" {
return prompt
}
if !strings.HasSuffix(prompt, "\n") {
prompt += "\n"
}
return prompt + section
}
func (p *UnifiedProcessorV2Impl) formatLearningsSection(items []*learnings.Learning) string {
if len(items) == 0 {
return ""
}
var b strings.Builder
b.WriteString("=== Org learnings ===\n")
b.WriteString("Incorporate the following established org guidance when drafting your reply:\n")
for _, item := range items {
b.WriteString(fmt.Sprintf("- [%s] %s\n", item.ShortID, item.Title))
if body := truncateLearningBodyV2(item.Body, 260); body != "" {
b.WriteString(" ")
b.WriteString(body)
b.WriteString("\n")
}
if len(item.Tags) > 0 {
b.WriteString(" Tags: ")
b.WriteString(strings.Join(item.Tags, ", "))
b.WriteString("\n")
}
}
b.WriteString("\n")
return b.String()
}
func truncateLearningBodyV2(body string, limit int) string {
body = strings.TrimSpace(body)
if body == "" {
return ""
}
if limit > 0 && len(body) > limit {
body = body[:limit]
if idx := strings.LastIndex(body, " "); idx > limit-40 {
body = body[:idx]
}
body = strings.TrimSpace(body) + "..."
}
return body
}
// extractCodeLinesFromDiff extracts code lines around a specific line number from the diff
func (p *UnifiedProcessorV2Impl) extractCodeLinesFromDiff(artifact *mrmodel.UnifiedArtifact, filePath string, lineNumber int) []string {
if artifact == nil || len(artifact.Diffs) == 0 {
return nil
}
// Find the diff for the specified file
var targetDiff *mrmodel.LocalCodeDiff
for i := range artifact.Diffs {
if artifact.Diffs[i].NewPath == filePath || artifact.Diffs[i].OldPath == filePath {
targetDiff = artifact.Diffs[i]
break
}
}
if targetDiff == nil {
return nil
}
// Extract lines from hunks that contain or are near the target line
var result []string
const contextLines = 3 // Show 3 lines before and after
for _, hunk := range targetDiff.Hunks {
for i, line := range hunk.Lines {
// Check if this line matches our target (use NewLineNo for new/context lines)
lineNo := line.NewLineNo
if line.LineType == "deleted" {
lineNo = line.OldLineNo
}
// If this line is within context range of our target
if lineNo >= lineNumber-contextLines && lineNo <= lineNumber+contextLines {
// Include a few lines before and after
startIdx := max(0, i-contextLines)
endIdx := min(len(hunk.Lines), i+contextLines+1)
for j := startIdx; j < endIdx; j++ {
diffLine := hunk.Lines[j]
linePrefix := " "
if diffLine.LineType == "added" {
linePrefix = "+"
} else if diffLine.LineType == "deleted" {
linePrefix = "-"
}
displayLineNo := diffLine.NewLineNo
if diffLine.LineType == "deleted" {
displayLineNo = diffLine.OldLineNo
}
result = append(result, fmt.Sprintf("%s %d: %s", linePrefix, displayLineNo, diffLine.Content))
}
return result // Found our context, return it
}
}
}
return nil
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
// ProcessFullReview processes full review flow when bot is assigned as reviewer
// Extracted from triggerReviewFor* functions (to be implemented in future phases)
func (p *UnifiedProcessorV2Impl) ProcessFullReview(ctx context.Context, event UnifiedWebhookEventV2, timeline *UnifiedTimelineV2) ([]UnifiedReviewCommentV2, *LearningMetadataV2, error) {
// TODO: Implement full review processing in Phase 7.2
// This will extract review logic from the monolithic handler
return nil, nil, fmt.Errorf("full review processing not yet implemented")
}
// Helper methods (extracted from webhook_handler.go)
func (p *UnifiedProcessorV2Impl) isReplyToBotComment(event UnifiedWebhookEventV2, botInfo *UnifiedBotUserInfoV2) (bool, error) {
if event.Comment == nil || botInfo == nil {
return false, nil
}
if event.Comment.InReplyToID == nil || *event.Comment.InReplyToID == "" {
return false, nil
}
replyToID := *event.Comment.InReplyToID
switch event.Provider {
case "github":
return p.checkGitHubParentCommentAuthor(event, replyToID, botInfo)
case "bitbucket":
return p.checkBitbucketParentCommentAuthor(event, replyToID, botInfo)
case "gitlab":
return p.checkGitLabDiscussionForBotReply(event, botInfo)
default:
return false, fmt.Errorf("reply detection not implemented for provider %s", event.Provider)
}
}
func (p *UnifiedProcessorV2Impl) checkGitHubParentCommentAuthor(event UnifiedWebhookEventV2, parentID string, botInfo *UnifiedBotUserInfoV2) (bool, error) {
if p.server == nil || p.server.githubProviderV2 == nil {
return false, fmt.Errorf("github provider unavailable for parent lookup")
}
repoFullName := event.Repository.FullName
if repoFullName == "" {
return false, fmt.Errorf("missing repository full name for GitHub reply detection")
}
token, err := p.server.githubProviderV2.FindIntegrationTokenForRepo(repoFullName)
if err != nil || token == nil {
return false, fmt.Errorf("failed to find GitHub token: %w", err)
}
var apiURL string
if event.Comment.Position != nil && event.Comment.Position.FilePath != "" {
apiURL = fmt.Sprintf("https://api.github.com/repos/%s/pulls/comments/%s", repoFullName, parentID)
} else {
apiURL = fmt.Sprintf("https://api.github.com/repos/%s/issues/comments/%s", repoFullName, parentID)
}
req, err := http.NewRequest("GET", apiURL, nil)
if err != nil {
return false, err
}
req.Header.Set("Authorization", "Bearer "+token.PatToken)
req.Header.Set("Accept", "application/vnd.github.v3+json")
req.Header.Set("User-Agent", "LiveReview-Bot")
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
return false, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return false, fmt.Errorf("GitHub API error getting parent comment (status %d): %s", resp.StatusCode, string(body))
}
var parent struct {
User struct {
Login string `json:"login"`
ID int64 `json:"id"`
} `json:"user"`
}
if err := json.NewDecoder(resp.Body).Decode(&parent); err != nil {
return false, err
}
if parent.User.Login == "" {
return false, nil
}
if botInfo.Username != "" && strings.EqualFold(parent.User.Login, botInfo.Username) {
return true, nil
}
if botInfo.UserID != "" && fmt.Sprintf("%d", parent.User.ID) == botInfo.UserID {
return true, nil
}
return false, nil
}
func (p *UnifiedProcessorV2Impl) checkBitbucketParentCommentAuthor(event UnifiedWebhookEventV2, parentID string, botInfo *UnifiedBotUserInfoV2) (bool, error) {
if p.server == nil || p.server.bitbucketProviderV2 == nil {
return false, fmt.Errorf("bitbucket provider unavailable for parent lookup")
}
if event.Comment.Metadata == nil {
return false, fmt.Errorf("missing Bitbucket metadata for reply detection")
}
workspace, _ := event.Comment.Metadata["workspace"].(string)
repository, _ := event.Comment.Metadata["repository"].(string)
prNumber := ""
switch value := event.Comment.Metadata["pr_number"].(type) {
case string:
prNumber = value
case int:
prNumber = fmt.Sprintf("%d", value)
case float64:
prNumber = fmt.Sprintf("%d", int(value))
}
if prNumber == "" && event.MergeRequest != nil {
prNumber = event.MergeRequest.ID
}
if workspace == "" || repository == "" || prNumber == "" {
return false, fmt.Errorf("insufficient Bitbucket metadata for reply detection")
}
token, err := p.server.bitbucketProviderV2.FindIntegrationTokenForRepo(event.Repository.FullName)
if err != nil || token == nil {
return false, fmt.Errorf("failed to find Bitbucket token: %w", err)
}
email := ""
if token.Metadata != nil {
if raw, ok := token.Metadata["email"]; ok {
switch v := raw.(type) {
case string:
email = v
case []byte:
email = string(v)
}
}
}
if email == "" {
return false, fmt.Errorf("bitbucket email missing in token metadata")
}
apiURL := fmt.Sprintf("https://api.bitbucket.org/2.0/repositories/%s/%s/pullrequests/%s/comments/%s", workspace, repository, prNumber, parentID)
req, err := http.NewRequest("GET", apiURL, nil)
if err != nil {
return false, err
}
req.SetBasicAuth(email, token.PatToken)
req.Header.Set("Accept", "application/json")
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return false, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return false, fmt.Errorf("Bitbucket API error getting parent comment (status %d): %s", resp.StatusCode, string(body))
}
var parent bitbucketParentComment
if err := json.NewDecoder(resp.Body).Decode(&parent); err != nil {
return false, err
}
if botInfo.Username != "" && strings.EqualFold(parent.User.Username, botInfo.Username) {
return true, nil
}
if botInfo.Metadata != nil {
if accountID, ok := botInfo.Metadata["account_id"].(string); ok && accountID != "" {
if normalizeIdentifier(parent.User.AccountID) == normalizeIdentifier(accountID) {
return true, nil
}
}
if uuid, ok := botInfo.Metadata["uuid"].(string); ok && uuid != "" {
if normalizeIdentifier(parent.User.UUID) == normalizeIdentifier(uuid) {
return true, nil
}
}
}
if botInfo.UserID != "" {
if normalizeIdentifier(parent.User.AccountID) == normalizeIdentifier(botInfo.UserID) {
return true, nil
}
}
return false, nil
}
func (p *UnifiedProcessorV2Impl) checkGitLabDiscussionForBotReply(event UnifiedWebhookEventV2, botInfo *UnifiedBotUserInfoV2) (bool, error) {
if event.Comment == nil || event.Comment.DiscussionID == nil || *event.Comment.DiscussionID == "" {
return false, nil
}
log.Printf("[DEBUG] GitLab discussion reply checking not yet implemented for discussion %s", *event.Comment.DiscussionID)
return false, nil
}
// checkDirectBotMentionV2 checks for direct @mentions of the bot using provider-aware helpers.
func (p *UnifiedProcessorV2Impl) checkDirectBotMentionV2(event UnifiedWebhookEventV2, botInfo *UnifiedBotUserInfoV2) bool {
if botInfo == nil || event.Comment == nil {
return false
}
body := event.Comment.Body
switch strings.ToLower(event.Provider) {
case "github":
return githubmentions.DetectDirectMention(body, botInfo)
case "gitlab":
return gitlabmentions.DetectDirectMention(body, botInfo)
case "bitbucket":
return bitbucketmentions.DetectDirectMention(body, botInfo)
default:
return fallbackUsernameMention(body, botInfo)
}
}
func fallbackUsernameMention(commentBody string, botInfo *UnifiedBotUserInfoV2) bool {
if botInfo == nil {
return false
}
username := strings.TrimSpace(botInfo.Username)
if username == "" {
return false
}
mentionPattern := "@" + strings.ToLower(username)
return strings.Contains(strings.ToLower(commentBody), mentionPattern)
}
// classifyContentTypeV2 classifies the type of content in a comment
// Extracted from classifyContentType
func (p *UnifiedProcessorV2Impl) classifyContentTypeV2(commentBody string) string {
commentLower := strings.ToLower(commentBody)
if strings.Contains(commentLower, "documentation") || strings.Contains(commentLower, "document") {
return "documentation"
}
if strings.Contains(commentLower, "error") || strings.Contains(commentLower, "bug") {
return "error_report"
}
if strings.Contains(commentLower, "performance") || strings.Contains(commentLower, "slow") {
return "performance"
}
if strings.Contains(commentLower, "security") || strings.Contains(commentLower, "vulnerable") {
return "security"
}
if strings.Contains(commentLower, "?") || strings.Contains(commentLower, "question") {
return "question"
}
if strings.Contains(commentLower, "help") || strings.Contains(commentLower, "explain") {
return "help_request"
}
return "general"
}
// determineResponseTypeV2 determines the appropriate response type
// Extracted from determineResponseType
func (p *UnifiedProcessorV2Impl) determineResponseTypeV2(commentBody string) string {
commentLower := strings.ToLower(commentBody)
if strings.Contains(commentLower, "brief") || strings.Contains(commentLower, "quick") {
return "brief_acknowledgment"
}
if strings.Contains(commentLower, "explain") || strings.Contains(commentLower, "detail") {
return "detailed_response"
}
if strings.Contains(commentLower, "how") || strings.Contains(commentLower, "implement") {
return "implementation_guidance"
}
return "contextual_analysis"
}
// buildUnifiedPromptV2 builds a provider-agnostic prompt for AI processing
// Unified version of buildGeminiPromptEnhanced
func (p *UnifiedProcessorV2Impl) buildUnifiedPromptV2(event UnifiedWebhookEventV2, timeline *UnifiedTimelineV2) string {
var prompt strings.Builder
// Context header
prompt.WriteString("You are an AI code review assistant. ")
prompt.WriteString(fmt.Sprintf("Analyzing a %s comment from %s.\n\n", event.Provider, event.Comment.Author.Username))
// Repository and MR context
if event.MergeRequest != nil {
prompt.WriteString(fmt.Sprintf("**Repository:** %s\n", event.Repository.FullName))
prompt.WriteString(fmt.Sprintf("**Merge Request:** %s\n", event.MergeRequest.Title))
prompt.WriteString(fmt.Sprintf("**Description:** %s\n\n", event.MergeRequest.Description))
}
// Comment content
prompt.WriteString(fmt.Sprintf("**Comment by @%s:**\n", event.Comment.Author.Username))
prompt.WriteString(fmt.Sprintf("%s\n\n", event.Comment.Body))
// Timeline context if available
if timeline != nil && len(timeline.Items) > 0 {
prompt.WriteString("**Recent Activity:**\n")
// Show last few timeline items for context
start := 0
if len(timeline.Items) > 5 {
start = len(timeline.Items) - 5
}
for i := start; i < len(timeline.Items); i++ {
item := timeline.Items[i]
switch item.Type {
case "commit":
if item.Commit != nil {
prompt.WriteString(fmt.Sprintf("- Commit: %s\n", item.Commit.Message))
}
case "comment":
if item.Comment != nil {
prompt.WriteString(fmt.Sprintf("- Comment by @%s: %s\n",
item.Comment.Author.Username,
p.truncateString(item.Comment.Body, 100)))
}
}
}
prompt.WriteString("\n")
}
// Code position context if available
if event.Comment.Position != nil {
prompt.WriteString("**Code Context:**\n")
prompt.WriteString(fmt.Sprintf("File: %s\n", event.Comment.Position.FilePath))
if event.Comment.Position.LineNumber > 0 {
prompt.WriteString(fmt.Sprintf("Line: %d\n", event.Comment.Position.LineNumber))
}
prompt.WriteString("\n")
}
// Response guidance
prompt.WriteString("Please provide a helpful, technical response that:\n")
prompt.WriteString("1. Addresses the specific question or concern\n")
prompt.WriteString("2. Provides actionable guidance when appropriate\n")
prompt.WriteString("3. Maintains a professional, collaborative tone\n")
prompt.WriteString("4. Focuses on code quality and best practices\n\n")
return prompt.String()
}
// generateLLMResponseWithLearning generates LLM response and extracts learning
func (p *UnifiedProcessorV2Impl) generateLLMResponseWithLearning(ctx context.Context, prompt string, event UnifiedWebhookEventV2, orgID int64) (string, *LearningMetadataV2, error) {
// Try to get LLM response
llmResponse, err := p.generateLLMResponseV2(ctx, prompt, orgID)
if err != nil {
return "", nil, err
}
// Extract learning from LLM response
learning := p.extractLearningFromLLMResponse(llmResponse, event, orgID)
// Clean response by removing learning block
cleanResponse := p.cleanResponseFromLearningBlock(llmResponse)
return cleanResponse, learning, nil
}
// generateLLMResponseV2 uses the actual AI connectors infrastructure
func (p *UnifiedProcessorV2Impl) generateLLMResponseV2(ctx context.Context, prompt string, orgID int64) (string, error) {
if p.server == nil || p.server.db == nil {
return "", fmt.Errorf("server or database not available")
}
// Get available AI connectors
storage := aiconnectors.NewStorage(p.server.db)
connectors, err := storage.GetAllConnectors(ctx, orgID)
if err != nil {
return "", fmt.Errorf("failed to get AI connectors: %w", err)
}
if len(connectors) == 0 {
return "", fmt.Errorf("no AI connectors configured for organization %d", orgID)