-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathautomerge-sync-server.js
More file actions
executable file
·1012 lines (876 loc) · 32.2 KB
/
Copy pathautomerge-sync-server.js
File metadata and controls
executable file
·1012 lines (876 loc) · 32.2 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
#!/usr/bin/env node
/**
* Automerge Sync Server
*
* HTTP/WebSocket hub for the current Mission Control deployment.
* CLI, external harnesses, and UI clients talk to this process.
*/
import { WebSocketServer } from 'ws'
import { AutomergeStore } from './lib/automerge-store.js'
import express from 'express'
import crypto from 'crypto'
import { createServer } from 'node:http'
import { execSync } from 'node:child_process'
import { fileURLToPath } from 'url'
import { findGitRoot, getTraceByCommit } from './lib/agent-trace.js'
import { parseGithubRepo } from './lib/github-remote.js'
const DEFAULT_HTTP_PORT = 8004
const DEFAULT_WS_PORT = 8005
function defaultAllowedOrigins(httpPort) {
return [
'http://localhost:5174',
'http://127.0.0.1:5174',
`http://localhost:${httpPort}`,
`http://127.0.0.1:${httpPort}`
]
}
function parseAllowedOrigins(value, defaults) {
if (value instanceof Set) return new Set(value)
if (Array.isArray(value)) {
return new Set(value.map(origin => origin.trim()).filter(Boolean))
}
if (!value) return new Set(defaults)
return new Set(
String(value)
.split(',')
.map(origin => origin.trim())
.filter(Boolean)
)
}
function parsePort(value, name) {
const parsed = Number(value)
if (!Number.isInteger(parsed) || parsed < 0) {
throw new Error(`Invalid ${name}: ${value}`)
}
return parsed
}
function appendHeaderValue(existing, value) {
if (!existing) return value
const values = String(existing)
.split(',')
.map(item => item.trim())
.filter(Boolean)
if (values.includes(value)) return String(existing)
return `${existing}, ${value}`
}
function getBearerToken(authorizationHeader = '') {
if (!authorizationHeader.startsWith('Bearer ')) return null
return authorizationHeader.slice('Bearer '.length).trim()
}
function isNonEmptyString(value) {
return typeof value === 'string' && value.trim().length > 0
}
class AutomergeSyncServer {
constructor(options = {}) {
const env = options.env ?? process.env
this.logger = options.logger ?? console
const storeOptions = {}
if (options.storagePath !== undefined) storeOptions.storagePath = options.storagePath
if (options.urlFile !== undefined) storeOptions.urlFile = options.urlFile
if (options.usePersistedUrl !== undefined) storeOptions.usePersistedUrl = options.usePersistedUrl
if (options.mentionClaimTtlMs !== undefined) storeOptions.mentionClaimTtlMs = options.mentionClaimTtlMs
storeOptions.env = env
if (options.logger !== undefined) storeOptions.logger = this.logger
this.store = options.store || new AutomergeStore(storeOptions)
this.connectedClients = new Set()
this.app = express()
this.wss = null
this.httpServer = null
this.wsHttpServer = null
this.host = options.host ?? env.MC_BIND_HOST ?? '127.0.0.1'
this.httpPort = parsePort(options.httpPort ?? env.MC_HTTP_PORT ?? DEFAULT_HTTP_PORT, 'MC_HTTP_PORT')
this.wsPort = parsePort(options.wsPort ?? env.MC_WS_PORT ?? DEFAULT_WS_PORT, 'MC_WS_PORT')
this.apiToken = options.apiToken ?? env.MC_API_TOKEN ?? ''
this.allowInsecureLocal = options.allowInsecureLocal ?? env.MC_ALLOW_INSECURE_LOCAL === '1'
this.allowLegacyWsQueryToken = options.allowLegacyWsQueryToken ?? env.MC_ALLOW_LEGACY_WS_QUERY_TOKEN === '1'
this.wsTicketTtlMs = Number(
options.wsTicketTtlMs ?? env.MC_WS_TICKET_TTL_MS ?? 60000
)
this.wsTickets = new Map()
this.securityCounters = {
httpUnauthorized: 0,
httpOriginRejected: 0,
wsUnauthorized: 0,
wsOriginRejected: 0
}
this.allowedOrigins = parseAllowedOrigins(
options.allowedOrigins ?? env.MC_ALLOWED_ORIGINS ?? '',
defaultAllowedOrigins(this.httpPort)
)
if (!this.apiToken && !this.allowInsecureLocal) {
throw new Error(
'MC_API_TOKEN is required. To bypass for local-only testing, set MC_ALLOW_INSECURE_LOCAL=1.'
)
}
if (this.allowedOrigins.has('*')) {
throw new Error(
'MC_ALLOWED_ORIGINS must be an explicit comma-separated allowlist. Wildcard "*" is not supported.'
)
}
if (!Number.isInteger(this.wsTicketTtlMs) || this.wsTicketTtlMs <= 0) {
throw new Error(`Invalid MC_WS_TICKET_TTL_MS: ${env.MC_WS_TICKET_TTL_MS}`)
}
}
async start() {
this.logger.log?.('🚀 Starting Automerge Sync Server...')
// Initialize backend store
await this.store.init()
this.logger.log?.('✅ Backend AutomergeStore initialized')
// Setup Express for HTTP API
this.setupHTTPAPI()
// Setup WebSocket for real-time sync
this.setupWebSocketServer()
// Start HTTP server
this.httpServer = await new Promise((resolve, reject) => {
const server = this.app.listen(this.httpPort, this.host, () => resolve(server))
server.once('error', reject)
})
this.httpPort = this.getBoundPort(this.httpServer, this.httpPort)
this.wsHttpServer = await new Promise((resolve, reject) => {
const server = this.wsHttpServer.listen(this.wsPort, this.host, () => resolve(this.wsHttpServer))
server.once('error', reject)
})
this.wsPort = this.getBoundPort(this.wsHttpServer, this.wsPort)
this.logger.log?.(`📡 HTTP API listening on ${this.host}:${this.httpPort}`)
this.logger.log?.(`🌐 WebSocket sync on ${this.host}:${this.wsPort}`)
this.logger.log?.(`🔐 Auth mode: ${this.apiToken ? 'token required' : 'disabled (unsafe local mode)'}`)
this.logger.log?.(
`🌍 Allowed CORS origins: ${this.allowedOrigins.size === 0 ? '(none)' : [...this.allowedOrigins].join(', ')}`
)
// Register default agents if not exists
await this.initializeDefaultAgents()
}
getBoundPort(server, fallbackPort) {
const address = server?.address?.()
if (address && typeof address === 'object' && Number.isInteger(address.port)) {
return address.port
}
return fallbackPort
}
async stop() {
for (const client of this.connectedClients) {
try {
client.terminate()
} catch {
// Ignore client shutdown errors during teardown.
}
}
this.connectedClients.clear()
if (this.wss) {
await new Promise(resolve => this.wss.close(() => resolve()))
this.wss = null
}
await this.closeServer(this.wsHttpServer)
await this.closeServer(this.httpServer)
this.wsHttpServer = null
this.httpServer = null
await this.store.close()
}
async closeServer(server) {
if (!server?.listening) return
await new Promise((resolve, reject) => {
server.close(error => {
if (error) return reject(error)
resolve()
})
})
}
isAllowedOrigin(origin) {
if (!origin) return true
return this.allowedOrigins.has(origin)
}
applyCorsHeaders(res, origin) {
if (!origin) return
res.setHeader('Access-Control-Allow-Origin', origin)
res.setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type, X-MC-Token')
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PATCH,DELETE,OPTIONS')
res.setHeader('Access-Control-Max-Age', '600')
res.setHeader('Vary', appendHeaderValue(res.getHeader('Vary'), 'Origin'))
}
recordSecurityEvent(type, message) {
if (type in this.securityCounters) {
this.securityCounters[type] += 1
}
this.logger.warn?.(`[security] ${message}`)
}
getSecurityCounters() {
return { ...this.securityCounters }
}
originMiddleware(req, res, next) {
const origin = req.headers.origin
if (!this.isAllowedOrigin(origin)) {
this.recordSecurityEvent(
'httpOriginRejected',
`Rejected HTTP ${req.method} ${req.url} from origin ${origin}`
)
return res.status(403).json({ error: `Origin not allowed: ${origin}` })
}
this.applyCorsHeaders(res, origin)
if (req.method === 'OPTIONS') {
return res.status(204).end()
}
return next()
}
tokenFromRequest(req, options = {}) {
const { allowLegacyWsQueryToken = false } = options
const bearerToken = getBearerToken(req.headers?.authorization || '')
if (bearerToken) return bearerToken
const headerToken = req.headers?.['x-mc-token']
if (headerToken) return String(headerToken)
if (allowLegacyWsQueryToken && this.allowLegacyWsQueryToken) {
try {
const url = new URL(req.url || '', `http://${this.host}:${this.httpPort}`)
const queryToken = url.searchParams.get('token')
if (queryToken) return queryToken
} catch {
// Ignore malformed URL values and continue unauthenticated.
}
}
return null
}
wsTicketFromRequest(req) {
try {
const url = new URL(req.url || '', `http://${this.host}:${this.httpPort}`)
const ticket = url.searchParams.get('ticket')
if (ticket) return ticket
} catch {
// Ignore malformed URL values and continue unauthenticated.
}
return null
}
mintWsTicket() {
const ticket = crypto.randomBytes(32).toString('hex')
this.wsTickets.set(ticket, Date.now() + this.wsTicketTtlMs)
return ticket
}
consumeWsTicket(ticket) {
if (!ticket) return false
const expiresAt = this.wsTickets.get(ticket)
if (!expiresAt) return false
this.wsTickets.delete(ticket)
return expiresAt > Date.now()
}
cleanupExpiredWsTickets() {
const now = Date.now()
for (const [ticket, expiresAt] of this.wsTickets) {
if (expiresAt <= now) this.wsTickets.delete(ticket)
}
}
isAuthorizedRequest(req) {
if (!this.apiToken) return true
const token = this.tokenFromRequest(req)
return token === this.apiToken
}
isAuthorizedWebSocketRequest(req) {
if (!this.apiToken) return true
const token = this.tokenFromRequest(req, { allowLegacyWsQueryToken: true })
if (token === this.apiToken) return true
const ticket = this.wsTicketFromRequest(req)
return this.consumeWsTicket(ticket)
}
authMiddleware(req, res, next) {
if (this.isAuthorizedRequest(req)) {
return next()
}
this.recordSecurityEvent(
'httpUnauthorized',
`Rejected unauthorized HTTP ${req.method} ${req.url}`
)
return res.status(401).json({ error: 'Unauthorized' })
}
setupHTTPAPI() {
this.app.use((req, res, next) => this.originMiddleware(req, res, next))
this.app.use(express.json())
this.app.use((req, res, next) => this.authMiddleware(req, res, next))
// Get current document state
this.app.get('/automerge/doc', async (req, res) => {
try {
const doc = this.store.getDoc()
res.json({ success: true, doc })
} catch (error) {
res.status(500).json({ error: error.message })
}
})
// Get document URL for frontend connection
this.app.get('/automerge/url', async (req, res) => {
try {
const url = this.store.docHandle?.url
res.json({ success: true, url })
} catch (error) {
res.status(500).json({ error: error.message })
}
})
// Mark mention as delivered
this.app.post('/automerge/mentions/:id/deliver', async (req, res) => {
try {
const mentionId = req.params.id
const { claimToken } = req.body
if (!isNonEmptyString(claimToken)) {
return res.status(400).json({ error: 'claimToken is required' })
}
const result = await this.store.markMentionDelivered(mentionId, claimToken)
if (result.staleClaim) {
return res.status(409).json({ error: 'Claim token mismatch' })
}
if (result.delivered) {
this.broadcastDocumentUpdate()
}
res.json({ success: true, mentionId, delivered: result.delivered })
} catch (error) {
res.status(500).json({ error: error.message })
}
})
// Claim a mention before delivery so duplicate poll cycles do not re-send it.
this.app.post('/automerge/mentions/:id/claim', async (req, res) => {
try {
const mentionId = req.params.id
const result = await this.store.claimMentionDelivery(mentionId)
if (result.claimed) {
this.broadcastDocumentUpdate()
}
res.json({ success: true, mentionId, ...result })
} catch (error) {
res.status(500).json({ error: error.message })
}
})
// Atomically claim the next pending mention for one agent.
this.app.post('/automerge/mentions/claim-next', async (req, res) => {
try {
const { agent } = req.body ?? {}
if (!isNonEmptyString(agent)) {
return res.status(400).json({ error: 'agent is required' })
}
const result = await this.store.claimNextMentionDelivery(agent)
if (result.claimed) {
this.broadcastDocumentUpdate()
}
res.json({ success: true, ...result })
} catch (error) {
res.status(500).json({ error: error.message })
}
})
// Release a failed delivery attempt so the mention becomes pending again.
this.app.post('/automerge/mentions/:id/release', async (req, res) => {
try {
const mentionId = req.params.id
const { claimToken, error: releaseError } = req.body
if (!isNonEmptyString(claimToken)) {
return res.status(400).json({ error: 'claimToken is required' })
}
const result = await this.store.releaseMentionDelivery(mentionId, claimToken, releaseError)
if (result.staleClaim) {
return res.status(409).json({ error: 'Claim token mismatch' })
}
if (result.released) {
this.broadcastDocumentUpdate()
}
res.json({ success: true, mentionId, released: result.released })
} catch (error) {
res.status(500).json({ error: error.message })
}
})
// Get pending mentions
this.app.get('/automerge/mentions/pending', async (req, res) => {
try {
const agent = req.query.agent
const mentions = await this.store.getPendingMentions(agent)
res.json({ success: true, mentions })
} catch (error) {
res.status(500).json({ error: error.message })
}
})
// Add comment (from CLI or other sources)
this.app.post('/automerge/comment', async (req, res) => {
try {
const { taskId, text, agent } = req.body
const commentId = await this.store.addComment(taskId, text, agent)
// Broadcast update
this.broadcastDocumentUpdate()
res.json({ success: true, commentId })
} catch (error) {
res.status(500).json({ error: error.message })
}
})
this.app.post('/automerge/ws-ticket', async (req, res) => {
try {
this.cleanupExpiredWsTickets()
const ticket = this.mintWsTicket()
res.json({ success: true, ticket, expiresInMs: this.wsTicketTtlMs })
} catch (error) {
res.status(500).json({ error: error.message })
}
})
// Update comment (e.g., fix attribution)
this.app.patch('/automerge/comment/:commentId', async (req, res) => {
try {
const { commentId } = req.params
const updates = req.body
const doc = this.store.getDoc()
if (!doc.comments?.[commentId]) {
return res.status(404).json({ error: 'Comment not found' })
}
await this.store.docHandle.change(doc => {
const comment = doc.comments[commentId]
if (updates.agent) comment.agent = updates.agent
if (updates.content) comment.content = updates.content
})
this.broadcastDocumentUpdate()
res.json({ success: true, commentId })
} catch (error) {
res.status(500).json({ error: error.message })
}
})
// Delete comment
this.app.delete('/automerge/comment/:commentId', async (req, res) => {
try {
const { commentId } = req.params
const doc = this.store.getDoc()
if (!doc.comments?.[commentId]) {
return res.status(404).json({ error: 'Comment not found' })
}
// Find mentions that reference this comment
const mentionsToDelete = Object.entries(doc.mentions || {})
.filter(([_, mention]) => mention.comment_id === commentId)
.map(([mentionId]) => mentionId)
await this.store.docHandle.change(doc => {
// Delete the comment
delete doc.comments[commentId]
// Delete associated mentions
if (doc.mentions) {
mentionsToDelete.forEach(mentionId => {
delete doc.mentions[mentionId]
})
}
})
this.broadcastDocumentUpdate()
res.json({
success: true,
commentId,
mentionsDeleted: mentionsToDelete.length
})
} catch (error) {
res.status(500).json({ error: error.message })
}
})
// Get agent trace for a specific commit
this.app.get('/automerge/trace/:commitHash', async (req, res) => {
try {
const { commitHash } = req.params
const repoPath = req.query.repoPath || process.cwd()
const gitRoot = findGitRoot(repoPath)
if (!gitRoot) {
return res.status(404).json({ error: 'Not a git repository' })
}
const trace = getTraceByCommit(gitRoot, commitHash, { exact: true })
if (!trace) {
return res.status(404).json({ error: 'Trace not found for this commit' })
}
// Try to get GitHub remote URL
let githubUrl = null
try {
const remote = execSync('git config --get remote.origin.url', {
cwd: gitRoot,
encoding: 'utf-8'
}).trim()
const repo = parseGithubRepo(remote)
if (repo) {
githubUrl = `https://github.com/${repo}/commit/${commitHash}`
}
} catch {
// No remote or not GitHub, that's fine
}
res.json({
success: true,
trace,
githubUrl
})
} catch (error) {
res.status(500).json({ error: error.message })
}
})
// Get GitHub remote URL for current repo
this.app.get('/automerge/github-remote', async (req, res) => {
try {
const repoPath = req.query.repoPath || process.cwd()
const gitRoot = findGitRoot(repoPath)
if (!gitRoot) {
return res.status(404).json({ error: 'Not a git repository' })
}
try {
const remote = execSync('git config --get remote.origin.url', {
cwd: gitRoot,
encoding: 'utf-8'
}).trim()
const repo = parseGithubRepo(remote)
if (repo) {
const githubUrl = `https://github.com/${repo}`
res.json({ success: true, githubUrl, repo })
} else {
res.json({ success: true, githubUrl: null })
}
} catch {
res.json({ success: true, githubUrl: null })
}
} catch (error) {
res.status(500).json({ error: error.message })
}
})
// Update last-seen timestamp for a task (read/unread helper - global lastSeen map in this prototype)
this.app.post('/automerge/last-seen', async (req, res) => {
try {
const { taskId, timestamp } = req.body
if (!taskId) {
return res.status(400).json({ error: 'taskId is required' })
}
const ts = timestamp || new Date().toISOString()
await this.store.docHandle.change(doc => {
if (!doc.lastSeen) doc.lastSeen = {}
doc.lastSeen[taskId] = ts
})
this.broadcastDocumentUpdate()
res.json({ success: true, taskId, timestamp: ts })
} catch (error) {
res.status(500).json({ error: error.message })
}
})
// Register agent
this.app.post('/automerge/agent', async (req, res) => {
try {
const { name, role } = req.body ?? {}
if (!isNonEmptyString(name)) {
return res.status(400).json({ error: 'name is required' })
}
await this.store.registerAgent(name.trim(), role || 'Agent')
this.broadcastDocumentUpdate()
res.json({ success: true, name: name.trim() })
} catch (error) {
res.status(500).json({ error: error.message })
}
})
// Create task (from CLI or other sources)
this.app.post('/automerge/task', async (req, res) => {
try {
const { title, description, priority, assignee, tags, status, agent } = req.body
if (!title) {
return res.status(400).json({ error: 'Title is required' })
}
const taskId = 'task-' + Math.random().toString(36).substr(2, 9)
await this.store.docHandle.change(doc => {
if (!doc.tasks) doc.tasks = {}
doc.tasks[taskId] = {
id: taskId,
title,
description: description || '',
priority: priority || 'p2',
assignee: assignee || null,
tags: tags || [],
status: status || 'todo',
type: 'task',
order: Date.now(),
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
}
if (!doc.activity) doc.activity = []
doc.activity.push({
id: Math.random().toString(16).slice(2),
type: 'task_created',
agent: agent || 'api',
taskId,
timestamp: new Date().toISOString()
})
})
// Broadcast update
this.broadcastDocumentUpdate()
res.json({ success: true, taskId })
} catch (error) {
res.status(500).json({ error: error.message })
}
})
// Update task (from CLI or other sources)
this.app.patch('/automerge/task/:taskId', async (req, res) => {
try {
const { taskId } = req.params
const { status, assignee, title, description, priority, agent } = req.body
const updates = {}
if (status !== undefined) updates.status = status
if (assignee !== undefined) updates.assignee = assignee || null
if (title !== undefined) updates.title = title
if (description !== undefined) updates.description = description
if (priority !== undefined) updates.priority = priority
const result = await this.store.updateTask(taskId, updates, agent || 'api')
if (!result.success) {
if (result.error === 'Task not found') {
return res.status(404).json({ error: `Task ${taskId} not found` })
}
return res.status(500).json({ error: result.error || 'Task update failed' })
}
if (result.changes.length > 0) {
this.broadcastDocumentUpdate()
}
res.json({ success: true, taskId, changes: result.changes })
} catch (error) {
res.status(500).json({ error: error.message })
}
})
// ─── Patchwork: Task History ───
this.app.get('/automerge/task/:taskId/history', async (req, res) => {
try {
const { taskId } = req.params
const history = await this.store.getTaskHistory(taskId)
res.json({ history })
} catch (error) {
res.status(500).json({ error: error.message })
}
})
// ─── Patchwork: Link Commit ───
this.app.post('/automerge/task/:taskId/commit', async (req, res) => {
try {
const { taskId } = req.params
const { commit, agent } = req.body
const doc = this.store.getDoc()
if (!commit?.hash || !commit?.message) {
return res.status(400).json({ error: 'commit.hash and commit.message are required' })
}
if (!doc.tasks?.[taskId]) {
return res.status(404).json({ error: `Task ${taskId} not found` })
}
await this.store.recordCommit(taskId, commit, agent || 'api')
this.broadcastDocumentUpdate()
res.json({ success: true, taskId, commitHash: commit.hash })
} catch (error) {
res.status(500).json({ error: error.message })
}
})
// ─── Patchwork: Create Branch ───
this.app.post('/automerge/task/:taskId/branch', async (req, res) => {
try {
const { taskId } = req.params
const { branchName, agent } = req.body
if (!branchName) {
return res.status(400).json({ error: 'branchName required' })
}
const branchId = await this.store.createBranch(taskId, branchName, agent || 'api')
if (!branchId) {
return res.status(404).json({ error: `Task ${taskId} not found` })
}
this.broadcastDocumentUpdate()
res.json({ success: true, branchId, parentId: taskId, branchName })
} catch (error) {
res.status(500).json({ error: error.message })
}
})
// ─── Patchwork: List Branches ───
this.app.get('/automerge/task/:taskId/branches', async (req, res) => {
try {
const { taskId } = req.params
const branches = await this.store.getBranches(taskId)
res.json({ branches })
} catch (error) {
res.status(500).json({ error: error.message })
}
})
// ─── Patchwork: Merge Branch ───
this.app.post('/automerge/branch/:branchId/merge', async (req, res) => {
try {
const { branchId } = req.params
const { agent } = req.body
const result = await this.store.mergeBranch(branchId, agent || 'api')
if (!result.success) {
return res.status(400).json({ error: result.error })
}
this.broadcastDocumentUpdate()
res.json(result)
} catch (error) {
res.status(500).json({ error: error.message })
}
})
this.logger.log?.('🌐 HTTP API routes configured')
}
setupWebSocketServer() {
this.wss = new WebSocketServer({ noServer: true })
this.wsHttpServer = createServer((req, res) => {
const origin = req.headers.origin
if (!this.isAllowedOrigin(origin)) {
this.recordSecurityEvent(
'wsOriginRejected',
`Rejected WS HTTP request ${req.method} ${req.url} from origin ${origin}`
)
res.statusCode = 403
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({ error: `Origin not allowed: ${origin}` }))
return
}
this.applyCorsHeaders(res, origin)
res.statusCode = 426
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({ error: 'Expected WebSocket upgrade' }))
})
this.wsHttpServer.on('upgrade', (req, socket, head) => {
socket.on('error', () => {})
this.cleanupExpiredWsTickets()
const origin = req.headers.origin
if (!this.isAllowedOrigin(origin)) {
this.recordSecurityEvent(
'wsOriginRejected',
`Rejected WS upgrade ${req.url} from origin ${origin}`
)
this.rejectWebSocketUpgrade(socket, 403, 'Forbidden', { error: `Origin not allowed: ${origin}` })
return
}
if (!this.isAuthorizedWebSocketRequest(req)) {
this.recordSecurityEvent(
'wsUnauthorized',
`Rejected unauthorized WS upgrade ${req.url}`
)
this.rejectWebSocketUpgrade(socket, 401, 'Unauthorized', { error: 'Unauthorized' })
return
}
this.wss.handleUpgrade(req, socket, head, ws => {
this.wss.emit('connection', ws, req)
})
})
this.wss.on('connection', (ws, req) => {
this.logger.log?.('🔌 Frontend client connected')
this.connectedClients.add(ws)
// Send current document state immediately
const doc = this.store.getDoc()
ws.send(JSON.stringify({
type: 'document-state',
doc: doc
}))
ws.on('message', async (message) => {
try {
const data = JSON.parse(message.toString())
await this.handleClientMessage(ws, data)
} catch (error) {
this.logger.error?.('❌ WebSocket message error:', error)
ws.send(JSON.stringify({
type: 'error',
error: error.message
}))
}
})
ws.on('close', () => {
this.logger.log?.('🔌 Frontend client disconnected')
this.connectedClients.delete(ws)
})
})
this.logger.log?.('🔄 WebSocket server configured')
}
rejectWebSocketUpgrade(socket, statusCode, statusText, payload) {
const body = JSON.stringify(payload)
socket.write(
`HTTP/1.1 ${statusCode} ${statusText}\r\n` +
'Connection: close\r\n' +
'Content-Type: application/json\r\n' +
`Content-Length: ${Buffer.byteLength(body)}\r\n` +
'\r\n' +
body
)
socket.destroy()
}
async handleClientMessage(ws, data) {
switch (data.type) {
case 'document-change':
this.logger.log?.('🔄 Applying frontend change:', data.change?.type)
if (!data.change) break
// Handle task update
if (data.change.type === 'task-update') {
await this.store.docHandle.change(doc => {
const { taskId, updates } = data.change
if (doc.tasks[taskId]) {
Object.assign(doc.tasks[taskId], updates)
doc.tasks[taskId].updated_at = new Date().toISOString()
if (!doc.activity) doc.activity = []
doc.activity.push({
id: Math.random().toString(16).slice(2),
type: 'task_updated',
agent: data.agent || 'ui',
taskId,
changes: updates,
timestamp: new Date().toISOString()
})
}
})
this.broadcastDocumentUpdate(ws)
}
// Handle task create
if (data.change.type === 'task-create') {
await this.store.docHandle.change(doc => {
const { task } = data.change
if (!doc.tasks) doc.tasks = {}
doc.tasks[task.id] = {
...task,
created_at: task.created_at || new Date().toISOString(),
updated_at: new Date().toISOString()
}
if (!doc.activity) doc.activity = []
doc.activity.push({
id: Math.random().toString(16).slice(2),
type: 'task_created',
agent: data.agent || 'ui',
taskId: task.id,
timestamp: new Date().toISOString()
})
})
this.logger.log?.('✅ Task created:', data.change.task.id)
this.broadcastDocumentUpdate(ws)
}
// Handle comment add
if (data.change.type === 'comment-add') {
const { taskId, comment } = data.change
await this.store.addComment(taskId, comment.text, comment.agent)
this.logger.log?.('✅ Comment added to task:', taskId)
// Don't exclude sender - UI doesn't do optimistic updates for comments
this.broadcastDocumentUpdate(null)
}
break
case 'ping':
ws.send(JSON.stringify({ type: 'pong' }))
break
default:
this.logger.log?.('⚠️ Unknown message type:', data.type)
}
}
broadcastDocumentUpdate(excludeClient = null) {
const doc = this.store.getDoc()
const message = JSON.stringify({
type: 'document-update',
doc: doc,
timestamp: new Date().toISOString()
})
this.connectedClients.forEach(client => {
if (client !== excludeClient && client.readyState === client.OPEN) {
client.send(message)
}
})
}
async initializeDefaultAgents() {
try {
// Check if agents already exist
const existingAgents = await this.store.getAgents()
if (existingAgents.length > 0) {
this.logger.log?.(`✅ ${existingAgents.length} agents already registered`)
return
}
// Register default agents
await this.store.registerAgent('gary', 'Lead')
await this.store.registerAgent('friday', 'Developer')
await this.store.registerAgent('writer', 'Content Writer')
this.logger.log?.('✅ Default agents registered')
} catch (error) {
this.logger.error?.('❌ Failed to initialize agents:', error)
}
}
}