forked from Windshiftapp/core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
2852 lines (2607 loc) · 115 KB
/
Copy pathserver.go
File metadata and controls
2852 lines (2607 loc) · 115 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 server provides a reusable HTTP server for windshift.
// This allows the server to be started both from the main binary
// and in-process for integration tests.
package server
import (
"bytes"
"context"
"embed"
"encoding/json"
"errors"
"fmt"
"io/fs"
"log/slog"
"net"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"sync"
"time"
"windshift/internal/aitools"
"windshift/internal/auth"
"windshift/internal/authz"
"windshift/internal/config"
"windshift/internal/database"
"windshift/internal/email"
"windshift/internal/emailutil"
"windshift/internal/events"
"windshift/internal/handlers"
"windshift/internal/health"
"windshift/internal/ldap"
"windshift/internal/llm"
"windshift/internal/logger"
mcpserver "windshift/internal/mcp"
appmetrics "windshift/internal/metrics"
"windshift/internal/middleware"
"windshift/internal/models"
"windshift/internal/objecttranslation"
"windshift/internal/plugins"
"windshift/internal/portalwebauthn"
"windshift/internal/repository"
"windshift/internal/restapi"
v1 "windshift/internal/restapi/v1"
v2 "windshift/internal/restapi/v2"
"windshift/internal/router"
"windshift/internal/routes"
"windshift/internal/scheduler"
"windshift/internal/scm"
"windshift/internal/services"
"windshift/internal/smtp"
"windshift/internal/standardagent"
"windshift/internal/utils"
"windshift/internal/webauthn"
"windshift/internal/webhook"
)
type planningReleaseProviderAdapter struct {
provider scm.ReleaseProvider
}
func (a planningReleaseProviderAdapter) CreateRelease(ctx context.Context, owner, repo string, input services.ExternalReleaseOptions) (*services.ExternalRelease, error) {
release, err := a.provider.CreateRelease(ctx, owner, repo, scm.CreateReleaseOptions{
TagName: input.TagName, TargetCommitish: input.TargetCommitish, Name: input.Name,
Body: input.Body, IsDraft: input.IsDraft, IsPrerelease: input.IsPrerelease,
})
if err != nil {
return nil, err
}
return &services.ExternalRelease{ID: release.ID, URL: release.URL, TagName: release.TagName}, nil
}
func (a planningReleaseProviderAdapter) ListReleases(ctx context.Context, owner, repo string) ([]services.ExternalRelease, error) {
releases, err := a.provider.ListReleases(ctx, owner, repo)
if err != nil {
return nil, err
}
result := make([]services.ExternalRelease, len(releases))
for i := range releases {
result[i] = services.ExternalRelease{ID: releases[i].ID, URL: releases[i].URL, TagName: releases[i].TagName}
}
return result, nil
}
// Config is an alias to config.Config — the canonical, fully-resolved runtime
// configuration. All resolution of env vars and CLI flags happens in
// internal/config/Load; this package only consumes the result.
type Config = config.Config
const (
databasePoolBudgetWarningPercent = 90
maxRequestHeaderValueCount = 128
)
// Server represents a windshift HTTP server instance.
type Server struct {
config Config
httpServer *http.Server
db database.Database
listener net.Listener
permissionService *services.PermissionService
sessionManager *auth.SessionManager
tokenManager *auth.TokenManager
scimTokenManager *auth.SCIMTokenManager
itemCache *services.ItemCacheService
ldapHandler *handlers.LDAPHandler
notificationManager *handlers.NotificationManager
notificationService *services.NotificationService
notificationScheduler *scheduler.NotificationScheduler
recurrenceScheduler *scheduler.RecurrenceScheduler
cfvCleanupScheduler *scheduler.CFVCleanupScheduler
todoistSyncScheduler *scheduler.TodoistSyncScheduler
runnerLeaseReaper *scheduler.RunnerLeaseReaper
globalRankMigrationScheduler *scheduler.GlobalRankMigrationScheduler
codingRunService *services.RunService
standardAgentDispatcher *standardagent.Dispatcher
workflowService *services.WorkflowService
actionService *services.ActionService
assetActionService *services.AssetActionService
eventEngine *events.Engine
approvalEscalationSweeper *services.ApprovalEscalationSweeper
emailScheduler *scheduler.EmailScheduler
emailTrackingRetention *scheduler.EmailTrackingRetentionSweeper
briefingScheduler *scheduler.BriefingScheduler
pluginScheduleScheduler *scheduler.PluginScheduleScheduler
activityTracker *services.ActivityTracker
tokenTracker *services.TokenTracker
webhookSender *webhook.WebhookSender
scmSyncStopChan chan struct{}
issueSyncStopChan chan struct{}
magicLinkStopChan chan struct{}
cleanupStopChan chan struct{}
jiraHostStopChan chan struct{}
cleanupTicker *time.Ticker
pluginManager *plugins.Manager
databaseDiagRepo *repository.DatabaseDiagnosticsRepository
databasePoolMonitor *services.DatabasePoolMonitor
channelService *services.ChannelService
memoryBudget config.MemoryBudget
metrics *appmetrics.Metrics
loginRateLimiter *middleware.RateLimiter
runnerRegisterLimiter *middleware.RateLimiter
fidoRateLimiter *middleware.RateLimiter
authRateLimiter *middleware.RateLimiter
scimRateLimiter *middleware.RateLimiter
portalSubmitLimiter *middleware.RateLimiter
portalSearchLimiter *middleware.RateLimiter
emailVerifyLimiter *middleware.RateLimiter
setupLimiter *middleware.RateLimiter
ssoRateLimiter *middleware.RateLimiter
portalAuthLimiter *middleware.RateLimiter
oauthTokenLimiter *middleware.RateLimiter
aiRateLimiter *middleware.RateLimiter
uploadLimiter *middleware.RateLimiter
webhookLimiter *middleware.RateLimiter
searchLimiter *middleware.RateLimiter
calendarFeedLimiter *middleware.RateLimiter
publicBoardLimiter *middleware.RateLimiter
userConcurrency *middleware.UserConcurrencyLimiter
actualPort int
started bool
shuttingDown bool
backgroundStopOnce sync.Once
}
// New creates a new Server instance with the given configuration.
// It initializes all services and handlers but does not start listening.
func New(cfg Config) (*Server, error) {
memoryBudget, err := config.ResolveMemoryBudget(cfg.Memory.LimitMB)
if err != nil {
return nil, fmt.Errorf("resolve memory budget: %w", err)
}
s := &Server{
config: cfg,
scmSyncStopChan: make(chan struct{}),
issueSyncStopChan: make(chan struct{}),
magicLinkStopChan: make(chan struct{}),
cleanupStopChan: make(chan struct{}),
jiraHostStopChan: make(chan struct{}),
memoryBudget: memoryBudget,
}
if err := s.initialize(); err != nil {
s.cleanup()
return nil, err
}
return s, nil
}
// initialize sets up all services and handlers.
func (s *Server) initialize() error {
// FIXME: split initialization into focused builders and lifecycle registries.
cfg := s.config
utils.SetSkipTLSVerify(cfg.OutboundTLS.SkipVerify)
if cfg.OutboundTLS.SkipVerify {
slog.Warn("outbound TLS certificate verification is disabled; self-signed certificates will be accepted without server identity verification")
}
if cfg.SilentMode {
logger.SetSilent(true)
}
var err error
if cfg.DB.PostgresConn != "" {
slog.Info("connecting to PostgreSQL database")
s.db, err = database.NewDatabase("postgres", cfg.DB.PostgresConn, cfg.DB.MaxReadConns, cfg.DB.MaxWriteConns)
if err != nil {
return fmt.Errorf("failed to connect to PostgreSQL database: %w", err)
}
slog.Info("PostgreSQL database initialized", "max_read_conns", cfg.DB.MaxReadConns, "max_write_conns", cfg.DB.MaxWriteConns)
} else {
slog.Info("connecting to SQLite database", "path", cfg.DB.SQLitePath)
s.db, err = database.NewDatabase("sqlite3", cfg.DB.SQLitePath, cfg.DB.MaxReadConns, cfg.DB.MaxWriteConns)
if err != nil {
return fmt.Errorf("failed to connect to SQLite database: %w", err)
}
slog.Info("SQLite database initialized", "max_read_conns", cfg.DB.MaxReadConns, "max_write_conns", cfg.DB.MaxWriteConns, "mode", "WAL")
}
s.databaseDiagRepo = repository.NewDatabaseDiagnosticsRepository(s.db)
if cfg.DB.PostgresConn != "" {
replicas := cfg.DB.ReplicaCount
if replicas <= 0 {
slog.Warn("invalid PostgreSQL replica count; capacity budget assumes one replica", "configured_replica_count", replicas)
replicas = 1
}
headroom := cfg.DB.ConnectionHeadroom
if headroom < 0 {
slog.Warn("invalid PostgreSQL connection headroom; capacity budget assumes zero", "configured_headroom", headroom)
headroom = 0
}
auxiliaryConnections := 0
if cfg.SSH.Enabled {
auxiliaryConnections = config.SSHDatabaseMaxConnections
}
budgetCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
budget, budgetErr := s.databaseDiagRepo.LoadPostgresCapacityBudget(
budgetCtx,
s.db,
replicas,
headroom,
auxiliaryConnections,
)
cancel()
if budgetErr != nil {
slog.Warn("unable to evaluate PostgreSQL connection capacity budget", "error", budgetErr)
} else {
logDatabaseCapacityBudget(budget)
}
}
s.databasePoolMonitor = services.NewDatabasePoolMonitor(s.databaseDiagRepo, services.DefaultDatabasePoolMonitorConfig())
if err = s.db.Initialize(); err != nil {
return fmt.Errorf("failed to initialize database: %w", err)
}
if err = database.ValidateCanonicalSchemaCheckpoint(s.db); err != nil {
return fmt.Errorf("database startup refused: %w", err)
}
objectTranslationService := objecttranslation.NewService(s.db)
if err := objectTranslationService.SyncSystem(context.Background(), objecttranslation.ShippedSystemTranslations()); err != nil {
return fmt.Errorf("sync shipped object translations: %w", err)
}
s.eventEngine = events.NewEngine(s.db, events.DefaultConfig())
if err = emailutil.SeedTemplates(s.db); err != nil {
slog.Warn("failed to seed default email templates", "error", err)
}
if err = repository.NewNotificationSettingsRepository(s.db).EnsureDefault(); err != nil {
slog.Warn("failed to ensure notification settings", "error", err)
}
if cfg.RecoverUser != "" {
s.recoverUser(cfg.RecoverUser)
}
setupCompleted, err := checkSetupStatusWithRetry(s.db, 5, time.Second)
if err != nil {
return fmt.Errorf("failed to determine setup status: %w", err)
}
permService, err := services.NewPermissionService(s.db, services.PermissionCacheConfig{
TTL: 15 * time.Minute,
MaxCacheSize: s.memoryBudget.PermissionCacheMB,
})
if err != nil {
return fmt.Errorf("failed to initialize permission service: %w", err)
}
s.permissionService = permService
// Shared channel service used by ChannelHandler, WebhookHandler,
// FormHandler, RequestTypeHandler, and AssetReportHandler for the
// "user manages channel C" gate.
channelService := services.NewChannelService(s.db, permService)
s.channelService = channelService
activityConfig := services.DefaultActivityTrackerConfig()
activityConfig.MaxCacheSize = s.memoryBudget.ActivityCacheMB
s.activityTracker, err = services.NewActivityTracker(s.db, activityConfig)
if err != nil {
return fmt.Errorf("failed to initialize activity tracker: %w", err)
}
s.cleanupTicker = time.NewTicker(24 * time.Hour)
go s.runActivityCleanup()
enableHTTPS := cfg.TLSCertPath != "" && cfg.TLSKeyPath != ""
var additionalProxyList []string
if cfg.AdditionalProxies != "" {
additionalProxyList = strings.Split(cfg.AdditionalProxies, ",")
}
ipExtractor := utils.NewIPExtractor(cfg.UseProxy, additionalProxyList)
primarySessionCacheMB, _ := config.SplitSSHCacheBudget(s.memoryBudget.SessionCacheMB, cfg.SSH.Enabled)
sessionManager := auth.NewSessionManagerWithValidationCacheTTL(
s.db,
enableHTTPS,
cfg.UseProxy,
additionalProxyList,
cfg.Auth.SessionSecret,
cfg.Auth.SessionIPBinding,
cfg.Auth.SessionValidationCacheTTL,
primarySessionCacheMB,
)
s.sessionManager = sessionManager
effectivePort := cfg.Port
if cfg.AllowedPort != "" {
effectivePort = cfg.AllowedPort
}
// WebAuthn settings are resolved by config.Load; development may override RPID.
isDevelopment := cfg.DisableCSRF
webAuthnConfig, portalWebAuthnConfig, err := initializeWebAuthnConfigs(cfg, isDevelopment, effectivePort, enableHTTPS)
if err != nil {
return err
}
var userKeyedOpts []middleware.RateLimiterOption
userKeyedOpts = append(userKeyedOpts, middleware.WithUserKeyed())
if cfg.DisableIPRateLimit {
userKeyedOpts = append(userKeyedOpts, middleware.WithDisableIPLimit())
}
s.loginRateLimiter = middleware.NewRateLimiter(5.0/60.0, 10, cfg.UseProxy, additionalProxyList)
s.runnerRegisterLimiter = middleware.NewRateLimiter(5.0/60.0, 10, cfg.UseProxy, additionalProxyList)
s.fidoRateLimiter = middleware.NewRateLimiter(10.0/60.0, 15, cfg.UseProxy, additionalProxyList)
s.scimRateLimiter = middleware.NewRateLimiter(10.0, 100, cfg.UseProxy, additionalProxyList)
s.portalSubmitLimiter = middleware.NewRateLimiter(5.0/60.0, 10, cfg.UseProxy, additionalProxyList)
s.portalSearchLimiter = middleware.NewRateLimiter(10.0/60.0, 15, cfg.UseProxy, additionalProxyList)
s.emailVerifyLimiter = middleware.NewRateLimiter(10.0/60.0, 15, cfg.UseProxy, additionalProxyList)
s.setupLimiter = middleware.NewRateLimiter(20.0/60.0, 30, cfg.UseProxy, additionalProxyList)
s.ssoRateLimiter = middleware.NewRateLimiter(10.0/60.0, 5, cfg.UseProxy, additionalProxyList)
s.portalAuthLimiter = middleware.NewRateLimiter(3.0/60.0, 3, cfg.UseProxy, additionalProxyList)
s.calendarFeedLimiter = middleware.NewRateLimiter(10.0/60.0, 15, cfg.UseProxy, additionalProxyList)
// Public boards are anonymous and can trigger substantial query and file IO.
// Keep this limiter IP-keyed even when authenticated IP limiting is disabled.
s.publicBoardLimiter = middleware.NewRateLimiter(30.0/60.0, 60, cfg.UseProxy, additionalProxyList)
// OAuth /token is unauthenticated (server-to-server), so it must stay
// IP-keyed and must NOT honor DisableIPRateLimit — otherwise enabling that
// flag for NAT deployments would silently remove all brute-force protection
// on client_secret/code guessing. Kept separate from the user-keyed
// authRateLimiter for exactly this reason.
s.oauthTokenLimiter = middleware.NewRateLimiter(20.0/60.0, 30, cfg.UseProxy, additionalProxyList)
s.authRateLimiter = middleware.NewRateLimiter(20.0/60.0, 30, cfg.UseProxy, additionalProxyList, userKeyedOpts...)
s.aiRateLimiter = middleware.NewRateLimiter(20.0/60.0, 30, cfg.UseProxy, additionalProxyList, userKeyedOpts...)
s.uploadLimiter = middleware.NewRateLimiter(10.0/60.0, 15, cfg.UseProxy, additionalProxyList, userKeyedOpts...)
s.webhookLimiter = middleware.NewRateLimiter(10.0/60.0, 15, cfg.UseProxy, additionalProxyList, userKeyedOpts...)
s.searchLimiter = middleware.NewRateLimiter(20.0/60.0, 30, cfg.UseProxy, additionalProxyList, userKeyedOpts...)
// Per-user in-flight concurrency cap for the whole /api surface — bounds how
// many shared DB-pool connections one user can hold so a runaway client
// can't starve the others. Applied to the api group below.
s.userConcurrency = middleware.NewUserConcurrencyLimiter(cfg.MaxUserConcurrency)
if cfg.MaxTemplateSeedItems > 0 {
services.MaxTemplateSeedItems = cfg.MaxTemplateSeedItems
}
s.tokenTracker = services.NewTokenTracker(s.db, services.DefaultTokenTrackerConfig())
apiTokenCacheMB, _ := config.SplitSSHCacheBudget(s.memoryBudget.APITokenCacheMB, cfg.SSH.Enabled)
tokenManager := auth.NewTokenManager(s.db, s.tokenTracker, apiTokenCacheMB)
s.tokenManager = tokenManager
if cleaned, cleanupErr := tokenManager.CleanupExpiredTokens(); cleanupErr != nil {
slog.Warn("failed to cleanup expired api tokens on startup", "error", cleanupErr)
} else if cleaned > 0 {
slog.Info("cleaned expired api tokens on startup", "count", cleaned)
}
userDeactivationService := services.NewUserDeactivationService(
s.db,
services.UserDeactivationInvalidators{
Tokens: tokenManager.InvalidateTokens,
Sessions: sessionManager.InvalidateUserSessionValidation,
Permissions: func(userID int) {
if err := permService.InvalidateUserCache(userID); err != nil {
slog.Warn("failed to invalidate permissions after user deactivation",
slog.Int("user_id", userID),
slog.Any("error", err))
}
},
},
)
authMiddleware := middleware.NewAuthMiddleware(sessionManager, tokenManager, s.db, cfg.UseProxy, additionalProxyList, setupCompleted)
var additionalProxyIPs []net.IP
for _, proxyStr := range additionalProxyList {
if ip := net.ParseIP(strings.TrimSpace(proxyStr)); ip != nil {
additionalProxyIPs = append(additionalProxyIPs, ip)
}
}
mux := http.NewServeMux()
healthHandler := health.NewHandler(s.db.GetDB())
mux.HandleFunc("GET /healthz", healthHandler.Liveness)
mux.HandleFunc("GET /readyz", healthHandler.Readiness)
s.metrics = appmetrics.New(s.db)
mux.Handle("GET /metrics", s.metrics.Handler())
nmCfg := handlers.DefaultNotificationManagerConfig()
nmCfg.MaxCacheSize = s.memoryBudget.NotificationCacheMB
if cfg.Notification.FlushInterval > 0 {
nmCfg.FlushInterval = cfg.Notification.FlushInterval
}
if cfg.Notification.BatchSize > 0 {
nmCfg.MaxBatchSize = cfg.Notification.BatchSize
}
if cfg.Notification.SyncInterval > 0 {
nmCfg.SyncInterval = cfg.Notification.SyncInterval
}
s.notificationManager, err = handlers.NewNotificationManager(s.db, nmCfg)
if err != nil {
return fmt.Errorf("failed to create notification manager: %w", err)
}
notificationAssetPermissions := services.NewAssetPermissionService(repository.NewAssetRepository(s.db), permService)
notificationAuthorizer := services.NewNotificationAuthorizer(s.db, permService, notificationAssetPermissions)
s.notificationService = services.NewNotificationService(
s.db,
s.notificationManager,
permService,
services.DefaultNotificationServiceConfig(),
notificationAssetPermissions,
)
if err := services.PrepareDurableNotificationEngine(context.Background(), s.eventEngine, s.notificationService); err != nil {
return fmt.Errorf("prepare durable notification consumers: %w", err)
}
smtpSender := smtp.NewNotificationSMTPSender(s.db)
s.notificationScheduler = scheduler.NewNotificationScheduler(s.db, smtpSender, cfg.Notification.BatchInterval, s.notificationService)
s.notificationScheduler.Start()
slog.Info("notification scheduler started")
// WorkflowService is constructed here (moved up from later in bootstrap) so the
// recurrence scheduler can resolve a workspace+item-type's initial status the
// same way the rest of the system does. The handler-side instance below reuses
// the same pointer, so the in-memory cache is shared.
s.workflowService = services.NewWorkflowService(s.db)
s.recurrenceScheduler = scheduler.NewRecurrenceScheduler(s.db, s.workflowService)
s.recurrenceScheduler.Start()
// Drains pending_custom_field_cleanups: when a custom field is
// deleted, items' cfv JSON still carries the deleted key. This
// scheduler scrubs them in batches so the Delete request returns
// immediately even when the workspace has millions of items.
s.cfvCleanupScheduler = scheduler.NewCFVCleanupScheduler(s.db)
s.cfvCleanupScheduler.Start()
// Liveness backstop for remote agent runs (WI-141): fail runs whose
// runner's heartbeat went stale and revoke the dead runner instances.
s.runnerLeaseReaper = scheduler.NewRunnerLeaseReaper(
repository.NewAgentRunRepository(s.db),
repository.NewRunnerRepository(s.db),
)
s.runnerLeaseReaper.Start()
globalRankHostname, hostnameErr := os.Hostname()
if hostnameErr != nil || globalRankHostname == "" {
globalRankHostname = "unknown-host"
}
globalRankOwner := fmt.Sprintf("global-rank-%s-%d", globalRankHostname, os.Getpid())
s.globalRankMigrationScheduler = scheduler.NewGlobalRankMigrationScheduler(s.db, globalRankOwner)
s.globalRankMigrationScheduler.Start()
slog.Info("global rank migration scheduler started", "owner", globalRankOwner)
slog.Info("recurrence scheduler started")
chainStore := services.NewExecutionChainStore()
s.actionService = services.NewActionService(s.db, services.DefaultActionServiceConfig(), chainStore)
s.actionService.SetNotificationService(s.notificationService)
s.actionService.SetPermissionService(permService)
if err := services.PrepareDurableActionEngine(context.Background(), s.eventEngine, s.actionService, cfg.ActivateDurableActions); err != nil {
return fmt.Errorf("prepare durable action consumers: %w", err)
}
slog.Info("action service initialized")
s.assetActionService = services.NewAssetActionService(s.db, services.DefaultActionServiceConfig(), chainStore)
s.assetActionService.SetNotificationService(s.notificationService)
s.assetActionService.SetPermissionService(permService)
if err := services.PrepareDurableAssetActionEngine(context.Background(), s.eventEngine, s.assetActionService, cfg.ActivateDurableAssetActions); err != nil {
return fmt.Errorf("prepare durable asset action consumers: %w", err)
}
slog.Info("asset action service initialized")
// Determine base URL — cfg.BaseURL is already resolved by config.Load
// from the --base-url flag or BASE_URL env; only the localhost fallback
// remains here because it needs cfg.Port.
baseURL := cfg.BaseURL
if baseURL == "" {
baseURL = fmt.Sprintf("http://localhost:%s%s", cfg.Port, cfg.ContextPath)
}
emailVerificationService := services.NewEmailVerificationService(s.db, smtpSender, baseURL)
portalSessionManager := auth.NewPortalSessionManager(s.db, enableHTTPS, cfg.UseProxy, additionalProxyList, cfg.Auth.SessionSecret, cfg.Auth.SessionIPBinding)
magicLinkService := services.NewMagicLinkService(s.db, smtpSender, baseURL)
invitationService := services.NewInvitationService(s.db, smtpSender, baseURL)
workspaceKeyCache := handlers.NewWorkspaceKeyCache(repository.NewWorkspaceRepository(s.db))
authorizationCacheInvalidator := services.NewAuthorizationCacheInvalidator(permService, workspaceKeyCache)
transitionMatrixService := services.NewTransitionMatrixService(s.db)
bulkOperationMetrics := services.NewBulkOperationMetrics()
itemHandler := handlers.NewItemHandler(s.db, permService, s.activityTracker, s.notificationService, s.memoryBudget.ItemCacheMB)
s.itemCache = itemHandler.ItemCacheService()
itemHandler.SetDBRequestTimeout(s.config.DB.RequestTimeout)
customFieldHandler := handlers.NewCustomFieldHandler(s.db)
workspaceHandler := handlers.NewWorkspaceHandler(s.db, permService, s.activityTracker, workspaceKeyCache, authorizationCacheInvalidator)
screenHandler := handlers.NewScreenHandler(s.db).WithObjectTranslations(objectTranslationService)
configSetHandler := handlers.NewConfigurationSetHandler(s.db, s.notificationService, permService).WithObjectTranslations(objectTranslationService)
// Shared audit emitter for enum services
enumAuditEmit := services.AuditEmitFunc(func(db database.Database, r *http.Request, actionType, resourceType string, entityID int, entityName string) {
currentUser := utils.GetCurrentUser(r)
if currentUser == nil {
return
}
_ = logger.LogAudit(db, logger.AuditEvent{
UserID: currentUser.ID,
Username: currentUser.Username,
IPAddress: utils.GetClientIP(r),
UserAgent: r.UserAgent(),
ActionType: actionType,
ResourceType: resourceType,
ResourceID: &entityID,
ResourceName: entityName,
Success: true,
})
})
hierarchyLevelConfig := services.NewHierarchyLevelConfig()
hierarchyLevelConfig.AuditEmit = enumAuditEmit
hierarchyLevelHandler := handlers.NewEnumHandler(
services.NewEnumService(s.db, hierarchyLevelConfig),
func() any { return &models.HierarchyLevel{} }).WithObjectTranslations(objectTranslationService, "hierarchy_level")
requestTypeHandler := handlers.NewRequestTypeHandler(
repository.NewRequestTypeRepository(s.db),
repository.NewChannelRepository(s.db),
repository.NewScreenRepository(s.db),
repository.NewItemTypeRepository(s.db),
logger.NewAuditor(s.db),
channelService,
)
workflowService := s.workflowService
userHandler := handlers.NewUserHandler(
repository.NewUserRepository(s.db),
logger.NewAuditor(s.db),
permService,
invitationService,
services.NewUserReadService(s.db),
func(id int) error {
tokenIDs, err := services.OffboardUser(s.db, id, s.notificationService, authorizationCacheInvalidator)
tokenManager.InvalidateTokens(tokenIDs)
sessionManager.InvalidateUserSessionValidation(id)
return err
},
userDeactivationService.DeactivateUser,
sessionManager.InvalidateUserSessionValidation,
)
groupHandler := handlers.NewGroupHandler(repository.NewGroupRepository(s.db), permService, logger.NewAuditor(s.db), authorizationCacheInvalidator)
credentialHandler := handlers.NewCredentialHandler(repository.NewCredentialRepository(s.db), logger.NewAuditor(s.db), permService, cfg.SSH.Enabled)
var webAuthnHandler *handlers.WebAuthnHandler
if webAuthnConfig != nil {
webAuthnHandler = handlers.NewWebAuthnHandler(s.db, permService, sessionManager, webAuthnConfig, ipExtractor)
}
publicBoardHandler := handlers.NewPublicBoardHandler(s.db, permService, cfg.AttachmentPath)
permissionHandler := handlers.NewPermissionHandlerWithCache(repository.NewPermissionRepository(s.db), permService, logger.NewAuditor(s.db))
apiTokenHandler := handlers.NewAPITokenHandler(
tokenManager,
repository.NewAPITokenPolicyRepository(s.db),
repository.NewWorkspaceRepository(s.db),
logger.NewAuditor(s.db),
permService,
)
agentHandler := handlers.NewAgentHandler(s.db, permService)
scimTokenManager := auth.NewSCIMTokenManager(s.db, s.memoryBudget.SCIMTokenCacheMB)
s.scimTokenManager = scimTokenManager
scimAuthMiddleware := middleware.NewSCIMAuthMiddleware(scimTokenManager)
scimHandler := handlers.NewSCIMHandler(
repository.NewSCIMRepository(s.db),
baseURL,
permService,
logger.NewAuditor(s.db),
userDeactivationService.DeactivateUser,
func() ([]int, error) {
return services.ActiveSystemAdminIDs(s.db)
},
s.notificationService,
authorizationCacheInvalidator,
)
scimTokenHandler := handlers.NewSCIMTokenHandler(scimTokenManager, logger.NewAuditor(s.db))
permissionSetHandler := handlers.NewPermissionSetHandlerWithPool(repository.NewPermissionSetRepository(s.db), permService, logger.NewAuditor(s.db))
workspaceRoleHandler := handlers.NewWorkspaceRoleHandlerWithPool(repository.NewWorkspaceRoleRepository(s.db), permService, logger.NewAuditor(s.db)).WithObjectTranslations(objectTranslationService)
timePermissionService := services.NewTimePermissionService(s.db, permService)
customerOrgPermissionService := services.NewCustomerOrganisationPermissionService(s.db, permService, timePermissionService)
timeCustomerHandler := handlers.NewTimeCustomerHandler(repository.NewCustomerOrganisationRepository(s.db), logger.NewAuditor(s.db), timePermissionService, customerOrgPermissionService)
timeProjectHandler := handlers.NewTimeProjectHandler(s.db, timePermissionService, customerOrgPermissionService)
timeWorklogService := services.NewTimeWorklogService(s.db)
activeTimerRepo := repository.NewActiveTimerRepository(s.db)
timerService := services.NewTimerService(activeTimerRepo, repository.NewItemRepository(s.db), timePermissionService, permService)
customerOrgPermissionHandler := handlers.NewCustomerOrganisationPermissionHandler(logger.NewAuditor(s.db), customerOrgPermissionService)
itemLinkService := services.NewItemLinkService(s.db).
WithPermissionService(permService).
WithNotificationEmitter(s.notificationService)
pageLabelRepo := repository.NewPageLabelRepository(s.db)
pageService := services.NewPageService(s.db)
pageService.SetPageLabelRepository(pageLabelRepo)
pagePermissionService := services.NewPagePermissionService(s.db, permService)
itemLinkService.WithPagePermissionChecker(pagePermissionService)
pageApplication := services.NewPageApplicationService(pageService, pagePermissionService)
pageDiagramService := services.NewPageDiagramService(
s.db,
cfg.AttachmentPath,
pageApplication,
pagePermissionService,
permService,
)
knowledgeRetrieval := services.NewKnowledgeRetrievalService(s.db, pagePermissionService)
knowledgeSearchHandler := handlers.NewKnowledgeSearchHandler(knowledgeRetrieval)
pageLabelService := services.NewPageLabelService(pageLabelRepo, logger.NewAuditor(s.db))
recurrenceService := services.NewRecurrenceService(repository.NewRecurrenceRepository(s.db), s.recurrenceScheduler, logger.NewAuditor(s.db))
actionsHandler := handlers.NewActionsHandler(
repository.NewActionRepository(s.db),
repository.NewActionCredentialRepository(s.db),
logger.NewAuditor(s.db),
workspaceKeyCache,
)
actionCredentialService := services.NewActionCredentialService(repository.NewActionCredentialRepository(s.db), cfg.Auth.SessionSecret)
actionCredentialsHandler := handlers.NewActionCredentialsHandler(actionCredentialService, permService, workspaceKeyCache, logger.NewAuditor(s.db))
// Wire credential resolution into the action runtime so HTTP capabilities
// can reference tokens by ID. The service shares the same SSO_SECRET via
// a domain-separated HKDF label (ActionCredentialEncryptionInfo).
credentialSvc := services.NewActionCredentialService(
repository.NewActionCredentialRepository(s.db),
cfg.Auth.SessionSecret,
)
s.actionService.SetCredentialService(credentialSvc)
// Lets container_run nodes dispatch to a remote runner pool (WI-146).
s.actionService.SetAgentRunRepository(repository.NewAgentRunRepository(s.db))
// One-shot scanner: warn about any legacy capability whose
// default_headers still holds a sensitive header value. The scanner logs
// capability ID + header name only — never the value.
services.ScanLegacyInlineSecrets(s.db)
// Team handlers
teamRepo := repository.NewTeamRepository(s.db)
leaveRepo := repository.NewLeaveRepository(s.db)
onCallRepo := repository.NewOnCallRepository(s.db)
teamService := services.NewTeamService(s.db, teamRepo, leaveRepo)
onCallService := services.NewOnCallService(s.db, onCallRepo, leaveRepo)
teamHandler := handlers.NewTeamHandler(teamRepo, leaveRepo, permService, logger.NewAuditor(s.db))
leaveHandler := handlers.NewLeaveHandler(leaveRepo, repository.NewUserRepository(s.db), permService)
onCallHandler := handlers.NewOnCallHandler(onCallRepo, teamRepo, onCallService, permService, logger.NewAuditor(s.db))
s.actionService.SetTeamService(teamService)
milestoneCategoryConfig := services.NewMilestoneCategoryConfig()
milestoneCategoryConfig.AuditEmit = enumAuditEmit
milestoneCategoryHandler := handlers.NewEnumHandler(
services.NewEnumService(s.db, milestoneCategoryConfig),
func() any { return &models.MilestoneCategory{} }).WithGlobalMutationPermission(permService, models.PermissionMilestoneCreate)
channelCategoryConfig := services.NewChannelCategoryConfig()
channelCategoryConfig.AuditEmit = enumAuditEmit
channelCategoryHandler := handlers.NewEnumHandler(
services.NewEnumService(s.db, channelCategoryConfig),
func() any { return &models.ChannelCategory{} })
iterationTypeConfig := services.NewIterationTypeConfig()
iterationTypeConfig.AuditEmit = enumAuditEmit
iterationTypeHandler := handlers.NewEnumHandler(
services.NewEnumService(s.db, iterationTypeConfig),
func() any { return &models.IterationType{} }).WithGlobalMutationPermission(permService, models.PermissionIterationManage)
personalLabelHandler := handlers.NewPersonalLabelHandler(s.db, permService)
reviewHandler := handlers.NewReviewHandler(s.db, permService)
calendarFeedHandler := handlers.NewCalendarFeedHandler(s.db, permService, cfg.BaseURL)
securitySettingsHandler := handlers.NewSecuritySettingsHandler(repository.NewSystemSettingRepository(s.db), logger.NewAuditor(s.db), cfg.Plugins.Disabled)
// WI-87/88/89/90 coding-agent harness stack lands later in the
// constructor — see the block right after the SCM handlers are
// built, since scm.CredentialResolver needs scmProviderHandler.GetEncryption().
var adminRateLimiter *middleware.AdminFallbackRateLimiter
if cfg.EnableAdminFallback {
adminRateLimiter = middleware.NewAdminFallbackRateLimiter(s.db)
slog.Info("Admin password fallback enabled", slog.String("component", "auth"))
}
authPolicyHandler := handlers.NewAuthPolicyHandlerWithFallback(s.db, cfg.EnableAdminFallback, logger.NewAuditor(s.db))
if webAuthnHandler != nil {
webAuthnHandler.SetAuthPolicyHandler(authPolicyHandler)
}
authHandler := handlers.NewAuthHandler(
repository.NewUserRepository(s.db),
repository.NewCredentialRepository(s.db),
logger.NewAuditor(s.db),
sessionManager,
s.loginRateLimiter,
permService,
emailVerificationService,
ipExtractor,
authPolicyHandler,
adminRateLimiter,
)
invitationHandler := handlers.NewInvitationHandler(invitationService)
themeHandler := handlers.NewThemeHandler(services.NewThemeService(repository.NewThemeRepository(s.db)), logger.NewAuditor(s.db)).WithObjectTranslations(objectTranslationService)
objectTranslationHandler := handlers.NewObjectTranslationHandler(objectTranslationService)
userPreferencesService := services.NewUserPreferencesService(repository.NewUserPreferencesRepository(s.db), repository.NewThemeRepository(s.db), permService)
userPreferencesHandler := handlers.NewUserPreferencesHandler(userPreferencesService)
homepageHandler := handlers.NewHomepageHandler(
repository.NewWorkspaceRepository(s.db),
repository.NewItemRepository(s.db),
services.NewItemCRUDService(s.db),
services.NewPlanningService(s.db),
s.activityTracker,
permService,
userPreferencesService,
)
notificationHandler := handlers.NewNotificationHandler(s.notificationManager, s.notificationService, permService)
notificationHandler.SetNotificationAuthorizer(notificationAuthorizer)
emailTemplateHandler := handlers.NewEmailTemplateHandler(repository.NewEmailTemplateRepository(s.db), logger.NewAuditor(s.db))
// Push dispatches every notification; VAPID config resolves env, persisted,
// then generated keys.
pushCfg := services.ResolveVAPIDConfig(s.db, cfg.Push, slog.Default())
pushService := services.NewPushService(s.db, pushCfg, permService)
pushService.SetNotificationAuthorizer(notificationAuthorizer)
pushHandler := handlers.NewPushHandler(pushService)
s.notificationManager.SetPushDispatcher(pushService)
if pushService.Enabled() {
slog.Info("Web Push enabled")
}
permissionMiddleware := middleware.NewPermissionMiddleware(s.db, permService)
setupHandler := handlers.NewSetupHandler(s.db, sessionManager, authMiddleware)
ssoHandler := handlers.NewSSOHandler(s.db, sessionManager, permService, emailVerificationService, s.pluginManager, cfg.Auth.SessionSecret, baseURL, cfg.AllowedHosts, cfg.DisableCSRF, ipExtractor, cfg.UseProxy, additionalProxyList)
scmProviderHandler := handlers.NewSCMProviderHandler(s.db, cfg.Auth.SessionSecret, baseURL)
scmWorkspaceRepo := repository.NewSCMWorkspaceRepository(s.db)
scmWorkspaceHandler := handlers.NewSCMWorkspaceHandler(scmWorkspaceRepo, scmProviderHandler.GetEncryption(), scmProviderHandler, scm.NewCredentialResolver(s.db, scmProviderHandler.GetEncryption()), permService, baseURL)
scmItemLinksHandler := handlers.NewSCMItemLinksHandler(s.db, scmProviderHandler.GetEncryption(), permService)
userSCMTokenHandler := handlers.NewUserSCMTokenHandler(repository.NewUserSCMTokenRepository(s.db), scmProviderHandler.GetEncryption())
milestonePlanningService := services.NewPlanningService(s.db)
milestonePlanningService.SetSCMWorkspaceRepository(scmWorkspaceRepo)
// The optional coding-agent harness queues and finalizes remote runner-pool
// work; disabled mode retains bindings without starting runs.
agentSecurityRepo := repository.NewAgentSecurityRepository(s.db)
agentIdentitySvc, _ := services.NewAgentActingIdentityService(services.NewUserReadService(s.db), agentSecurityRepo)
agentBindingRepo := repository.NewWorkspaceAgentBindingRepository(s.db)
scmCredResolver := scm.NewCredentialResolver(s.db, scmProviderHandler.GetEncryption())
// AI handlers and agents share embedded or configured prompt overrides.
promptStore := llm.NewPromptStore(cfg.LLM.PromptsDir)
// System-admin-overridable Agent Studio catalog (WI-922): configured rows
// overlay or disable embedded defaults.
agentTemplateCatalogRepo := repository.NewAgentTemplateCatalogRepository(s.db)
templateCatalog := llm.NewTemplateCatalog(promptStore, agentTemplateCatalogRepo)
agentTemplateCatalogHandler := handlers.NewAdminAgentTemplateCatalogHandler(agentTemplateCatalogRepo, permService, logger.NewAuditor(s.db))
agentTemplateCatalogHandler.SetDefaults(promptStore)
// Bindings and AI handlers share the provider registry.
if cfg.LLM.ProvidersFile != "" {
if err := llm.LoadProviders(cfg.LLM.ProvidersFile); err != nil {
slog.Error("failed to load custom LLM providers file, falling back to built-in defaults", "path", cfg.LLM.ProvidersFile, "error", err)
llm.LoadDefaultProviders()
} else {
slog.Info("loaded custom LLM providers", "path", cfg.LLM.ProvidersFile)
}
} else {
llm.LoadDefaultProviders()
}
fallbackLLMClient := llm.NewClient(llm.Config{Endpoint: cfg.LLM.Endpoint})
if fallbackLLMClient.Available() {
slog.Info("LLM fallback service configured", slog.String("endpoint", cfg.LLM.Endpoint))
} else {
slog.Info("LLM fallback service not configured")
}
llmManager := llm.NewConnectionManager(s.db, scmProviderHandler.GetEncryption(), fallbackLLMClient)
llmModelCache := llm.NewModelCache(s.db)
llmManager.SetModelCache(llmModelCache) // freshest vision-capability resolution
llmModelRefresher := llm.NewModelRefresher(llmModelCache)
var codingRunSvc *services.RunService
if cfg.CodingAgent.Enabled {
var bootErr error
codingRunSvc, bootErr = bootCodingAgentRunService(s.db, tokenManager, agentBindingRepo, scmCredResolver, promptStore.Get(llm.PromptCodingAgentInitial))
if bootErr != nil {
slog.Warn("coding-agent harness disabled: failed to construct RunService",
slog.String("component", "coding-agent"),
slog.Any("error", bootErr),
)
}
}
// Retain the service so shutdown can drain local runs.
s.codingRunService = codingRunSvc
agentAPIURL := cfg.CodingAgent.WSAPIURL
if agentAPIURL == "" {
// Agent broker URLs require the API suffix, not the SPA base URL.
agentAPIURL = strings.TrimRight(baseURL, "/") + "/api"
}
agentSkillRepo := repository.NewWorkspaceAgentSkillRepository(s.db)
standardCapabilityGroups := aitools.StandardCapabilityGroups(aitools.Default)
standardCapabilityKeys := make([]string, 0, len(standardCapabilityGroups))
for _, group := range standardCapabilityGroups {
standardCapabilityKeys = append(standardCapabilityKeys, string(group.Key))
}
bindingSvc, _ := services.NewBindingService(services.BindingServiceOptions{
DB: s.db,
Repo: agentBindingRepo,
Identity: agentIdentitySvc,
Permissions: permService,
Prompts: templateCatalog,
StandardCapabilityGroups: standardCapabilityKeys,
Runs: codingRunSvc,
SCMCreds: &scmCredsAdapter{cr: scmCredResolver},
LLMRuntime: llmManager,
RunContext: agentBindingRepo,
Pools: repository.NewActionRepository(s.db),
Skills: agentSkillRepo,
Continuations: &itemPRContinuationResolver{db: s.db, cr: scmCredResolver},
APIURL: agentAPIURL,
})
// Wire remote-claim enrichment after construction to break the service cycle.
if codingRunSvc != nil && bindingSvc != nil {
codingRunSvc.SetBindingInputsResolver(bindingSvc)
}
agentBindingHandler := handlers.NewWorkspaceAgentBindingHandler(bindingSvc, agentIdentitySvc, permService, logger.NewAuditor(s.db))
agentBindingHandler.SetSkillsRepo(agentSkillRepo)
agentBindingHandler.SetPromptStore(promptStore)
agentBindingHandler.SetTemplateCatalog(templateCatalog)
agentBindingHandler.SetInitialPrompt(promptStore.Get(llm.PromptCodingAgentInitial))
// Remote-runner control plane (WI-141). Constructed unconditionally;
// the handler 503s when the registry/run service is unavailable (i.e.
// CodingAgent.Enabled is off).
runnerRegistry := services.NewRunnerRegistryService(repository.NewRunnerRepository(s.db), nil)
runnerControlHandler := handlers.NewRunnerControlHandler(runnerRegistry, repository.NewAgentRunRepository(s.db), codingRunSvc, repository.NewActionRepository(s.db), nil, baseURL)
agentBindingHandler.SetRunnerOnboarding(runnerRegistry, baseURL)
// Agent presence for workspace rosters (WI-272): ready binding → pool →
// heartbeat-fresh runner count, surfaced as online/offline/local.
agentPresenceService := services.NewAgentPresenceService(agentBindingRepo, repository.NewRunnerRepository(s.db))
workspaceUsers := services.NewWorkspaceUserResolver(s.db, permService)
userHandler.SetWorkspaceUserResolver(workspaceUsers)
agentBindingHandler.SetPresenceService(agentPresenceService)
workspaceBootstrapHandler := handlers.NewWorkspaceBootstrapHandler(workspaceHandler, userHandler, milestonePlanningService, permService, timeProjectHandler)
// Secretless access layer (WI-144): brokers a granted credential to a
// running job without it ever living on the runner host.
runnerBrokerHandler := handlers.NewRunnerBrokerHandler(tokenManager, repository.NewAgentRunRepository(s.db), credentialSvc, llmManager, &scmCredsAdapter{cr: scmCredResolver})
runnerBrokerHandler.SetUsageRepository(repository.NewLLMUsageRepository(s.db)) // meter LLM token/cost at the broker (WI-493)
if bindingSvc != nil {
// Registers the coding-agent assignee trigger inside the item
// create/update services, so every surface that sets an assignee
// (cookie handlers, REST v1, MCP/AI tools, automation actions,
// recurrence) starts runs — not just the cookie update handler.
services.SetItemAssigneeTrigger(bindingSvc)
}
assetHandler := handlers.NewAssetHandler(s.db, permService, cfg.AttachmentPath)
assetApplication := services.NewAssetApplicationService(s.db, permService, assetHandler.AssetService(), assetHandler.AssetPermissionService()).
WithLinks(itemLinkService).
WithImportStorage(cfg.AttachmentPath)
s.actionService.SetAssetNodeServices(assetHandler.AssetService(), assetHandler.AssetPermissionService())
if n, err := assetApplication.ReconcileInterruptedImports(); err != nil {
slog.Warn("failed to reconcile interrupted asset imports", slog.Any("error", err))
} else if n > 0 {
slog.Info("reconciled interrupted asset imports", slog.Int("count", n))
}
go s.runAssetImportRecovery(assetApplication)
itemLinkService.WithAssetPermissionChecker(assetHandler)
assetRepo := repository.NewAssetRepository(s.db)
assetReportHandler := handlers.NewAssetReportHandler(
repository.NewAssetReportRepository(s.db),
repository.NewChannelRepository(s.db),
repository.NewScreenRepository(s.db),
logger.NewAuditor(s.db),
channelService,
services.NewAssetPermissionService(assetRepo, permService),
)
assetActionHandler := handlers.NewAssetActionHandler(repository.NewAssetActionRepository(s.db), assetHandler, s.assetActionService, logger.NewAuditor(s.db))
jiraImportHandler := handlers.NewJiraImportHandler(s.db, cfg.Auth.SessionSecret, cfg.Jira.CapturePayloadsDir).
WithAuthorizationCacheInvalidator(authorizationCacheInvalidator)
// Share one credential manager so every in-process refresh/callback path
// uses the same per-channel lock and CAS config writer.
emailCredManager := email.NewCredentialManager(s.db, scmProviderHandler.GetEncryption())
emailProviderHandler := handlers.NewEmailProviderHandler(s.db, scmProviderHandler.GetEncryption(), baseURL, channelService)
emailProviderHandler.SetCredentialManager(emailCredManager)
s.emailScheduler = scheduler.NewEmailScheduler(s.db, emailCredManager, cfg.AttachmentPath)
s.emailScheduler.Start()
slog.Info("email scheduler started (IMAP polling)")
// Daily retention sweep for email_message_tracking. Per-channel
// retention comes from ChannelConfig.EmailTrackingRetentionDays; anchors
// referenced by in_reply_to are preserved past the cutoff.
s.emailTrackingRetention = scheduler.NewEmailTrackingRetentionSweeper(s.db)
s.emailTrackingRetention.Start()
integrationProviderHandler := handlers.NewIntegrationProviderHandler(repository.NewIntegrationProviderRepository(s.db), scmProviderHandler.GetEncryption(), logger.NewAuditor(s.db))
integrationOAuthHandler := handlers.NewIntegrationOAuthHandler(s.db, scmProviderHandler.GetEncryption(), baseURL)
integrationItemLinksHandler := handlers.NewIntegrationItemLinksHandler(s.db, scmProviderHandler.GetEncryption(), permService)
todoistSyncHandler := handlers.NewTodoistSyncHandler(s.db, scmProviderHandler.GetEncryption())
s.todoistSyncScheduler = scheduler.NewTodoistSyncScheduler(s.db, scmProviderHandler.GetEncryption())
s.todoistSyncScheduler.Start()
scmSyncService := scm.NewSyncService(s.db, scmProviderHandler.GetEncryption())
issueSyncService := scm.NewIssueSyncService(s.db, scmProviderHandler.GetEncryption())
issueSyncService.SetUserService(services.NewUserReadService(s.db))
go s.runIssueSync(issueSyncService)
go s.runMagicLinkCleanup(magicLinkService)
webhookSender := webhook.NewWebhookSender(s.db, scmProviderHandler.GetEncryption())
s.webhookSender = webhookSender
eventCoordinator := services.NewEventCoordinator(s.db)
eventCoordinator.SetNotificationService(s.notificationService)
eventCoordinator.SetActivityTracker(s.activityTracker)
eventCoordinator.SetWebhookDispatcher(webhookSender)
eventCoordinator.SetActionService(s.actionService)
eventCoordinator.SetMagicLinkService(magicLinkService)
s.actionService.SetEventCoordinator(eventCoordinator)
s.assetActionService.SetAssetPermissionChecker(assetHandler)
s.assetActionService.SetEventCoordinator(eventCoordinator)
slog.Info("event coordinator initialized")
// Wire up services
itemHandler.SetWebhookSender(webhookSender)
itemHandler.SetEventCoordinator(eventCoordinator)
s.actionService.SetItemUpdateApplicationService(itemHandler.ItemUpdateApplicationService())
s.assetActionService.SetItemCreationService(itemHandler.ItemCreationService())
// Item live-update stream (WI-484): register the in-memory SSE hub as the
// process-wide item-change publisher (WI-483 installed a no-op default), and
// give the item handler the hub so GET /items/{id}/events can subscribe.
sseHub := services.NewSSEHub()
services.SetItemChangePublisher(sseHub)
itemHandler.SetSSEHub(sseHub)
mentionService := services.NewMentionService(s.db, s.notificationService, permService)
mentionService.SetWorkspaceUserResolver(workspaceUsers)
itemHandler.SetMentionService(mentionService)
commentService := services.NewCommentService(s.db)
commentService.SetActivityTracker(s.activityTracker)
commentService.SetNotificationService(s.notificationService)
commentService.SetMentionService(mentionService)
commentService.SetWebhookSender(webhookSender)
commentService.SetIssueSync(issueSyncService)
if bindingSvc != nil {
// @mentioning a binding's acting user in a comment starts a run
// (WI-264), same machinery as the assignee-change trigger.
commentService.SetAgentMentionTrigger(bindingSvc)
}
s.actionService.SetCommentService(commentService)