-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnotify.go
More file actions
965 lines (859 loc) · 30.3 KB
/
notify.go
File metadata and controls
965 lines (859 loc) · 30.3 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
// Package notify handles user notifications and reminders.
package notify
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"sort"
"strings"
"time"
"github.com/codeGROOVE-dev/slacker/pkg/slack"
"github.com/codeGROOVE-dev/slacker/pkg/state"
"github.com/codeGROOVE-dev/turnclient/pkg/turn"
"github.com/google/uuid"
)
// Constants for notification defaults.
const (
defaultReminderDMDelayMinutes = 65 // Default delay in minutes before sending DM if user tagged in channel
)
// UserMapper interface for formatting user mentions in messages.
type UserMapper interface {
FormatUserMentions(ctx context.Context, githubUsers []string, owner, domain string) string
}
// MessageParams contains all parameters needed to format a channel message.
//
//nolint:govet // fieldalignment optimization would reduce parameter clarity
type MessageParams struct {
CheckResult *turn.CheckResponse
Owner string
Repo string
PRNumber int
Title string
Author string
HTMLURL string
Domain string
UserMapper UserMapper
}
// FormatChannelMessageBase formats the base Slack channel message for a PR (without next actions).
// This is the single source of truth for channel message formatting.
// It handles emoji determination and base message assembly.
// Use FormatNextActionsSuffix to add next actions when needed.
func FormatChannelMessageBase(ctx context.Context, params MessageParams) string {
pr := params.CheckResult.PullRequest
a := params.CheckResult.Analysis
prID := fmt.Sprintf("%s/%s#%d", params.Owner, params.Repo, params.PRNumber)
// Log all decision factors for debugging
kinds := make([]string, 0, len(a.NextAction))
for user, action := range a.NextAction {
kinds = append(kinds, fmt.Sprintf("%s:%s", user, action.Kind))
}
slog.Info("formatting channel message",
"pr", prID,
"pr_state", pr.State,
"merged", pr.Merged,
"draft", pr.Draft,
"workflow_state", a.WorkflowState,
"next_action_count", len(a.NextAction),
"next_actions", kinds,
"checks_failing", a.Checks.Failing,
"checks_pending", a.Checks.Pending,
"checks_waiting", a.Checks.Waiting,
"approved", a.Approved,
"unresolved_comments", a.UnresolvedComments)
// Determine emoji and state parameter
var emoji, state string
// Handle merged/closed states first (most definitive)
//nolint:gocritic // if-else chain is clearer than switch for state-based logic
if pr.Merged {
emoji, state = ":rocket:", "?st=merged"
slog.Info("using :rocket: emoji - PR is merged", "pr", prID, "merged_at", pr.MergedAt)
} else if pr.State == "closed" {
emoji, state = ":x:", "?st=closed"
slog.Info("using :x: emoji - PR is closed but not merged", "pr", prID)
} else if a.WorkflowState != "" {
// Use WorkflowState as primary signal (most reliable source of truth)
emoji, state = emojiFromWorkflowState(a.WorkflowState, a.NextAction)
slog.Info("using emoji from workflow_state", "pr", prID, "workflow_state", a.WorkflowState, "emoji", emoji, "state_param", state)
} else if len(a.NextAction) > 0 {
// Fallback to NextAction if no WorkflowState (shouldn't normally happen)
action := PrimaryAction(a.NextAction)
emoji = PrefixForAction(action)
state = stateParam(params.CheckResult)
slog.Info("using emoji from primary next_action (no workflow_state)", "pr", prID, "primary_action", action, "emoji", emoji, "state_param", state)
} else {
// Final fallback based on PR properties
emoji, state = fallbackEmoji(params.CheckResult)
//nolint:revive // line length acceptable for structured logging
slog.Info("using fallback emoji - no workflow_state or next_actions", "pr", prID, "emoji", emoji, "state_param", state, "fallback_reason", "empty_workflow_state_and_next_actions")
}
return fmt.Sprintf("%s %s <%s|%s#%d> · %s",
emoji,
params.Title,
params.HTMLURL+state,
params.Repo,
params.PRNumber,
params.Author)
}
// FormatNextActionsSuffix formats the next actions suffix for a channel message.
// Returns empty string if no next actions are present.
// Call this after FormatChannelMessageBase to build a complete message with user mentions.
func FormatNextActionsSuffix(ctx context.Context, params MessageParams) string {
if params.CheckResult == nil || len(params.CheckResult.Analysis.NextAction) == 0 {
return ""
}
actions := formatNextActionsInternal(ctx, params.CheckResult.Analysis.NextAction, params.Owner, params.Domain, params.UserMapper)
if actions != "" {
return fmt.Sprintf(" → %s", actions)
}
return ""
}
// emojiFromWorkflowState determines emoji based on WorkflowState as the primary signal.
// Uses NextAction for additional granularity in specific states (e.g., test failures).
func emojiFromWorkflowState(workflowState string, nextActions map[string]turn.Action) (emoji, state string) {
switch workflowState {
case string(turn.StateNewlyPublished):
return ":new:", "?st=newly_published"
case string(turn.StateInDraft):
return ":construction:", "?st=draft"
case string(turn.StatePublishedWaitingForTests):
// Use NextAction to distinguish between broken tests vs pending tests
if len(nextActions) > 0 {
action := PrimaryAction(nextActions)
if action == string(turn.ActionFixTests) {
return ":cockroach:", "?st=tests_broken"
}
if action == string(turn.ActionTestsPending) {
return ":test_tube:", "?st=tests_running"
}
}
// Default to tests running
return ":test_tube:", "?st=tests_running"
case string(turn.StateTestedWaitingForAssignment):
// Check if tests are actually broken despite "TESTED" state
// This can happen if new commits pushed after tests passed
if len(nextActions) > 0 {
action := PrimaryAction(nextActions)
if action == string(turn.ActionFixTests) {
return ":cockroach:", "?st=tests_broken"
}
}
// Tests passed, waiting for reviewers to be assigned
return ":shrug:", "?st=awaiting_assignment"
case string(turn.StateAssignedWaitingForReview):
// Waiting for assigned reviewers to review
return ":hourglass:", "?st=awaiting_review"
case string(turn.StateReviewedNeedsRefinement):
// Author needs to address feedback/comments
return ":carpentry_saw:", "?st=changes_requested"
case string(turn.StateRefinedWaitingForApproval):
// Waiting for final approval after refinements
return ":hourglass:", "?st=awaiting_approval"
case string(turn.StateApprovedWaitingForMerge):
// Approved and ready to merge
return ":white_check_mark:", "?st=approved"
default:
// Unknown workflow state - fall back to NextAction
slog.Warn("unknown workflow state, falling back to NextAction",
"workflow_state", workflowState)
if len(nextActions) > 0 {
action := PrimaryAction(nextActions)
return PrefixForAction(action), "?st=unknown"
}
return ":postal_horn:", "?st=unknown"
}
}
// stateParam returns the URL state parameter based on PR analysis.
func stateParam(r *turn.CheckResponse) string {
pr := r.PullRequest
a := r.Analysis
if pr.Draft {
return "?st=tests_running"
}
if a.Checks.Failing > 0 {
return "?st=tests_broken"
}
if a.Checks.Pending > 0 || a.Checks.Waiting > 0 {
return "?st=tests_running"
}
if a.Approved {
if a.UnresolvedComments > 0 {
return "?st=changes_requested"
}
return "?st=approved"
}
return "?st=awaiting_review"
}
// fallbackEmoji determines emoji when no workflow_state or next_actions are available.
func fallbackEmoji(r *turn.CheckResponse) (emoji, state string) {
pr := r.PullRequest
a := r.Analysis
if pr.Draft {
return ":test_tube:", "?st=tests_running"
}
if a.Checks.Failing > 0 {
return ":cockroach:", "?st=tests_broken"
}
if a.Checks.Pending > 0 || a.Checks.Waiting > 0 {
return ":test_tube:", "?st=tests_running"
}
if a.Approved {
if a.UnresolvedComments > 0 {
return ":carpentry_saw:", "?st=changes_requested"
}
return ":white_check_mark:", "?st=approved"
}
return ":hourglass:", "?st=awaiting_review"
}
// formatNextActionsInternal formats next actions with user mentions (internal helper).
func formatNextActionsInternal(ctx context.Context, nextActions map[string]turn.Action, owner, domain string, userMapper UserMapper) string {
if len(nextActions) == 0 {
return ""
}
// Group users by action kind, filtering out _system users
actionGroups := make(map[string][]string)
for user, action := range nextActions {
actionKind := string(action.Kind)
// Skip _system users but still track the action exists
if user != "_system" {
actionGroups[actionKind] = append(actionGroups[actionKind], user)
} else if _, exists := actionGroups[actionKind]; !exists {
// Action only has _system - create empty slice to track it exists
actionGroups[actionKind] = []string{}
}
}
// Format each action group
var parts []string
for actionKind, users := range actionGroups {
// Convert snake_case to space-separated words
actionName := strings.ReplaceAll(actionKind, "_", " ")
// Sort users for deterministic output
sort.Strings(users)
// Format user mentions (will be empty if only _system was assigned)
userMentions := userMapper.FormatUserMentions(ctx, users, owner, domain)
// If action has users, format as "action: users"
// If no users (was only _system), just show the action
if userMentions != "" {
parts = append(parts, fmt.Sprintf("%s: %s", actionName, userMentions))
} else {
parts = append(parts, actionName)
}
}
// Use semicolons to separate different actions (commas are used between users)
return strings.Join(parts, "; ")
}
// Store interface for persistent DM queue management.
type Store interface {
QueuePendingDM(dm state.PendingDM) error
GetPendingDMs(before time.Time) ([]state.PendingDM, error)
RemovePendingDM(id string) error
}
// Manager handles user notifications across multiple workspaces.
type Manager struct {
slackManager SlackManager
Tracker *NotificationTracker
configManager ConfigManager
store Store
}
// New creates a new notification manager.
func New(slackManager SlackManager, configManager ConfigManager, store Store) *Manager {
return &Manager{
slackManager: slackManager,
configManager: configManager,
store: store,
Tracker: &NotificationTracker{
lastDM: make(map[string]time.Time),
lastDaily: make(map[string]time.Time),
lastChannelNotification: make(map[string]time.Time),
lastUserPRChannelTag: make(map[string]TagInfo),
},
}
}
// Run starts the notification scheduler.
func (m *Manager) Run(ctx context.Context) error {
ticker := time.NewTicker(1 * time.Minute)
defer ticker.Stop()
// Cleanup old entries every hour to prevent unbounded memory growth
cleanupTicker := time.NewTicker(1 * time.Hour)
defer cleanupTicker.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
// Check for pending DMs that should be sent now
if err := m.processPendingDMs(ctx); err != nil {
slog.Error("failed to process pending DMs", "error", err)
}
case <-cleanupTicker.C:
// Clean up entries older than 7 days
// This keeps recent data for rate limiting while preventing unbounded growth
m.Tracker.Cleanup(7 * 24 * time.Hour)
slog.Debug("cleaned up old notification tracker entries")
}
}
}
// processPendingDMs checks for pending DMs that should be sent and sends them.
func (m *Manager) processPendingDMs(ctx context.Context) error {
now := time.Now()
pendingDMs, err := m.store.GetPendingDMs(now)
if err != nil {
return fmt.Errorf("failed to get pending DMs: %w", err)
}
if len(pendingDMs) == 0 {
return nil
}
slog.Info("processing pending DMs", "count", len(pendingDMs))
for _, dm := range pendingDMs {
// Deserialize NextActions
var nextAction map[string]turn.Action
if err := json.Unmarshal([]byte(dm.NextActions), &nextAction); err != nil {
slog.Error("failed to deserialize next actions for pending DM",
"dm_id", dm.ID,
"user", dm.UserID,
"pr", fmt.Sprintf("%s/%s#%d", dm.PROwner, dm.PRRepo, dm.PRNumber),
"error", err)
nextAction = make(map[string]turn.Action)
}
// Reconstruct PRInfo from pending DM
prInfo := PRInfo{
Owner: dm.PROwner,
Repo: dm.PRRepo,
Title: dm.PRTitle,
Author: dm.PRAuthor,
State: dm.PRState,
HTMLURL: dm.PRURL,
Number: dm.PRNumber,
WorkflowState: dm.WorkflowState,
NextAction: nextAction,
}
// Send the DM (bypassing the deferral logic by not passing tagInfo)
// We call the actual DM sending logic directly
if err := m.sendDMNow(ctx, dm.WorkspaceID, dm.UserID, dm.ChannelID, dm.ChannelName, prInfo); err != nil {
slog.Error("failed to send pending DM",
"dm_id", dm.ID,
"user", dm.UserID,
"pr", fmt.Sprintf("%s/%s#%d", dm.PROwner, dm.PRRepo, dm.PRNumber),
"error", err)
// Continue processing other DMs even if one fails
continue
}
// Remove from queue after successful send
if err := m.store.RemovePendingDM(dm.ID); err != nil {
slog.Error("failed to remove pending DM from queue",
"dm_id", dm.ID,
"user", dm.UserID,
"pr", fmt.Sprintf("%s/%s#%d", dm.PROwner, dm.PRRepo, dm.PRNumber),
"error", err)
// Don't return error - the DM was sent successfully
} else {
slog.Info("sent and removed pending DM",
"dm_id", dm.ID,
"user", dm.UserID,
"pr", fmt.Sprintf("%s/%s#%d", dm.PROwner, dm.PRRepo, dm.PRNumber),
"queued_at", dm.QueuedAt,
"send_after", dm.SendAfter,
"delay", now.Sub(dm.QueuedAt))
}
}
return nil
}
// sendDMNow sends a DM immediately, bypassing deferral logic.
// This is used by the scheduler to send queued DMs.
func (m *Manager) sendDMNow(ctx context.Context, workspaceID, userID, channelID, channelName string, pr PRInfo) error {
// Get the Slack client for this workspace
slackClient, err := m.slackManager.Client(ctx, workspaceID)
if err != nil {
return fmt.Errorf("failed to get Slack client: %w", err)
}
// Check anti-spam protection
lastDM := m.Tracker.LastDMNotification(workspaceID, userID)
timeSinceLastDM := time.Since(lastDM)
antiSpamDelay := 1 * time.Minute
if timeSinceLastDM < antiSpamDelay {
slog.Info("skipping DM - anti-spam protection active",
"user", userID,
"pr", fmt.Sprintf("%s/%s#%d", pr.Owner, pr.Repo, pr.Number),
"time_since_last_dm", timeSinceLastDM,
"time_until_next_allowed", antiSpamDelay-timeSinceLastDM)
return nil
}
// Check if user is active
isActive := slackClient.IsUserActive(ctx, userID)
if !isActive {
slog.Info("deferring DM - user not active on Slack",
"user", userID,
"pr", fmt.Sprintf("%s/%s#%d", pr.Owner, pr.Repo, pr.Number))
// Re-queue for later (add 10 minutes to send time)
// TODO: Implement re-queuing logic if needed
return nil
}
// Format notification message
var prefix string
if pr.WorkflowState != "" {
prefix = PrefixForAnalysis(pr.WorkflowState, pr.NextAction)
} else {
prefix = PrefixForState(pr.State)
}
// Format: :emoji: Title <url|repo#123> · author → action
var action string
switch pr.State {
case "newly_published":
action = "newly published"
case "tests_broken":
action = "fix tests"
case "awaiting_review":
action = "review"
case "changes_requested":
action = "address feedback"
case "approved":
action = "merge"
default:
// Derive action from NextAction if available
if len(pr.NextAction) > 0 {
action = strings.ReplaceAll(PrimaryAction(pr.NextAction), "_", " ")
}
}
message := fmt.Sprintf("%s %s <%s|%s/%s#%d>",
prefix,
pr.Title,
pr.HTMLURL,
pr.Owner,
pr.Repo,
pr.Number)
if action != "" {
message += fmt.Sprintf(" · %s → %s", pr.Author, action)
}
// Send DM
_, _, err = slackClient.SendDirectMessage(ctx, userID, message)
if err != nil {
return fmt.Errorf("failed to send DM: %w", err)
}
// Track that we sent this DM
m.Tracker.UpdateDMNotification(workspaceID, userID)
slog.Info("sent deferred DM",
"user", userID,
"pr", fmt.Sprintf("%s/%s#%d", pr.Owner, pr.Repo, pr.Number),
"channel_id", channelID,
"channel_name", channelName)
return nil
}
// PRInfo contains the minimal information needed to notify about a PR.
//
//nolint:govet // fieldalignment optimization would reduce clarity
type PRInfo struct {
Owner string
Repo string
Title string
Author string
State string // Deprecated: use WorkflowState and NextAction for emoji determination
HTMLURL string
Number int
WorkflowState string // Workflow state from turnclient Analysis
NextAction map[string]turn.Action // Next actions from turnclient Analysis
}
// PrefixForState returns the emoji prefix for a given PR state.
// Exported for use by bot package to ensure consistent PR state display.
//
// Deprecated: Use PrefixForAnalysis instead to derive emoji from NextAction.
func PrefixForState(prState string) string {
switch prState {
case "newly_published":
return ":new:"
case "tests_running":
return ":test_tube:"
case "tests_broken":
return ":cockroach:"
case "awaiting_review":
return ":hourglass:"
case "changes_requested":
return ":carpentry_saw:"
case "approved":
return ":white_check_mark:"
case "merged":
return ":rocket:"
case "closed":
return ":x:"
default:
return ":postal_horn:"
}
}
// PrefixForAction returns the emoji prefix for a given action kind.
func PrefixForAction(action string) string {
switch action {
case "publish_draft":
return ":construction:"
case "fix_tests":
return ":cockroach:"
case "tests_pending":
return ":test_tube:"
case "review", "re_review", "request_reviewers":
return ":hourglass:"
case "resolve_comments", "respond", "review_discussion":
return ":carpentry_saw:"
case "approve":
return ":white_check_mark:"
case "merge":
return ":rocket:"
default:
return ":postal_horn:"
}
}
// actionPriority returns a priority score for action kinds (lower = higher priority).
// Used to determine which emoji to show when multiple actions are pending.
func actionPriority(action string) int {
switch action {
case "publish_draft":
return 1
case "fix_tests":
return 2
case "tests_pending":
return 3
case "fix_conflict":
return 4
case "resolve_comments", "respond", "review_discussion":
return 5
case "review", "re_review", "request_reviewers":
return 6
case "approve":
return 7
case "merge":
return 8
default:
return 99
}
}
// PrimaryAction determines the primary action kind from a NextAction map.
// Returns the highest-priority action (lowest priority score).
func PrimaryAction(nextActions map[string]turn.Action) string {
if len(nextActions) == 0 {
return ""
}
var primaryAction string
minPriority := 999
// Track all actions considered for debugging
actionPriorities := make(map[string]int)
for _, action := range nextActions {
kind := string(action.Kind)
priority := actionPriority(kind)
actionPriorities[kind] = priority
if priority < minPriority {
minPriority = priority
primaryAction = kind
}
}
slog.Debug("determined primary action from priorities",
"primary_action", primaryAction,
"primary_priority", minPriority,
"all_action_priorities", actionPriorities)
return primaryAction
}
// PrefixForAnalysis returns the emoji prefix based on workflow state and next actions.
// This is the primary function for determining PR emoji - it handles the logic:
// 1. Use WorkflowState as primary signal (most reliable)
// 2. Fall back to NextAction if no WorkflowState
func PrefixForAnalysis(workflowState string, nextActions map[string]turn.Action) string {
// Log input for debugging emoji selection
actionKinds := make([]string, 0, len(nextActions))
for user, action := range nextActions {
actionKinds = append(actionKinds, fmt.Sprintf("%s:%s", user, action.Kind))
}
slog.Debug("determining emoji prefix",
"workflow_state", workflowState,
"next_actions_count", len(nextActions),
"next_actions", actionKinds)
// Use WorkflowState as primary signal
if workflowState != "" {
emoji, _ := emojiFromWorkflowState(workflowState, nextActions)
slog.Debug("determined emoji from workflow_state",
"workflow_state", workflowState,
"emoji", emoji)
return emoji
}
// Fallback to NextAction if no WorkflowState
primaryAction := PrimaryAction(nextActions)
if primaryAction != "" {
emoji := PrefixForAction(primaryAction)
slog.Debug("determined emoji from primary action (no workflow_state)",
"primary_action", primaryAction,
"emoji", emoji)
return emoji
}
// Final fallback if no workflow state or actions
slog.Info("no workflow_state or primary action - using fallback emoji",
"next_actions_count", len(nextActions),
"fallback_emoji", ":postal_horn:")
return ":postal_horn:"
}
// NotifyUser sends a smart notification to a user about a PR using the configured logic.
// Implements delayed DM logic: if user was tagged in channel, delay by configured time.
// If user is not in channel where tagged, send DM immediately.
//
//nolint:revive,maintidx // function length acceptable for complex notification logic
func (m *Manager) NotifyUser(ctx context.Context, workspaceID, userID, channelID, channelName string, pr PRInfo) error {
slog.Info("evaluating notification for user",
"user", userID,
"workspace", workspaceID,
"owner", pr.Owner,
"repo", pr.Repo,
"pr_number", pr.Number,
"pr_state", pr.State,
"channel", channelID,
"channel_name", channelName)
// Get the Slack client for this workspace
slackClient, err := m.slackManager.Client(ctx, workspaceID)
if err != nil {
slog.Error("failed to get Slack client for workspace",
"workspace", workspaceID,
"error", err)
return fmt.Errorf("failed to get Slack client: %w", err)
}
lastDM := m.Tracker.LastDMNotification(workspaceID, userID)
tagInfo := m.Tracker.LastUserPRChannelTag(workspaceID, userID, pr.Owner, pr.Repo, pr.Number)
slog.Debug("notification state",
"user", userID,
"last_dm", lastDM,
"last_channel_tag", tagInfo.Timestamp,
"tag_channel_id", tagInfo.ChannelID)
// Check if user is active on Slack.
isActive := slackClient.IsUserActive(ctx, userID)
slog.Debug("checking user activity status",
"user", userID,
"is_active", isActive)
if !isActive {
slog.Info("deferring notification - user not active on Slack",
"user", userID,
"pr", fmt.Sprintf("%s/%s#%d", pr.Owner, pr.Repo, pr.Number),
"will_retry_when_active", true)
return nil
}
// Avoid spamming - don't send DM if we recently sent one
timeSinceLastDM := time.Since(lastDM)
antiSpamDelay := 1 * time.Minute
slog.Debug("checking anti-spam protection",
"user", userID,
"time_since_last_dm", timeSinceLastDM,
"anti_spam_delay", antiSpamDelay,
"will_block", timeSinceLastDM < antiSpamDelay)
if timeSinceLastDM < antiSpamDelay {
slog.Info("skipping DM - anti-spam protection active",
"user", userID,
"pr", fmt.Sprintf("%s/%s#%d", pr.Owner, pr.Repo, pr.Number),
"time_since_last_dm", timeSinceLastDM,
"anti_spam_delay", antiSpamDelay,
"time_until_next_allowed", antiSpamDelay-timeSinceLastDM)
return nil
}
// Check if we should delay this DM based on channel tag timing
if !tagInfo.Timestamp.IsZero() {
// User was tagged in a channel - use the ACTUAL channel they were tagged in
taggedChannelID := tagInfo.ChannelID
// Check if they're in that specific channel
userInChannel := slackClient.IsUserInChannel(ctx, taggedChannelID, userID)
// Get configured delay for this channel/org (we need channel name for config lookup)
// If channelName wasn't provided, we can't look up config - use default
delayMins := defaultReminderDMDelayMinutes
if channelName != "" {
delayMins = m.configManager.ReminderDMDelay(pr.Owner, channelName)
}
slog.Debug("evaluating follow-up reminder delay",
"user", userID,
"pr", fmt.Sprintf("%s/%s#%d", pr.Owner, pr.Repo, pr.Number),
"user_in_channel", userInChannel,
"channel_tag_time", tagInfo.Timestamp,
"tagged_channel_id", taggedChannelID,
"configured_delay_mins", delayMins)
if delayMins == 0 {
slog.Info("follow-up reminders disabled for this channel - skipping DM",
"user", userID,
"pr", fmt.Sprintf("%s/%s#%d", pr.Owner, pr.Repo, pr.Number),
"channel", channelName,
"channel_id", taggedChannelID)
return nil
}
if userInChannel {
// User is in the channel - apply delay
timeSinceTag := time.Since(tagInfo.Timestamp)
delayDuration := time.Duration(delayMins) * time.Minute
if timeSinceTag < delayDuration {
// Queue this DM to be sent later
sendAfter := tagInfo.Timestamp.Add(delayDuration)
// Serialize NextAction map to JSON
nextActionsJSON, err := json.Marshal(pr.NextAction)
if err != nil {
slog.Error("failed to serialize next actions for pending DM",
"user", userID,
"pr", fmt.Sprintf("%s/%s#%d", pr.Owner, pr.Repo, pr.Number),
"error", err)
nextActionsJSON = []byte("{}")
}
pendingDM := state.PendingDM{
ID: uuid.New().String(),
WorkspaceID: workspaceID,
UserID: userID,
PROwner: pr.Owner,
PRRepo: pr.Repo,
PRNumber: pr.Number,
PRURL: pr.HTMLURL,
PRTitle: pr.Title,
PRAuthor: pr.Author,
PRState: pr.State,
WorkflowState: pr.WorkflowState,
NextActions: string(nextActionsJSON),
ChannelID: taggedChannelID,
ChannelName: channelName,
QueuedAt: time.Now(),
SendAfter: sendAfter,
}
if err := m.store.QueuePendingDM(pendingDM); err != nil {
slog.Error("failed to queue pending DM",
"user", userID,
"pr", fmt.Sprintf("%s/%s#%d", pr.Owner, pr.Repo, pr.Number),
"error", err)
return fmt.Errorf("failed to queue pending DM: %w", err)
}
slog.Info("queued DM for later delivery",
"user", userID,
"pr", fmt.Sprintf("%s/%s#%d", pr.Owner, pr.Repo, pr.Number),
"channel_id", taggedChannelID,
"time_since_tag", timeSinceTag,
"configured_delay", delayDuration,
"send_after", sendAfter,
"time_until_dm", delayDuration-timeSinceTag,
"dm_id", pendingDM.ID)
return nil
}
slog.Info("sending delayed follow-up DM - user was tagged but delay elapsed",
"user", userID,
"pr", fmt.Sprintf("%s/%s#%d", pr.Owner, pr.Repo, pr.Number),
"channel_id", taggedChannelID,
"time_since_tag", timeSinceTag,
"configured_delay", delayDuration)
} else {
// User is NOT in the channel - send DM immediately
slog.Info("sending immediate DM - user not in channel where tagged",
"user", userID,
"pr", fmt.Sprintf("%s/%s#%d", pr.Owner, pr.Repo, pr.Number),
"channel_id", taggedChannelID)
}
} else {
slog.Debug("no channel tag found - sending DM without delay",
"user", userID,
"pr", fmt.Sprintf("%s/%s#%d", pr.Owner, pr.Repo, pr.Number))
}
// Format notification message using same style as channel messages
// Determine emoji prefix based on workflow state and next actions
var prefix string
if pr.WorkflowState != "" {
prefix = PrefixForAnalysis(pr.WorkflowState, pr.NextAction)
} else {
// Fallback to state if workflow state not available
prefix = PrefixForState(pr.State)
}
// Format: :emoji: Title <url|repo#123> · author → action
var action string
switch pr.State {
case "newly_published":
action = "newly published"
case "tests_broken":
action = "fix tests"
case "awaiting_review":
action = "review"
case "changes_requested":
action = "address feedback"
case "approved":
action = "merge"
default:
action = "attention needed"
}
// Use same compact format as channel messages
message := fmt.Sprintf(
"%s %s <%s|%s#%d> · %s → %s",
prefix,
pr.Title,
pr.HTMLURL,
pr.Repo,
pr.Number,
pr.Author,
action,
)
slog.Info("sending DM notification to user",
"user", userID,
"pr", fmt.Sprintf("%s/%s#%d", pr.Owner, pr.Repo, pr.Number),
"pr_state", pr.State,
"action_required", action,
"message", message)
// Try to update existing DM first (if one exists in our state store)
// UpdateDMMessage returns ErrNoDMToUpdate if no DM exists
updateErr := slackClient.UpdateDMMessage(ctx, userID, pr.HTMLURL, message)
if updateErr == nil {
// Successfully updated existing DM
slog.Info("successfully updated existing DM with new PR state",
"user", userID,
"pr", fmt.Sprintf("%s/%s#%d", pr.Owner, pr.Repo, pr.Number),
"pr_state", pr.State,
"action_required", action)
return nil
}
// Check if it's because no DM exists (expected case for first notification)
if !errors.Is(updateErr, slack.ErrNoDMToUpdate) {
// Actual error occurred during update - log warning but continue to send new DM
slog.Warn("failed to update existing DM, will send new one",
"user", userID,
"pr", fmt.Sprintf("%s/%s#%d", pr.Owner, pr.Repo, pr.Number),
"error", updateErr)
}
slog.Debug("no existing DM to update, will check for recent DMs and potentially send new one",
"user", userID,
"pr", fmt.Sprintf("%s/%s#%d", pr.Owner, pr.Repo, pr.Number),
"reason", "DM not in state store or too old")
// Check if we recently sent a DM about this PR (prevents duplicates during rolling deployments)
hasRecent, err := slackClient.HasRecentDMAboutPR(ctx, userID, pr.HTMLURL)
if err != nil {
slog.Warn("failed to check for recent DM, will send anyway to avoid false negative",
"user", userID,
"pr", fmt.Sprintf("%s/%s#%d", pr.Owner, pr.Repo, pr.Number),
"error", err,
"check_window", "1h",
"impact", "possible_duplicate_dm")
} else if hasRecent {
slog.Info("skipping DM - already sent notification about this PR recently",
"user", userID,
"pr", fmt.Sprintf("%s/%s#%d", pr.Owner, pr.Repo, pr.Number),
"check_window", "1h",
"reason", "duplicate prevention during rolling deployment",
"will_retry_later", false)
return nil
}
// Send DM to user.
dmChannelID, messageTS, err := slackClient.SendDirectMessage(ctx, userID, message)
if err != nil {
slog.Error("failed to send DM notification",
"user", userID,
"pr", fmt.Sprintf("%s/%s#%d", pr.Owner, pr.Repo, pr.Number),
"error", err,
"will_retry", true)
return fmt.Errorf("failed to send notification: %w", err)
}
// Update last DM notification time.
m.Tracker.UpdateDMNotification(workspaceID, userID)
// Save DM message info for future updates
if err := slackClient.SaveDMMessageInfo(ctx, userID, pr.HTMLURL, dmChannelID, messageTS, message); err != nil {
slog.Warn("failed to save DM message info",
"user", userID,
"pr", fmt.Sprintf("%s/%s#%d", pr.Owner, pr.Repo, pr.Number),
"error", err,
"impact", "DM won't be updated on state changes")
}
slog.Info("successfully sent DM notification",
"user", userID,
"pr", fmt.Sprintf("%s/%s#%d", pr.Owner, pr.Repo, pr.Number),
"pr_author", pr.Author,
"pr_state", pr.State,
"action_required", action,
"notification_updated", true,
"dm_channel_id", dmChannelID,
"message_ts", messageTS)
return nil
}