Nyk commited on
Commit
8dc7515
Β·
1 Parent(s): 134bcfd

feat: add GitHub Issues sync (Phase 1, Issue #58)

Browse files

Import GitHub issues as Mission Control tasks with duplicate detection,
priority mapping from labels, and bidirectional actions (comment/close).

- Migration 017: github_syncs table for sync history tracking
- GitHub API client (src/lib/github.ts) with fetch, comment, close ops
- POST/GET /api/github route with sync, comment, close, status actions
- GitHubSyncPanel UI: import form, issue preview, sync history, linked tasks
- Nav rail + page router wiring
- 6 E2E tests (all passing)
- Validation schema + github.synced event type

src/app/api/github/route.ts ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from 'next/server'
2
+ import { getDatabase, Task, db_helpers } from '@/lib/db'
3
+ import { eventBus } from '@/lib/event-bus'
4
+ import { requireRole } from '@/lib/auth'
5
+ import { mutationLimiter } from '@/lib/rate-limit'
6
+ import { logger } from '@/lib/logger'
7
+ import { validateBody, githubSyncSchema } from '@/lib/validation'
8
+ import {
9
+ getGitHubToken,
10
+ fetchIssues,
11
+ fetchIssue,
12
+ createIssueComment,
13
+ updateIssueState,
14
+ type GitHubIssue,
15
+ } from '@/lib/github'
16
+
17
+ /**
18
+ * GET /api/github?action=issues&repo=owner/repo&state=open&labels=bug
19
+ * Fetch issues from GitHub for preview before import.
20
+ */
21
+ export async function GET(request: NextRequest) {
22
+ const auth = requireRole(request, 'operator')
23
+ if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
24
+
25
+ try {
26
+ const { searchParams } = new URL(request.url)
27
+ const action = searchParams.get('action')
28
+
29
+ if (action !== 'issues') {
30
+ return NextResponse.json({ error: 'Unknown action. Use ?action=issues' }, { status: 400 })
31
+ }
32
+
33
+ const repo = searchParams.get('repo') || process.env.GITHUB_DEFAULT_REPO
34
+ if (!repo || !/^[^/]+\/[^/]+$/.test(repo)) {
35
+ return NextResponse.json({ error: 'repo query parameter required (owner/repo format)' }, { status: 400 })
36
+ }
37
+
38
+ const token = getGitHubToken()
39
+ if (!token) {
40
+ return NextResponse.json({ error: 'GITHUB_TOKEN not configured' }, { status: 400 })
41
+ }
42
+
43
+ const state = (searchParams.get('state') as 'open' | 'closed' | 'all') || 'open'
44
+ const labels = searchParams.get('labels') || undefined
45
+
46
+ const issues = await fetchIssues(repo, { state, labels, per_page: 50 })
47
+
48
+ return NextResponse.json({ issues, total: issues.length, repo })
49
+ } catch (error: any) {
50
+ logger.error({ err: error }, 'GET /api/github error')
51
+ return NextResponse.json({ error: error.message || 'Failed to fetch issues' }, { status: 500 })
52
+ }
53
+ }
54
+
55
+ /**
56
+ * POST /api/github β€” Action dispatcher for sync, comment, close, status.
57
+ */
58
+ export async function POST(request: NextRequest) {
59
+ const auth = requireRole(request, 'operator')
60
+ if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
61
+
62
+ const rateCheck = mutationLimiter(request)
63
+ if (rateCheck) return rateCheck
64
+
65
+ const validated = await validateBody(request, githubSyncSchema)
66
+ if ('error' in validated) return validated.error
67
+
68
+ const body = validated.data
69
+ const { action } = body
70
+
71
+ try {
72
+ switch (action) {
73
+ case 'sync':
74
+ return await handleSync(body, auth.user.username)
75
+ case 'comment':
76
+ return await handleComment(body, auth.user.username)
77
+ case 'close':
78
+ return await handleClose(body, auth.user.username)
79
+ case 'status':
80
+ return handleStatus()
81
+ default:
82
+ return NextResponse.json({ error: 'Unknown action' }, { status: 400 })
83
+ }
84
+ } catch (error: any) {
85
+ logger.error({ err: error }, `POST /api/github action=${action} error`)
86
+ return NextResponse.json({ error: error.message || 'GitHub action failed' }, { status: 500 })
87
+ }
88
+ }
89
+
90
+ // ── Sync: import GitHub issues as MC tasks ──────────────────────
91
+
92
+ async function handleSync(
93
+ body: { repo?: string; labels?: string; state?: 'open' | 'closed' | 'all'; assignAgent?: string },
94
+ actor: string
95
+ ) {
96
+ const repo = body.repo || process.env.GITHUB_DEFAULT_REPO
97
+ if (!repo) {
98
+ return NextResponse.json({ error: 'repo is required' }, { status: 400 })
99
+ }
100
+
101
+ const token = getGitHubToken()
102
+ if (!token) {
103
+ return NextResponse.json({ error: 'GITHUB_TOKEN not configured' }, { status: 400 })
104
+ }
105
+
106
+ const issues = await fetchIssues(repo, {
107
+ state: body.state || 'open',
108
+ labels: body.labels,
109
+ per_page: 100,
110
+ })
111
+
112
+ const db = getDatabase()
113
+ const now = Math.floor(Date.now() / 1000)
114
+ let imported = 0
115
+ let skipped = 0
116
+ let errors = 0
117
+ const createdTasks: any[] = []
118
+
119
+ for (const issue of issues) {
120
+ try {
121
+ // Check for duplicate: existing task with same github_repo + github_issue_number
122
+ const existing = db.prepare(`
123
+ SELECT id FROM tasks
124
+ WHERE json_extract(metadata, '$.github_repo') = ?
125
+ AND json_extract(metadata, '$.github_issue_number') = ?
126
+ `).get(repo, issue.number) as { id: number } | undefined
127
+
128
+ if (existing) {
129
+ skipped++
130
+ continue
131
+ }
132
+
133
+ // Map priority from labels
134
+ const priority = mapPriority(issue.labels.map(l => l.name))
135
+ const tags = issue.labels.map(l => l.name)
136
+ const status = issue.state === 'closed' ? 'done' : 'inbox'
137
+
138
+ const metadata = {
139
+ github_repo: repo,
140
+ github_issue_number: issue.number,
141
+ github_issue_url: issue.html_url,
142
+ github_synced_at: new Date().toISOString(),
143
+ github_state: issue.state,
144
+ }
145
+
146
+ const stmt = db.prepare(`
147
+ INSERT INTO tasks (
148
+ title, description, status, priority, assigned_to, created_by,
149
+ created_at, updated_at, tags, metadata
150
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
151
+ `)
152
+
153
+ const dbResult = stmt.run(
154
+ issue.title,
155
+ issue.body || '',
156
+ status,
157
+ priority,
158
+ body.assignAgent || null,
159
+ actor,
160
+ now,
161
+ now,
162
+ JSON.stringify(tags),
163
+ JSON.stringify(metadata)
164
+ )
165
+
166
+ const taskId = dbResult.lastInsertRowid as number
167
+
168
+ db_helpers.logActivity(
169
+ 'task_created',
170
+ 'task',
171
+ taskId,
172
+ actor,
173
+ `Imported from GitHub: ${repo}#${issue.number}`,
174
+ { github_issue: issue.number, github_repo: repo }
175
+ )
176
+
177
+ const createdTask = db.prepare('SELECT * FROM tasks WHERE id = ?').get(taskId) as Task
178
+ const parsedTask = {
179
+ ...createdTask,
180
+ tags: JSON.parse(createdTask.tags || '[]'),
181
+ metadata: JSON.parse(createdTask.metadata || '{}'),
182
+ }
183
+
184
+ eventBus.broadcast('task.created', parsedTask)
185
+ createdTasks.push(parsedTask)
186
+ imported++
187
+ } catch (err: any) {
188
+ logger.error({ err, issue: issue.number }, 'Failed to import GitHub issue')
189
+ errors++
190
+ }
191
+ }
192
+
193
+ // Log sync to github_syncs table
194
+ db.prepare(`
195
+ INSERT INTO github_syncs (repo, last_synced_at, issue_count, sync_direction, status, error)
196
+ VALUES (?, ?, ?, 'inbound', ?, ?)
197
+ `).run(
198
+ repo,
199
+ now,
200
+ imported,
201
+ errors > 0 ? 'partial' : 'success',
202
+ errors > 0 ? `${errors} issues failed to import` : null
203
+ )
204
+
205
+ eventBus.broadcast('github.synced', {
206
+ repo,
207
+ imported,
208
+ skipped,
209
+ errors,
210
+ timestamp: now,
211
+ })
212
+
213
+ return NextResponse.json({
214
+ imported,
215
+ skipped,
216
+ errors,
217
+ tasks: createdTasks,
218
+ })
219
+ }
220
+
221
+ // ── Comment: post a comment on a GitHub issue ───────────────────
222
+
223
+ async function handleComment(
224
+ body: { repo?: string; issueNumber?: number; body?: string },
225
+ actor: string
226
+ ) {
227
+ if (!body.repo || !body.issueNumber || !body.body) {
228
+ return NextResponse.json(
229
+ { error: 'repo, issueNumber, and body are required' },
230
+ { status: 400 }
231
+ )
232
+ }
233
+
234
+ await createIssueComment(body.repo, body.issueNumber, body.body)
235
+
236
+ db_helpers.logActivity(
237
+ 'github_comment',
238
+ 'task',
239
+ 0,
240
+ actor,
241
+ `Commented on ${body.repo}#${body.issueNumber}`,
242
+ { github_repo: body.repo, github_issue: body.issueNumber }
243
+ )
244
+
245
+ return NextResponse.json({ ok: true })
246
+ }
247
+
248
+ // ── Close: close a GitHub issue ─────────────────────────────────
249
+
250
+ async function handleClose(
251
+ body: { repo?: string; issueNumber?: number; comment?: string },
252
+ actor: string
253
+ ) {
254
+ if (!body.repo || !body.issueNumber) {
255
+ return NextResponse.json(
256
+ { error: 'repo and issueNumber are required' },
257
+ { status: 400 }
258
+ )
259
+ }
260
+
261
+ // Optionally post a closing comment first
262
+ if (body.comment) {
263
+ await createIssueComment(body.repo, body.issueNumber, body.comment)
264
+ }
265
+
266
+ await updateIssueState(body.repo, body.issueNumber, 'closed')
267
+
268
+ // Update local task metadata if we have a linked task
269
+ const db = getDatabase()
270
+ const now = Math.floor(Date.now() / 1000)
271
+ db.prepare(`
272
+ UPDATE tasks
273
+ SET metadata = json_set(metadata, '$.github_state', 'closed'),
274
+ updated_at = ?
275
+ WHERE json_extract(metadata, '$.github_repo') = ?
276
+ AND json_extract(metadata, '$.github_issue_number') = ?
277
+ `).run(now, body.repo, body.issueNumber)
278
+
279
+ db_helpers.logActivity(
280
+ 'github_close',
281
+ 'task',
282
+ 0,
283
+ actor,
284
+ `Closed GitHub issue ${body.repo}#${body.issueNumber}`,
285
+ { github_repo: body.repo, github_issue: body.issueNumber }
286
+ )
287
+
288
+ return NextResponse.json({ ok: true })
289
+ }
290
+
291
+ // ── Status: return recent sync history ──────────────────────────
292
+
293
+ function handleStatus() {
294
+ const db = getDatabase()
295
+ const syncs = db.prepare(`
296
+ SELECT * FROM github_syncs
297
+ ORDER BY created_at DESC
298
+ LIMIT 20
299
+ `).all()
300
+
301
+ return NextResponse.json({ syncs })
302
+ }
303
+
304
+ // ── Priority mapping helper ─────────────────────────────────────
305
+
306
+ function mapPriority(labels: string[]): 'critical' | 'high' | 'medium' | 'low' {
307
+ for (const label of labels) {
308
+ const lower = label.toLowerCase()
309
+ if (lower === 'priority:critical' || lower === 'critical') return 'critical'
310
+ if (lower === 'priority:high' || lower === 'high') return 'high'
311
+ if (lower === 'priority:low' || lower === 'low') return 'low'
312
+ if (lower === 'priority:medium') return 'medium'
313
+ }
314
+ return 'medium'
315
+ }
src/app/page.tsx CHANGED
@@ -29,6 +29,7 @@ import { IntegrationsPanel } from '@/components/panels/integrations-panel'
29
  import { AlertRulesPanel } from '@/components/panels/alert-rules-panel'
30
  import { MultiGatewayPanel } from '@/components/panels/multi-gateway-panel'
31
  import { SuperAdminPanel } from '@/components/panels/super-admin-panel'
 
32
  import { ChatPanel } from '@/components/chat/chat-panel'
33
  import { ErrorBoundary } from '@/components/ErrorBoundary'
34
  import { useWebSocket } from '@/lib/websocket'
@@ -184,6 +185,8 @@ function ContentRouter({ tab }: { tab: string }) {
184
  return <IntegrationsPanel />
185
  case 'settings':
186
  return <SettingsPanel />
 
 
187
  case 'super-admin':
188
  return <SuperAdminPanel />
189
  default:
 
29
  import { AlertRulesPanel } from '@/components/panels/alert-rules-panel'
30
  import { MultiGatewayPanel } from '@/components/panels/multi-gateway-panel'
31
  import { SuperAdminPanel } from '@/components/panels/super-admin-panel'
32
+ import { GitHubSyncPanel } from '@/components/panels/github-sync-panel'
33
  import { ChatPanel } from '@/components/chat/chat-panel'
34
  import { ErrorBoundary } from '@/components/ErrorBoundary'
35
  import { useWebSocket } from '@/lib/websocket'
 
185
  return <IntegrationsPanel />
186
  case 'settings':
187
  return <SettingsPanel />
188
+ case 'github':
189
+ return <GitHubSyncPanel />
190
  case 'super-admin':
191
  return <SuperAdminPanel />
192
  default:
src/components/layout/nav-rail.tsx CHANGED
@@ -45,6 +45,7 @@ const navGroups: NavGroup[] = [
45
  { id: 'spawn', label: 'Spawn', icon: <SpawnIcon />, priority: false },
46
  { id: 'webhooks', label: 'Webhooks', icon: <WebhookIcon />, priority: false },
47
  { id: 'alerts', label: 'Alerts', icon: <AlertIcon />, priority: false },
 
48
  ],
49
  },
50
  {
@@ -590,6 +591,14 @@ function AgentCostsIcon() {
590
  )
591
  }
592
 
 
 
 
 
 
 
 
 
593
  function SettingsIcon() {
594
  return (
595
  <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
 
45
  { id: 'spawn', label: 'Spawn', icon: <SpawnIcon />, priority: false },
46
  { id: 'webhooks', label: 'Webhooks', icon: <WebhookIcon />, priority: false },
47
  { id: 'alerts', label: 'Alerts', icon: <AlertIcon />, priority: false },
48
+ { id: 'github', label: 'GitHub', icon: <GitHubIcon />, priority: false },
49
  ],
50
  },
51
  {
 
591
  )
592
  }
593
 
594
+ function GitHubIcon() {
595
+ return (
596
+ <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
597
+ <path d="M6 12.5c-3 1-3-1.5-4-2m8 4v-2.2a2.1 2.1 0 00-.6-1.6c2-.2 4.1-1 4.1-4.5a3.5 3.5 0 00-1-2.4 3.2 3.2 0 00-.1-2.4s-.8-.2-2.5 1a8.7 8.7 0 00-4.6 0C3.7 3.4 2.9 3.6 2.9 3.6a3.2 3.2 0 00-.1 2.4 3.5 3.5 0 00-1 2.4c0 3.5 2.1 4.3 4.1 4.5a2.1 2.1 0 00-.6 1.6v2.2" />
598
+ </svg>
599
+ )
600
+ }
601
+
602
  function SettingsIcon() {
603
  return (
604
  <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
src/components/panels/github-sync-panel.tsx ADDED
@@ -0,0 +1,534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use client'
2
+
3
+ import { useState, useEffect, useCallback } from 'react'
4
+
5
+ interface GitHubLabel {
6
+ name: string
7
+ color?: string
8
+ }
9
+
10
+ interface GitHubIssue {
11
+ number: number
12
+ title: string
13
+ body: string | null
14
+ state: 'open' | 'closed'
15
+ labels: GitHubLabel[]
16
+ assignee: { login: string } | null
17
+ html_url: string
18
+ created_at: string
19
+ updated_at: string
20
+ }
21
+
22
+ interface SyncRecord {
23
+ id: number
24
+ repo: string
25
+ last_synced_at: number
26
+ issue_count: number
27
+ sync_direction: string
28
+ status: string
29
+ error: string | null
30
+ created_at: number
31
+ }
32
+
33
+ interface LinkedTask {
34
+ id: number
35
+ title: string
36
+ status: string
37
+ priority: string
38
+ metadata: {
39
+ github_repo?: string
40
+ github_issue_number?: number
41
+ github_issue_url?: string
42
+ github_synced_at?: string
43
+ github_state?: string
44
+ }
45
+ }
46
+
47
+ export function GitHubSyncPanel() {
48
+ // Connection status
49
+ const [tokenStatus, setTokenStatus] = useState<{ connected: boolean; user?: string } | null>(null)
50
+
51
+ // Import form
52
+ const [repo, setRepo] = useState('')
53
+ const [labelFilter, setLabelFilter] = useState('')
54
+ const [stateFilter, setStateFilter] = useState<'open' | 'closed' | 'all'>('open')
55
+ const [assignAgent, setAssignAgent] = useState('')
56
+ const [agents, setAgents] = useState<{ name: string }[]>([])
57
+
58
+ // Preview
59
+ const [previewIssues, setPreviewIssues] = useState<GitHubIssue[]>([])
60
+ const [previewing, setPreviewing] = useState(false)
61
+
62
+ // Sync
63
+ const [syncing, setSyncing] = useState(false)
64
+ const [syncResult, setSyncResult] = useState<{ imported: number; skipped: number; errors: number } | null>(null)
65
+
66
+ // Sync history
67
+ const [syncHistory, setSyncHistory] = useState<SyncRecord[]>([])
68
+
69
+ // Linked tasks
70
+ const [linkedTasks, setLinkedTasks] = useState<LinkedTask[]>([])
71
+
72
+ // Feedback
73
+ const [feedback, setFeedback] = useState<{ ok: boolean; text: string } | null>(null)
74
+ const [loading, setLoading] = useState(true)
75
+
76
+ const showFeedback = (ok: boolean, text: string) => {
77
+ setFeedback({ ok, text })
78
+ setTimeout(() => setFeedback(null), 4000)
79
+ }
80
+
81
+ // Check GitHub token status
82
+ const checkToken = useCallback(async () => {
83
+ try {
84
+ const res = await fetch('/api/integrations', {
85
+ method: 'POST',
86
+ headers: { 'Content-Type': 'application/json' },
87
+ body: JSON.stringify({ action: 'test', integrationId: 'github' }),
88
+ })
89
+ const data = await res.json()
90
+ setTokenStatus({
91
+ connected: data.ok === true,
92
+ user: data.detail?.replace('User: ', ''),
93
+ })
94
+ } catch {
95
+ setTokenStatus({ connected: false })
96
+ }
97
+ }, [])
98
+
99
+ // Fetch sync history
100
+ const fetchSyncHistory = useCallback(async () => {
101
+ try {
102
+ const res = await fetch('/api/github', {
103
+ method: 'POST',
104
+ headers: { 'Content-Type': 'application/json' },
105
+ body: JSON.stringify({ action: 'status' }),
106
+ })
107
+ if (res.ok) {
108
+ const data = await res.json()
109
+ setSyncHistory(data.syncs || [])
110
+ }
111
+ } catch { /* ignore */ }
112
+ }, [])
113
+
114
+ // Fetch linked tasks
115
+ const fetchLinkedTasks = useCallback(async () => {
116
+ try {
117
+ const res = await fetch('/api/tasks?limit=200')
118
+ if (res.ok) {
119
+ const data = await res.json()
120
+ const linked = (data.tasks || []).filter(
121
+ (t: LinkedTask) => t.metadata?.github_repo
122
+ )
123
+ setLinkedTasks(linked)
124
+ }
125
+ } catch { /* ignore */ }
126
+ }, [])
127
+
128
+ // Fetch agents for assign dropdown
129
+ const fetchAgents = useCallback(async () => {
130
+ try {
131
+ const res = await fetch('/api/agents')
132
+ if (res.ok) {
133
+ const data = await res.json()
134
+ setAgents((data.agents || []).map((a: any) => ({ name: a.name })))
135
+ }
136
+ } catch { /* ignore */ }
137
+ }, [])
138
+
139
+ useEffect(() => {
140
+ Promise.all([checkToken(), fetchSyncHistory(), fetchLinkedTasks(), fetchAgents()])
141
+ .finally(() => setLoading(false))
142
+ }, [checkToken, fetchSyncHistory, fetchLinkedTasks, fetchAgents])
143
+
144
+ // Preview issues from GitHub
145
+ const handlePreview = async () => {
146
+ if (!repo) {
147
+ showFeedback(false, 'Enter a repository (owner/repo)')
148
+ return
149
+ }
150
+ setPreviewing(true)
151
+ setPreviewIssues([])
152
+ setSyncResult(null)
153
+ try {
154
+ const params = new URLSearchParams({ action: 'issues', repo, state: stateFilter })
155
+ if (labelFilter) params.set('labels', labelFilter)
156
+ const res = await fetch(`/api/github?${params}`)
157
+ const data = await res.json()
158
+ if (res.ok) {
159
+ setPreviewIssues(data.issues || [])
160
+ if (data.issues?.length === 0) showFeedback(true, 'No issues found matching filters')
161
+ } else {
162
+ showFeedback(false, data.error || 'Failed to fetch issues')
163
+ }
164
+ } catch {
165
+ showFeedback(false, 'Network error')
166
+ } finally {
167
+ setPreviewing(false)
168
+ }
169
+ }
170
+
171
+ // Import issues as tasks
172
+ const handleImport = async () => {
173
+ if (!repo) return
174
+ setSyncing(true)
175
+ setSyncResult(null)
176
+ try {
177
+ const res = await fetch('/api/github', {
178
+ method: 'POST',
179
+ headers: { 'Content-Type': 'application/json' },
180
+ body: JSON.stringify({
181
+ action: 'sync',
182
+ repo,
183
+ labels: labelFilter || undefined,
184
+ state: stateFilter,
185
+ assignAgent: assignAgent || undefined,
186
+ }),
187
+ })
188
+ const data = await res.json()
189
+ if (res.ok) {
190
+ setSyncResult({ imported: data.imported, skipped: data.skipped, errors: data.errors })
191
+ showFeedback(true, `Imported ${data.imported} issue${data.imported === 1 ? '' : 's'}, skipped ${data.skipped}`)
192
+ setPreviewIssues([])
193
+ fetchSyncHistory()
194
+ fetchLinkedTasks()
195
+ } else {
196
+ showFeedback(false, data.error || 'Sync failed')
197
+ }
198
+ } catch {
199
+ showFeedback(false, 'Network error')
200
+ } finally {
201
+ setSyncing(false)
202
+ }
203
+ }
204
+
205
+ if (loading) {
206
+ return (
207
+ <div className="p-6 flex items-center gap-2">
208
+ <div className="w-4 h-4 border-2 border-primary border-t-transparent rounded-full animate-spin" />
209
+ <span className="text-sm text-muted-foreground">Loading GitHub sync...</span>
210
+ </div>
211
+ )
212
+ }
213
+
214
+ return (
215
+ <div className="p-4 md:p-6 max-w-4xl mx-auto space-y-6">
216
+ {/* Header */}
217
+ <div className="flex items-center justify-between">
218
+ <div>
219
+ <h2 className="text-lg font-semibold text-foreground">GitHub Issues Sync</h2>
220
+ <p className="text-xs text-muted-foreground mt-0.5">
221
+ Import GitHub issues as Mission Control tasks
222
+ </p>
223
+ </div>
224
+ {/* Connection status badge */}
225
+ <div className="flex items-center gap-2">
226
+ <span className={`text-2xs px-2 py-1 rounded flex items-center gap-1.5 ${
227
+ tokenStatus?.connected
228
+ ? 'bg-green-500/10 text-green-400'
229
+ : 'bg-destructive/10 text-destructive'
230
+ }`}>
231
+ <span className={`w-1.5 h-1.5 rounded-full ${
232
+ tokenStatus?.connected ? 'bg-green-500' : 'bg-destructive'
233
+ }`} />
234
+ {tokenStatus?.connected
235
+ ? `GitHub: ${tokenStatus.user || 'connected'}`
236
+ : 'GitHub: not configured'}
237
+ </span>
238
+ </div>
239
+ </div>
240
+
241
+ {/* Feedback */}
242
+ {feedback && (
243
+ <div className={`rounded-lg p-3 text-xs font-medium ${
244
+ feedback.ok ? 'bg-green-500/10 text-green-400' : 'bg-destructive/10 text-destructive'
245
+ }`}>
246
+ {feedback.text}
247
+ </div>
248
+ )}
249
+
250
+ {/* Sync result banner */}
251
+ {syncResult && (
252
+ <div className="rounded-lg p-3 text-xs bg-blue-500/10 text-blue-400 flex items-center gap-4">
253
+ <span>Imported: {syncResult.imported}</span>
254
+ <span>Skipped: {syncResult.skipped}</span>
255
+ {syncResult.errors > 0 && <span className="text-destructive">Errors: {syncResult.errors}</span>}
256
+ </div>
257
+ )}
258
+
259
+ {/* Import Issues Form */}
260
+ <div className="rounded-xl border border-border bg-card overflow-hidden">
261
+ <div className="px-4 py-3 border-b border-border">
262
+ <h3 className="text-sm font-medium text-foreground">Import Issues</h3>
263
+ </div>
264
+ <div className="p-4 space-y-3">
265
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
266
+ {/* Repo input */}
267
+ <div>
268
+ <label className="text-xs text-muted-foreground mb-1 block">Repository</label>
269
+ <input
270
+ type="text"
271
+ value={repo}
272
+ onChange={e => setRepo(e.target.value)}
273
+ placeholder="owner/repo"
274
+ className="w-full px-3 py-1.5 text-sm rounded-md border border-border bg-background text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-1 focus:ring-primary"
275
+ />
276
+ </div>
277
+
278
+ {/* Label filter */}
279
+ <div>
280
+ <label className="text-xs text-muted-foreground mb-1 block">Labels (optional)</label>
281
+ <input
282
+ type="text"
283
+ value={labelFilter}
284
+ onChange={e => setLabelFilter(e.target.value)}
285
+ placeholder="bug,enhancement"
286
+ className="w-full px-3 py-1.5 text-sm rounded-md border border-border bg-background text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-1 focus:ring-primary"
287
+ />
288
+ </div>
289
+
290
+ {/* State filter */}
291
+ <div>
292
+ <label className="text-xs text-muted-foreground mb-1 block">State</label>
293
+ <select
294
+ value={stateFilter}
295
+ onChange={e => setStateFilter(e.target.value as any)}
296
+ className="w-full px-3 py-1.5 text-sm rounded-md border border-border bg-background text-foreground focus:outline-none focus:ring-1 focus:ring-primary"
297
+ >
298
+ <option value="open">Open</option>
299
+ <option value="closed">Closed</option>
300
+ <option value="all">All</option>
301
+ </select>
302
+ </div>
303
+
304
+ {/* Assign to agent */}
305
+ <div>
306
+ <label className="text-xs text-muted-foreground mb-1 block">Assign to Agent (optional)</label>
307
+ <select
308
+ value={assignAgent}
309
+ onChange={e => setAssignAgent(e.target.value)}
310
+ className="w-full px-3 py-1.5 text-sm rounded-md border border-border bg-background text-foreground focus:outline-none focus:ring-1 focus:ring-primary"
311
+ >
312
+ <option value="">Unassigned</option>
313
+ {agents.map(a => (
314
+ <option key={a.name} value={a.name}>{a.name}</option>
315
+ ))}
316
+ </select>
317
+ </div>
318
+ </div>
319
+
320
+ {/* Actions */}
321
+ <div className="flex items-center gap-2 pt-1">
322
+ <button
323
+ onClick={handlePreview}
324
+ disabled={previewing || !repo}
325
+ className="px-4 py-1.5 text-xs rounded-md border border-border text-foreground hover:bg-secondary transition-colors flex items-center gap-1.5 disabled:opacity-50"
326
+ >
327
+ {previewing ? (
328
+ <div className="w-3 h-3 border-2 border-current border-t-transparent rounded-full animate-spin" />
329
+ ) : (
330
+ <svg className="w-3.5 h-3.5" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
331
+ <circle cx="7" cy="7" r="5" />
332
+ <path d="M11 11l3 3" />
333
+ </svg>
334
+ )}
335
+ Preview
336
+ </button>
337
+ <button
338
+ onClick={handleImport}
339
+ disabled={syncing || !repo}
340
+ className={`px-4 py-1.5 text-xs rounded-md font-medium transition-colors flex items-center gap-1.5 ${
341
+ repo
342
+ ? 'bg-primary text-primary-foreground hover:bg-primary/90'
343
+ : 'bg-muted text-muted-foreground cursor-not-allowed'
344
+ }`}
345
+ >
346
+ {syncing ? (
347
+ <div className="w-3 h-3 border-2 border-current border-t-transparent rounded-full animate-spin" />
348
+ ) : (
349
+ <svg className="w-3.5 h-3.5" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
350
+ <path d="M8 2v8M5 7l3 3 3-3" />
351
+ <path d="M3 12v2h10v-2" />
352
+ </svg>
353
+ )}
354
+ Import
355
+ </button>
356
+ </div>
357
+ </div>
358
+ </div>
359
+
360
+ {/* Issue Preview Table */}
361
+ {previewIssues.length > 0 && (
362
+ <div className="rounded-xl border border-border bg-card overflow-hidden">
363
+ <div className="px-4 py-3 border-b border-border flex items-center justify-between">
364
+ <h3 className="text-sm font-medium text-foreground">
365
+ Preview ({previewIssues.length} issues)
366
+ </h3>
367
+ </div>
368
+ <div className="overflow-x-auto">
369
+ <table className="w-full text-xs">
370
+ <thead>
371
+ <tr className="border-b border-border text-muted-foreground">
372
+ <th className="text-left px-4 py-2 font-medium">#</th>
373
+ <th className="text-left px-4 py-2 font-medium">Title</th>
374
+ <th className="text-left px-4 py-2 font-medium">Labels</th>
375
+ <th className="text-left px-4 py-2 font-medium">State</th>
376
+ <th className="text-left px-4 py-2 font-medium">Created</th>
377
+ </tr>
378
+ </thead>
379
+ <tbody>
380
+ {previewIssues.map(issue => (
381
+ <tr key={issue.number} className="border-b border-border/50 hover:bg-secondary/50">
382
+ <td className="px-4 py-2 text-muted-foreground">{issue.number}</td>
383
+ <td className="px-4 py-2 text-foreground max-w-[300px] truncate">
384
+ <a
385
+ href={issue.html_url}
386
+ target="_blank"
387
+ rel="noopener noreferrer"
388
+ className="hover:text-primary transition-colors"
389
+ >
390
+ {issue.title}
391
+ </a>
392
+ </td>
393
+ <td className="px-4 py-2">
394
+ <div className="flex flex-wrap gap-1">
395
+ {issue.labels.map(l => (
396
+ <span
397
+ key={l.name}
398
+ className="px-1.5 py-0.5 rounded text-2xs bg-secondary text-muted-foreground"
399
+ >
400
+ {l.name}
401
+ </span>
402
+ ))}
403
+ </div>
404
+ </td>
405
+ <td className="px-4 py-2">
406
+ <span className={`px-1.5 py-0.5 rounded text-2xs ${
407
+ issue.state === 'open'
408
+ ? 'bg-green-500/10 text-green-400'
409
+ : 'bg-purple-500/10 text-purple-400'
410
+ }`}>
411
+ {issue.state}
412
+ </span>
413
+ </td>
414
+ <td className="px-4 py-2 text-muted-foreground">
415
+ {new Date(issue.created_at).toLocaleDateString()}
416
+ </td>
417
+ </tr>
418
+ ))}
419
+ </tbody>
420
+ </table>
421
+ </div>
422
+ </div>
423
+ )}
424
+
425
+ {/* Sync History */}
426
+ {syncHistory.length > 0 && (
427
+ <div className="rounded-xl border border-border bg-card overflow-hidden">
428
+ <div className="px-4 py-3 border-b border-border">
429
+ <h3 className="text-sm font-medium text-foreground">Sync History</h3>
430
+ </div>
431
+ <div className="overflow-x-auto">
432
+ <table className="w-full text-xs">
433
+ <thead>
434
+ <tr className="border-b border-border text-muted-foreground">
435
+ <th className="text-left px-4 py-2 font-medium">Repo</th>
436
+ <th className="text-left px-4 py-2 font-medium">Issues</th>
437
+ <th className="text-left px-4 py-2 font-medium">Status</th>
438
+ <th className="text-left px-4 py-2 font-medium">Synced At</th>
439
+ </tr>
440
+ </thead>
441
+ <tbody>
442
+ {syncHistory.map(sync => (
443
+ <tr key={sync.id} className="border-b border-border/50 hover:bg-secondary/50">
444
+ <td className="px-4 py-2 font-mono text-foreground">{sync.repo}</td>
445
+ <td className="px-4 py-2 text-muted-foreground">{sync.issue_count}</td>
446
+ <td className="px-4 py-2">
447
+ <span className={`px-1.5 py-0.5 rounded text-2xs ${
448
+ sync.status === 'success'
449
+ ? 'bg-green-500/10 text-green-400'
450
+ : sync.status === 'partial'
451
+ ? 'bg-yellow-500/10 text-yellow-400'
452
+ : 'bg-destructive/10 text-destructive'
453
+ }`}>
454
+ {sync.status}
455
+ </span>
456
+ </td>
457
+ <td className="px-4 py-2 text-muted-foreground">
458
+ {new Date(sync.created_at * 1000).toLocaleString()}
459
+ </td>
460
+ </tr>
461
+ ))}
462
+ </tbody>
463
+ </table>
464
+ </div>
465
+ </div>
466
+ )}
467
+
468
+ {/* Linked Tasks */}
469
+ {linkedTasks.length > 0 && (
470
+ <div className="rounded-xl border border-border bg-card overflow-hidden">
471
+ <div className="px-4 py-3 border-b border-border">
472
+ <h3 className="text-sm font-medium text-foreground">
473
+ Linked Tasks ({linkedTasks.length})
474
+ </h3>
475
+ </div>
476
+ <div className="overflow-x-auto">
477
+ <table className="w-full text-xs">
478
+ <thead>
479
+ <tr className="border-b border-border text-muted-foreground">
480
+ <th className="text-left px-4 py-2 font-medium">Task</th>
481
+ <th className="text-left px-4 py-2 font-medium">Status</th>
482
+ <th className="text-left px-4 py-2 font-medium">Priority</th>
483
+ <th className="text-left px-4 py-2 font-medium">GitHub</th>
484
+ <th className="text-left px-4 py-2 font-medium">Synced</th>
485
+ </tr>
486
+ </thead>
487
+ <tbody>
488
+ {linkedTasks.map(task => (
489
+ <tr key={task.id} className="border-b border-border/50 hover:bg-secondary/50">
490
+ <td className="px-4 py-2 text-foreground max-w-[250px] truncate">{task.title}</td>
491
+ <td className="px-4 py-2">
492
+ <span className="px-1.5 py-0.5 rounded text-2xs bg-secondary text-muted-foreground">
493
+ {task.status}
494
+ </span>
495
+ </td>
496
+ <td className="px-4 py-2">
497
+ <span className={`px-1.5 py-0.5 rounded text-2xs ${
498
+ task.priority === 'critical' ? 'bg-red-500/10 text-red-400' :
499
+ task.priority === 'high' ? 'bg-orange-500/10 text-orange-400' :
500
+ task.priority === 'low' ? 'bg-blue-500/10 text-blue-400' :
501
+ 'bg-secondary text-muted-foreground'
502
+ }`}>
503
+ {task.priority}
504
+ </span>
505
+ </td>
506
+ <td className="px-4 py-2">
507
+ {task.metadata.github_issue_url ? (
508
+ <a
509
+ href={task.metadata.github_issue_url}
510
+ target="_blank"
511
+ rel="noopener noreferrer"
512
+ className="text-primary hover:underline font-mono"
513
+ >
514
+ {task.metadata.github_repo}#{task.metadata.github_issue_number}
515
+ </a>
516
+ ) : (
517
+ <span className="text-muted-foreground">β€”</span>
518
+ )}
519
+ </td>
520
+ <td className="px-4 py-2 text-muted-foreground">
521
+ {task.metadata.github_synced_at
522
+ ? new Date(task.metadata.github_synced_at).toLocaleDateString()
523
+ : 'β€”'}
524
+ </td>
525
+ </tr>
526
+ ))}
527
+ </tbody>
528
+ </table>
529
+ </div>
530
+ </div>
531
+ )}
532
+ </div>
533
+ )
534
+ }
src/lib/event-bus.ts CHANGED
@@ -30,6 +30,7 @@ export type EventType =
30
  | 'audit.security'
31
  | 'connection.created'
32
  | 'connection.disconnected'
 
33
 
34
  class ServerEventBus extends EventEmitter {
35
  private static instance: ServerEventBus | null = null
 
30
  | 'audit.security'
31
  | 'connection.created'
32
  | 'connection.disconnected'
33
+ | 'github.synced'
34
 
35
  class ServerEventBus extends EventEmitter {
36
  private static instance: ServerEventBus | null = null
src/lib/github.ts ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * GitHub API client for Mission Control issue sync.
3
+ * Uses GITHUB_TOKEN from env (integration key, not core config).
4
+ */
5
+
6
+ export interface GitHubLabel {
7
+ name: string
8
+ color?: string
9
+ }
10
+
11
+ export interface GitHubUser {
12
+ login: string
13
+ avatar_url?: string
14
+ }
15
+
16
+ export interface GitHubIssue {
17
+ number: number
18
+ title: string
19
+ body: string | null
20
+ state: 'open' | 'closed'
21
+ labels: GitHubLabel[]
22
+ assignee: GitHubUser | null
23
+ html_url: string
24
+ created_at: string
25
+ updated_at: string
26
+ }
27
+
28
+ export function getGitHubToken(): string | null {
29
+ return process.env.GITHUB_TOKEN || null
30
+ }
31
+
32
+ /**
33
+ * Authenticated fetch wrapper for GitHub API.
34
+ */
35
+ export async function githubFetch(
36
+ path: string,
37
+ options: RequestInit = {}
38
+ ): Promise<Response> {
39
+ const token = getGitHubToken()
40
+ if (!token) {
41
+ throw new Error('GITHUB_TOKEN not configured')
42
+ }
43
+
44
+ const url = path.startsWith('https://')
45
+ ? path
46
+ : `https://api.github.com${path.startsWith('/') ? '' : '/'}${path}`
47
+
48
+ const headers: Record<string, string> = {
49
+ Authorization: `Bearer ${token}`,
50
+ Accept: 'application/vnd.github.v3+json',
51
+ 'User-Agent': 'MissionControl/1.0',
52
+ ...(options.headers as Record<string, string> || {}),
53
+ }
54
+
55
+ if (options.body) {
56
+ headers['Content-Type'] = 'application/json'
57
+ }
58
+
59
+ const controller = new AbortController()
60
+ const timeout = setTimeout(() => controller.abort(), 15000)
61
+
62
+ try {
63
+ const res = await fetch(url, {
64
+ ...options,
65
+ headers,
66
+ signal: controller.signal,
67
+ })
68
+ return res
69
+ } finally {
70
+ clearTimeout(timeout)
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Fetch issues from a GitHub repo.
76
+ */
77
+ export async function fetchIssues(
78
+ repo: string,
79
+ params?: {
80
+ state?: 'open' | 'closed' | 'all'
81
+ labels?: string
82
+ since?: string
83
+ per_page?: number
84
+ page?: number
85
+ }
86
+ ): Promise<GitHubIssue[]> {
87
+ const searchParams = new URLSearchParams()
88
+ if (params?.state) searchParams.set('state', params.state)
89
+ if (params?.labels) searchParams.set('labels', params.labels)
90
+ if (params?.since) searchParams.set('since', params.since)
91
+ searchParams.set('per_page', String(params?.per_page ?? 30))
92
+ searchParams.set('page', String(params?.page ?? 1))
93
+
94
+ const qs = searchParams.toString()
95
+ const res = await githubFetch(`/repos/${repo}/issues?${qs}`)
96
+
97
+ if (!res.ok) {
98
+ const text = await res.text()
99
+ throw new Error(`GitHub API error ${res.status}: ${text}`)
100
+ }
101
+
102
+ const data = await res.json()
103
+ // Filter out pull requests (GitHub API returns PRs in issues endpoint)
104
+ return (data as any[]).filter((item: any) => !item.pull_request)
105
+ }
106
+
107
+ /**
108
+ * Fetch a single issue.
109
+ */
110
+ export async function fetchIssue(
111
+ repo: string,
112
+ issueNumber: number
113
+ ): Promise<GitHubIssue> {
114
+ const res = await githubFetch(`/repos/${repo}/issues/${issueNumber}`)
115
+ if (!res.ok) {
116
+ const text = await res.text()
117
+ throw new Error(`GitHub API error ${res.status}: ${text}`)
118
+ }
119
+ return res.json()
120
+ }
121
+
122
+ /**
123
+ * Post a comment on a GitHub issue.
124
+ */
125
+ export async function createIssueComment(
126
+ repo: string,
127
+ issueNumber: number,
128
+ body: string
129
+ ): Promise<void> {
130
+ const res = await githubFetch(`/repos/${repo}/issues/${issueNumber}/comments`, {
131
+ method: 'POST',
132
+ body: JSON.stringify({ body }),
133
+ })
134
+ if (!res.ok) {
135
+ const text = await res.text()
136
+ throw new Error(`GitHub API error ${res.status}: ${text}`)
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Update an issue's state (open/closed).
142
+ */
143
+ export async function updateIssueState(
144
+ repo: string,
145
+ issueNumber: number,
146
+ state: 'open' | 'closed'
147
+ ): Promise<void> {
148
+ const res = await githubFetch(`/repos/${repo}/issues/${issueNumber}`, {
149
+ method: 'PATCH',
150
+ body: JSON.stringify({ state }),
151
+ })
152
+ if (!res.ok) {
153
+ const text = await res.text()
154
+ throw new Error(`GitHub API error ${res.status}: ${text}`)
155
+ }
156
+ }
src/lib/migrations.ts CHANGED
@@ -458,6 +458,25 @@ const migrations: Migration[] = [
458
  CREATE INDEX IF NOT EXISTS idx_direct_connections_status ON direct_connections(status);
459
  `)
460
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
461
  }
462
  ]
463
 
 
458
  CREATE INDEX IF NOT EXISTS idx_direct_connections_status ON direct_connections(status);
459
  `)
460
  }
461
+ },
462
+ {
463
+ id: '017_github_sync',
464
+ up: (db) => {
465
+ db.exec(`
466
+ CREATE TABLE IF NOT EXISTS github_syncs (
467
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
468
+ repo TEXT NOT NULL,
469
+ last_synced_at INTEGER NOT NULL DEFAULT (unixepoch()),
470
+ issue_count INTEGER NOT NULL DEFAULT 0,
471
+ sync_direction TEXT NOT NULL DEFAULT 'inbound',
472
+ status TEXT NOT NULL DEFAULT 'success',
473
+ error TEXT,
474
+ created_at INTEGER NOT NULL DEFAULT (unixepoch())
475
+ );
476
+ CREATE INDEX IF NOT EXISTS idx_github_syncs_repo ON github_syncs(repo);
477
+ CREATE INDEX IF NOT EXISTS idx_github_syncs_created_at ON github_syncs(created_at);
478
+ `)
479
+ }
480
  }
481
  ]
482
 
src/lib/validation.ts CHANGED
@@ -161,3 +161,14 @@ export const connectSchema = z.object({
161
  agent_role: z.string().max(100).optional(),
162
  metadata: z.record(z.string(), z.unknown()).optional(),
163
  })
 
 
 
 
 
 
 
 
 
 
 
 
161
  agent_role: z.string().max(100).optional(),
162
  metadata: z.record(z.string(), z.unknown()).optional(),
163
  })
164
+
165
+ export const githubSyncSchema = z.object({
166
+ action: z.enum(['sync', 'comment', 'close', 'status']),
167
+ repo: z.string().regex(/^[^/]+\/[^/]+$/, 'Repo must be owner/repo format').optional(),
168
+ labels: z.string().optional(),
169
+ state: z.enum(['open', 'closed', 'all']).optional(),
170
+ assignAgent: z.string().optional(),
171
+ issueNumber: z.number().optional(),
172
+ body: z.string().optional(),
173
+ comment: z.string().optional(),
174
+ })
tests/github-sync.spec.ts ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { test, expect } from '@playwright/test'
2
+ import { API_KEY_HEADER } from './helpers'
3
+
4
+ test.describe('GitHub Sync API', () => {
5
+ // ── GET /api/github ────────────────────────────
6
+
7
+ test('GET /api/github?action=issues requires auth', async ({ request }) => {
8
+ const res = await request.get('/api/github?action=issues&repo=owner/repo')
9
+ expect(res.status()).toBe(401)
10
+ })
11
+
12
+ test('GET /api/github?action=issues returns error without GITHUB_TOKEN', async ({ request }) => {
13
+ const res = await request.get('/api/github?action=issues&repo=owner/repo', {
14
+ headers: API_KEY_HEADER,
15
+ })
16
+ // Either 400 (token not configured) or 500 (API error) are acceptable
17
+ expect([400, 500]).toContain(res.status())
18
+ const body = await res.json()
19
+ expect(body.error).toBeDefined()
20
+ })
21
+
22
+ test('GET /api/github rejects invalid action', async ({ request }) => {
23
+ const res = await request.get('/api/github?action=invalid', {
24
+ headers: API_KEY_HEADER,
25
+ })
26
+ expect(res.status()).toBe(400)
27
+ const body = await res.json()
28
+ expect(body.error).toContain('Unknown action')
29
+ })
30
+
31
+ // ── POST /api/github ───────────────────────────
32
+
33
+ test('POST /api/github with action=status returns sync history', async ({ request }) => {
34
+ const res = await request.post('/api/github', {
35
+ headers: API_KEY_HEADER,
36
+ data: { action: 'status' },
37
+ })
38
+ expect(res.status()).toBe(200)
39
+ const body = await res.json()
40
+ expect(body.syncs).toBeDefined()
41
+ expect(Array.isArray(body.syncs)).toBe(true)
42
+ })
43
+
44
+ test('POST /api/github with action=sync requires repo param', async ({ request }) => {
45
+ const res = await request.post('/api/github', {
46
+ headers: API_KEY_HEADER,
47
+ data: { action: 'sync' },
48
+ })
49
+ // Should fail because no repo and no GITHUB_DEFAULT_REPO
50
+ expect([400, 500]).toContain(res.status())
51
+ })
52
+
53
+ test('POST /api/github rejects invalid repo format', async ({ request }) => {
54
+ const res = await request.post('/api/github', {
55
+ headers: API_KEY_HEADER,
56
+ data: { action: 'sync', repo: 'invalid-no-slash' },
57
+ })
58
+ expect(res.status()).toBe(400)
59
+ const body = await res.json()
60
+ expect(body.error || body.details).toBeDefined()
61
+ })
62
+ })