Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
claude/adoring-hopper-5x74bqclaude/affectionate-feynman-ykrf1hclaude/architecture-audit-design-wxprenclaude/build-status-update-3MXsfclaude/charming-meitner-mllb5rclaude/compare-gate-gluecron-s4mFQclaude/confident-faraday-tikcwbclaude/continue-work-XMTlIclaude/crontech-gluecron-deploy-7MIECclaude/crontech-platform-setup-SeKfwclaude/design-2026claude/ecstatic-ptolemy-jMdigclaude/enhance-github-integration-QNHdGclaude/fix-aa-loop-issue-PonMQclaude/fix-actions-and-processclaude/fix-desktop-errors-XqoW8claude/fix-red-workflowsclaude/fix-website-access-6FKJNclaude/gatetest-integration-hardeningclaude/github-audit-improvements-bDFr9claude/gluecron-launch-status-FoMRlclaude/hopeful-lamport-olfCTclaude/issue-to-pr-and-protectionsclaude/jolly-heisenberg-2sg1Qclaude/launch-preparation-QmTb6claude/new-session-xk1l7claude/plan-platform-architecture-kkN4yclaude/platform-analysis-roadmap-1nUGLclaude/platform-launch-assessment-8dWV8claude/polish-platform-release-AeDrUclaude/resume-previous-work-KzyLwclaude/review-crontech-handoff-qYEVqclaude/review-project-completeness-lHhS2claude/review-readme-docs-ulqPKclaude/serene-edison-rj87weclaude/setup-multi-repo-dev-BCwNQclaude/ship-fixes-and-tests-Jvz1cclaude/site-audit-competitive-pctlwgclaude/site-migration-vercel-XstpKclaude/standalone-product-repos-XHFTDcopilot/feat-smart-empty-states-keyboard-first-enhancementcopilot/feat-smart-morning-digest-review-context-restorecopilot/fix-and-process-workflowscopilot/update-ai-powered-code-reviewfeat/debt-mapfeat/push-policy-codeowners-hardeningfeat/smart-digest-contextfeat/stage-impactfeat/t1-secret-migrationfeat/u-polishfeat/w-self-hostfeat/w2-claude-configfix/agent-journey-orphan-sweepgatetest/auto-fix-1776586424172gatetest/auto-fix-1776586534814gatetest/auto-fix-1776590685143gatetest/auto-fix-1776590808199mainops/redeploy-retriggerstyle/dxt-cta-themeworktree-agent-a3377aad30d55da26worktree-agent-a7ef607b7ee1d6c74
admin-command.tsx31.5 KB · 865 lines
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
/**
 * Admin Command Center — /admin/command
 *
 * Single-pane operational view for site admins. Shows the live health of
 * every system in one place so you never have to click through 20 separate
 * pages to understand what's wrong.
 *
 * Panels:
 *   1. Platform status bar — 5 color-coded health indicators
 *   2. Failing gates right now — repos with gate failures (last 2h)
 *   3. Deployment health — last 24h, failed/blocked surfaced first
 *   4. AI engine activity — reviews, merges, repairs, triages (24h)
 *   5. Auth anomalies — failed-login clusters (brute-force signal)
 *   6. Recent audit errors — security/delete/error actions (last hour)
 *   7. Quick-action links to every admin sub-page
 *
 * All queries are wrapped in try/catch — a DB hiccup on one panel never
 * breaks the whole page. Each failed panel degrades to "unavailable."
 *
 * Auto-refreshes every 30 seconds via a <meta> refresh so operators
 * keeping this open in a tab always see live state.
 */

import { Hono } from "hono";
import { and, desc, eq, gte, lt, ne, sql } from "drizzle-orm";
import { db } from "../db";
import {
  auditLog,
  deployments,
  gateRuns,
  loginAttempts,
  prComments,
  pullRequests,
  repositories,
  users,
  issueComments,
} from "../db/schema";
import { Layout } from "../views/layout";
import { softAuth } from "../middleware/auth";
import type { AuthEnv } from "../middleware/auth";
import { isSiteAdmin } from "../lib/admin";

const app = new Hono<AuthEnv>();
app.use("*", softAuth);

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

function statusPill(
  ok: boolean | null,
  label: string,
  detail?: string
): JSX.Element {
  const cls = ok === null ? "cmd-pill cmd-pill-warn" : ok ? "cmd-pill cmd-pill-ok" : "cmd-pill cmd-pill-err";
  return (
    <span class={cls} title={detail ?? ""}>
      <span class="cmd-pill-dot" />
      {label}
    </span>
  );
}

function relativeTime(d: Date): string {
  const sec = Math.floor((Date.now() - d.getTime()) / 1000);
  if (sec < 60) return `${sec}s ago`;
  if (sec < 3600) return `${Math.floor(sec / 60)}m ago`;
  if (sec < 86400) return `${Math.floor(sec / 3600)}h ago`;
  return `${Math.floor(sec / 86400)}d ago`;
}

// ---------------------------------------------------------------------------
// GET /admin/command
// ---------------------------------------------------------------------------

app.get("/admin/command", async (c) => {
  const auth = c.get("user");
  if (!auth) return c.redirect("/login?next=/admin/command");
  if (!(await isSiteAdmin(auth.id))) return c.redirect("/admin?error=Not+a+site+admin");

  const now = new Date();
  const h1 = new Date(now.getTime() - 1 * 60 * 60 * 1000);
  const h2 = new Date(now.getTime() - 2 * 60 * 60 * 1000);
  const h24 = new Date(now.getTime() - 24 * 60 * 60 * 1000);
  const h6 = new Date(now.getTime() - 6 * 60 * 60 * 1000);

  // ── 1. Platform status indicators ────────────────────────────────────────
  let gateFailRate: number | null = null;
  let deployFailRate: number | null = null;
  let aiActivity: number | null = null;
  let authFailures: number | null = null;
  let recentErrors: number | null = null;

  try {
    const [total] = await db
      .select({ n: sql<number>`count(*)::int` })
      .from(gateRuns)
      .where(gte(gateRuns.createdAt, h6));
    const [failed] = await db
      .select({ n: sql<number>`count(*)::int` })
      .from(gateRuns)
      .where(and(gte(gateRuns.createdAt, h6), eq(gateRuns.status, "failed")));
    const t = Number(total?.n || 0);
    gateFailRate = t === 0 ? 0 : Math.round((Number(failed?.n || 0) / t) * 100);
  } catch (_) {}

  try {
    const [dfail] = await db
      .select({ n: sql<number>`count(*)::int` })
      .from(deployments)
      .where(and(gte(deployments.createdAt, h24), eq(deployments.status, "failed")));
    const [dtotal] = await db
      .select({ n: sql<number>`count(*)::int` })
      .from(deployments)
      .where(gte(deployments.createdAt, h24));
    const dt = Number(dtotal?.n || 0);
    deployFailRate = dt === 0 ? 0 : Math.round((Number(dfail?.n || 0) / dt) * 100);
  } catch (_) {}

  try {
    const [ai] = await db
      .select({ n: sql<number>`count(*)::int` })
      .from(prComments)
      .where(and(gte(prComments.createdAt, h24), eq(prComments.isAiReview, true)));
    aiActivity = Number(ai?.n || 0);
  } catch (_) {}

  try {
    const [af] = await db
      .select({ n: sql<number>`count(*)::int` })
      .from(loginAttempts)
      .where(and(gte(loginAttempts.createdAt, h1), eq(loginAttempts.success, false)));
    authFailures = Number(af?.n || 0);
  } catch (_) {}

  try {
    const [ae] = await db
      .select({ n: sql<number>`count(*)::int` })
      .from(auditLog)
      .where(
        and(
          gte(auditLog.createdAt, h1),
          sql`${auditLog.action} IN ('repo.delete','push.rejected','auth.lockout','admin.security','error')`
        )
      );
    recentErrors = Number(ae?.n || 0);
  } catch (_) {}

  // ── 2. Failing gates (last 2h) ────────────────────────────────────────────
  type FailingGate = {
    id: string;
    gateName: string;
    status: string;
    repoName: string;
    ownerUsername: string;
    prId: string | null;
    createdAt: Date;
  };
  let failingGates: FailingGate[] = [];
  try {
    failingGates = await db
      .select({
        id: gateRuns.id,
        gateName: gateRuns.gateName,
        status: gateRuns.status,
        repoName: repositories.name,
        ownerUsername: users.username,
        prId: gateRuns.pullRequestId,
        createdAt: gateRuns.createdAt,
      })
      .from(gateRuns)
      .innerJoin(repositories, eq(gateRuns.repositoryId, repositories.id))
      .innerJoin(users, eq(repositories.ownerId, users.id))
      .where(and(gte(gateRuns.createdAt, h2), eq(gateRuns.status, "failed")))
      .orderBy(desc(gateRuns.createdAt))
      .limit(20);
  } catch (_) {}

  // ── 3. Deployment health (last 24h) ──────────────────────────────────────
  type DeployRow = {
    id: string;
    status: string;
    environment: string;
    ref: string;
    repoName: string;
    ownerUsername: string;
    blockedReason: string | null;
    createdAt: Date;
  };
  let recentDeploys: DeployRow[] = [];
  try {
    recentDeploys = await db
      .select({
        id: deployments.id,
        status: deployments.status,
        environment: deployments.environment,
        ref: deployments.ref,
        repoName: repositories.name,
        ownerUsername: users.username,
        blockedReason: deployments.blockedReason,
        createdAt: deployments.createdAt,
      })
      .from(deployments)
      .innerJoin(repositories, eq(deployments.repositoryId, repositories.id))
      .innerJoin(users, eq(repositories.ownerId, users.id))
      .where(gte(deployments.createdAt, h24))
      .orderBy(desc(deployments.createdAt))
      .limit(15);
  } catch (_) {}

  // ── 4. AI engine activity (24h) ───────────────────────────────────────────
  let aiReviews = 0, autoMerges = 0, issueTriages = 0, ciRepairs = 0;
  try {
    const [r] = await db
      .select({ n: sql<number>`count(*)::int` })
      .from(prComments)
      .where(and(gte(prComments.createdAt, h24), eq(prComments.isAiReview, true)));
    aiReviews = Number(r?.n || 0);

    const [m] = await db
      .select({ n: sql<number>`count(*)::int` })
      .from(auditLog)
      .where(
        and(
          gte(auditLog.createdAt, h24),
          eq(auditLog.action, "auto_merge.merged")
        )
      );
    autoMerges = Number(m?.n || 0);

    const [it] = await db
      .select({ n: sql<number>`count(*)::int` })
      .from(issueComments)
      .where(
        and(
          gte(issueComments.createdAt, h24),
          sql`${issueComments.body} LIKE '%gluecron:issue-triage%'`
        )
      );
    issueTriages = Number(it?.n || 0);

    const [cr] = await db
      .select({ n: sql<number>`count(*)::int` })
      .from(auditLog)
      .where(
        and(
          gte(auditLog.createdAt, h24),
          sql`${auditLog.action} LIKE 'ci_autofix%'`
        )
      );
    ciRepairs = Number(cr?.n || 0);
  } catch (_) {}

  // ── 5. Auth anomalies (failed login clusters, last hour) ─────────────────
  type AuthAnomaly = { email: string; failCount: number; lastSeen: Date };
  let authAnomalies: AuthAnomaly[] = [];
  try {
    const rows = await db
      .select({
        email: loginAttempts.email,
        failCount: sql<number>`count(*)::int`,
        lastSeen: sql<Date>`max(${loginAttempts.createdAt})`,
      })
      .from(loginAttempts)
      .where(and(gte(loginAttempts.createdAt, h1), eq(loginAttempts.success, false)))
      .groupBy(loginAttempts.email)
      .having(sql`count(*) >= 3`)
      .orderBy(sql`count(*) desc`)
      .limit(10);
    authAnomalies = rows.map((r) => ({
      email: r.email,
      failCount: Number(r.failCount),
      lastSeen: new Date(r.lastSeen),
    }));
  } catch (_) {}

  // ── 6. Recent audit errors (last hour) ───────────────────────────────────
  type AuditEntry = {
    id: string;
    action: string;
    username: string | null;
    ip: string | null;
    createdAt: Date;
  };
  let auditErrors: AuditEntry[] = [];
  try {
    auditErrors = await db
      .select({
        id: auditLog.id,
        action: auditLog.action,
        username: users.username,
        ip: auditLog.ip,
        createdAt: auditLog.createdAt,
      })
      .from(auditLog)
      .leftJoin(users, eq(auditLog.userId, users.id))
      .where(
        and(
          gte(auditLog.createdAt, h1),
          sql`${auditLog.action} IN ('repo.delete','push.rejected','auth.lockout','admin.security.alert','error','deploy.failed','gate.force_pass')`
        )
      )
      .orderBy(desc(auditLog.createdAt))
      .limit(20);
  } catch (_) {}

  // ── 7. Recently active repos with open failing PRs ────────────────────────
  type NeedAttention = {
    ownerUsername: string;
    repoName: string;
    failedGates: number;
    openPrs: number;
  };
  let needAttention: NeedAttention[] = [];
  try {
    const rows = await db
      .select({
        ownerUsername: users.username,
        repoName: repositories.name,
        failedGates: sql<number>`count(distinct ${gateRuns.id})::int`,
        openPrs: sql<number>`count(distinct ${pullRequests.id})::int`,
      })
      .from(gateRuns)
      .innerJoin(repositories, eq(gateRuns.repositoryId, repositories.id))
      .innerJoin(users, eq(repositories.ownerId, users.id))
      .leftJoin(
        pullRequests,
        and(
          eq(pullRequests.repositoryId, repositories.id),
          eq(pullRequests.state, "open")
        )
      )
      .where(and(gte(gateRuns.createdAt, h24), eq(gateRuns.status, "failed")))
      .groupBy(users.username, repositories.name)
      .orderBy(sql`count(distinct ${gateRuns.id}) desc`)
      .limit(8);
    needAttention = rows.map((r) => ({
      ownerUsername: r.ownerUsername,
      repoName: r.repoName,
      failedGates: Number(r.failedGates),
      openPrs: Number(r.openPrs),
    }));
  } catch (_) {}

  // ── Derived health indicators ─────────────────────────────────────────────
  const gatesOk = gateFailRate === null ? null : gateFailRate <= 15;
  const deploysOk = deployFailRate === null ? null : deployFailRate <= 10;
  const aiOk = aiActivity === null ? null : true; // AI is "ok" as long as we got a count
  const authOk = authFailures === null ? null : authFailures <= 20;
  const errorsOk = recentErrors === null ? null : recentErrors === 0;

  const overallOk =
    gatesOk !== false && deploysOk !== false && authOk !== false && errorsOk !== false;

  // ── Render ─────────────────────────────────────────────────────────────────
  const styles = `
    .cmd-wrap { max-width: 1680px; margin: 0 auto; padding: 0 var(--space-4); }

    .cmd-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: var(--space-4);
      margin-bottom: var(--space-5);
      padding: var(--space-4) var(--space-5);
      background: var(--bg-elevated);
      border: 1px solid var(--border);
      border-radius: 14px;
    }
    .cmd-header-left { display: flex; align-items: center; gap: var(--space-3); }
    .cmd-header-eyebrow { font-size: 11px; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.1em; }
    .cmd-header-title { font-size: 22px; font-weight: 700; color: var(--text); margin: 2px 0 0; }
    .cmd-overall { display: flex; align-items: center; gap: 8px; font-size: 13px; font-weight: 600; }
    .cmd-overall-ok  { color: var(--success); }
    .cmd-overall-err { color: var(--danger); }

    .cmd-status-bar {
      display: flex;
      gap: var(--space-3);
      flex-wrap: wrap;
      margin-bottom: var(--space-5);
    }
    .cmd-pill {
      display: inline-flex;
      align-items: center;
      gap: 6px;
      padding: 5px 12px;
      border-radius: 20px;
      font-size: 12px;
      font-weight: 600;
      border: 1px solid transparent;
    }
    .cmd-pill-ok   { background: rgba(35,134,54,0.12); border-color: rgba(35,134,54,0.25); color: #3fb950; }
    .cmd-pill-err  { background: rgba(248,81,73,0.12); border-color: rgba(248,81,73,0.25); color: #f85149; }
    .cmd-pill-warn { background: rgba(210,153,34,0.12); border-color: rgba(210,153,34,0.25); color: #d29922; }
    .cmd-pill-dot  { width: 7px; height: 7px; border-radius: 50%; background: currentColor; }

    .cmd-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: var(--space-4);
      margin-bottom: var(--space-4);
    }
    @media (max-width: 900px) { .cmd-grid { grid-template-columns: 1fr; } }
    .cmd-grid-wide { grid-column: 1 / -1; }

    .cmd-panel {
      background: var(--bg-elevated);
      border: 1px solid var(--border);
      border-radius: 12px;
      overflow: hidden;
    }
    .cmd-panel-head {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: var(--space-3) var(--space-4);
      border-bottom: 1px solid var(--border);
      font-size: 12px;
      font-weight: 700;
      text-transform: uppercase;
      letter-spacing: 0.07em;
      color: var(--text-muted);
    }
    .cmd-panel-head-count {
      font-size: 11px;
      background: var(--bg-inset);
      border: 1px solid var(--border);
      border-radius: 10px;
      padding: 1px 8px;
      color: var(--text-muted);
      font-weight: 500;
      letter-spacing: 0;
    }
    .cmd-panel-body { padding: var(--space-3) 0; }
    .cmd-empty { padding: var(--space-3) var(--space-4); color: var(--text-muted); font-size: 13px; display: flex; align-items: center; gap: 8px; }
    .cmd-empty::before { content: '✓'; color: var(--success); font-weight: 700; }

    .cmd-row {
      display: flex;
      align-items: flex-start;
      gap: var(--space-3);
      padding: var(--space-2) var(--space-4);
      transition: background 120ms;
    }
    .cmd-row:hover { background: var(--bg-hover); }
    .cmd-row-icon { font-size: 13px; margin-top: 1px; flex-shrink: 0; width: 16px; text-align: center; }
    .cmd-row-main { flex: 1; min-width: 0; }
    .cmd-row-title {
      font-size: 13px;
      color: var(--text);
      font-weight: 500;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .cmd-row-title a { color: inherit; text-decoration: none; }
    .cmd-row-title a:hover { color: var(--accent); text-decoration: underline; }
    .cmd-row-sub { font-size: 11px; color: var(--text-muted); margin-top: 1px; }
    .cmd-row-time { font-size: 11px; color: var(--text-muted); flex-shrink: 0; white-space: nowrap; }

    .cmd-badge {
      display: inline-block;
      padding: 1px 7px;
      border-radius: 9px;
      font-size: 11px;
      font-weight: 600;
    }
    .cmd-badge-fail    { background: rgba(248,81,73,0.15); color: #f85149; }
    .cmd-badge-ok      { background: rgba(35,134,54,0.15); color: #3fb950; }
    .cmd-badge-warn    { background: rgba(210,153,34,0.15); color: #d29922; }
    .cmd-badge-pending { background: rgba(130,80,223,0.15); color: #9a7fde; }
    .cmd-badge-running { background: rgba(88,166,255,0.15); color: #58a6ff; }

    .cmd-ai-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: var(--space-3);
      padding: var(--space-4);
    }
    @media (max-width: 700px) { .cmd-ai-grid { grid-template-columns: repeat(2, 1fr); } }
    .cmd-ai-card {
      background: var(--bg-inset);
      border: 1px solid var(--border);
      border-radius: 10px;
      padding: var(--space-3);
      text-align: center;
    }
    .cmd-ai-value { font-size: 28px; font-weight: 700; color: var(--text); line-height: 1; margin-bottom: 4px; }
    .cmd-ai-label { font-size: 11px; color: var(--text-muted); }

    .cmd-links {
      display: flex;
      flex-wrap: wrap;
      gap: var(--space-2);
      padding: var(--space-4);
    }
    .cmd-link {
      display: inline-flex;
      align-items: center;
      gap: 6px;
      padding: 6px 12px;
      background: var(--bg-inset);
      border: 1px solid var(--border);
      border-radius: 8px;
      font-size: 12px;
      color: var(--text-secondary);
      text-decoration: none;
      transition: border-color 120ms, color 120ms;
    }
    .cmd-link:hover { border-color: var(--accent); color: var(--accent); }

    .cmd-refresh-note { font-size: 11px; color: var(--text-muted); }
  `;

  const deployStatusBadge = (status: string) => {
    if (status === "success" || status === "succeeded") return <span class="cmd-badge cmd-badge-ok">{status}</span>;
    if (status === "failed") return <span class="cmd-badge cmd-badge-fail">failed</span>;
    if (status === "running") return <span class="cmd-badge cmd-badge-running">running</span>;
    if (status === "pending" || status === "waiting_timer") return <span class="cmd-badge cmd-badge-pending">{status}</span>;
    if (status === "blocked") return <span class="cmd-badge cmd-badge-warn">blocked</span>;
    return <span class="cmd-badge cmd-badge-warn">{status}</span>;
  };

  return c.html(
    <Layout title="Command Center — Admin" user={auth}>
      <style>{styles}</style>
      {/* Auto-refresh every 30s */}
      <meta http-equiv="refresh" content="30" />

      <div class="cmd-wrap">
        {/* Header */}
        <div class="cmd-header">
          <div class="cmd-header-left">
            <div>
              <div class="cmd-header-eyebrow">Site Administration</div>
              <div class="cmd-header-title">Command Center</div>
            </div>
          </div>
          <div class="cmd-overall">
            {overallOk ? (
              <span class="cmd-overall-ok">● All systems nominal</span>
            ) : (
              <span class="cmd-overall-err">● Attention required</span>
            )}
            <span class="cmd-refresh-note">· refreshes every 30s</span>
          </div>
        </div>

        {/* Status bar */}
        <div class="cmd-status-bar">
          {statusPill(
            gatesOk,
            gateFailRate === null ? "Gates: unknown" : `Gates: ${gateFailRate}% fail (6h)`,
            "Gate run failure rate over the last 6 hours"
          )}
          {statusPill(
            deploysOk,
            deployFailRate === null ? "Deploys: unknown" : `Deploys: ${deployFailRate}% fail (24h)`,
            "Deployment failure rate over the last 24 hours"
          )}
          {statusPill(
            aiOk,
            aiActivity === null ? "AI: unknown" : `AI: ${aiActivity} reviews (24h)`,
            "AI review comments posted in the last 24 hours"
          )}
          {statusPill(
            authOk,
            authFailures === null ? "Auth: unknown" : `Auth: ${authFailures} failed logins (1h)`,
            "Failed login attempts in the last hour"
          )}
          {statusPill(
            errorsOk,
            recentErrors === null ? "Errors: unknown" : recentErrors === 0 ? "No critical events (1h)" : `${recentErrors} critical events (1h)`,
            "Security/delete/error audit events in the last hour"
          )}
        </div>

        <div class="cmd-grid">
          {/* Failing gates */}
          <div class="cmd-panel">
            <div class="cmd-panel-head">
              <span>Failing gates</span>
              <span class="cmd-panel-head-count">{failingGates.length} in last 2h</span>
            </div>
            <div class="cmd-panel-body">
              {failingGates.length === 0 ? (
                <div class="cmd-empty">No gate failures in the last 2 hours</div>
              ) : (
                failingGates.map((g) => (
                  <div class="cmd-row" key={g.id}>
                    <div class="cmd-row-icon"></div>
                    <div class="cmd-row-main">
                      <div class="cmd-row-title">
                        <a href={`/${g.ownerUsername}/${g.repoName}`}>
                          {g.ownerUsername}/{g.repoName}
                        </a>
                        {" — "}
                        <span style="color:var(--text-muted)">{g.gateName}</span>
                      </div>
                      <div class="cmd-row-sub">
                        {g.prId ? (
                          <a href={`/${g.ownerUsername}/${g.repoName}/pulls`} style="color:inherit">
                            View PR →
                          </a>
                        ) : "push gate"}
                      </div>
                    </div>
                    <div class="cmd-row-time">{relativeTime(g.createdAt)}</div>
                  </div>
                ))
              )}
            </div>
          </div>

          {/* Deployment health */}
          <div class="cmd-panel">
            <div class="cmd-panel-head">
              <span>Deployments</span>
              <span class="cmd-panel-head-count">{recentDeploys.length} in 24h</span>
            </div>
            <div class="cmd-panel-body">
              {recentDeploys.length === 0 ? (
                <div class="cmd-empty">No deployments in the last 24 hours</div>
              ) : (
                recentDeploys.map((d) => (
                  <div class="cmd-row" key={d.id}>
                    <div class="cmd-row-icon">
                      {d.status === "success" || d.status === "succeeded" ? "🟢" :
                       d.status === "failed" ? "🔴" :
                       d.status === "running" ? "🔵" : "🟡"}
                    </div>
                    <div class="cmd-row-main">
                      <div class="cmd-row-title">
                        <a href={`/${d.ownerUsername}/${d.repoName}/deployments`}>
                          {d.ownerUsername}/{d.repoName}
                        </a>
                        {" "}{deployStatusBadge(d.status)}
                      </div>
                      <div class="cmd-row-sub">
                        {d.environment} · {d.ref.replace("refs/heads/", "")}
                        {d.blockedReason ? ` · ${d.blockedReason.slice(0, 60)}` : ""}
                      </div>
                    </div>
                    <div class="cmd-row-time">{relativeTime(d.createdAt)}</div>
                  </div>
                ))
              )}
            </div>
          </div>

          {/* Repos needing attention */}
          <div class="cmd-panel">
            <div class="cmd-panel-head">
              <span>Repos needing attention</span>
              <span class="cmd-panel-head-count">{needAttention.length} repos (24h)</span>
            </div>
            <div class="cmd-panel-body">
              {needAttention.length === 0 ? (
                <div class="cmd-empty">All repos healthy in the last 24 hours</div>
              ) : (
                needAttention.map((r) => (
                  <div class="cmd-row" key={`${r.ownerUsername}/${r.repoName}`}>
                    <div class="cmd-row-icon"></div>
                    <div class="cmd-row-main">
                      <div class="cmd-row-title">
                        <a href={`/${r.ownerUsername}/${r.repoName}`}>
                          {r.ownerUsername}/{r.repoName}
                        </a>
                      </div>
                      <div class="cmd-row-sub">
                        {r.failedGates} gate failure{r.failedGates === 1 ? "" : "s"} ·{" "}
                        {r.openPrs} open PR{r.openPrs === 1 ? "" : "s"}
                      </div>
                    </div>
                    <div class="cmd-row-time">
                      <a href={`/${r.ownerUsername}/${r.repoName}/gates`} style="color:var(--accent);font-size:11px">
                        Gates →
                      </a>
                    </div>
                  </div>
                ))
              )}
            </div>
          </div>

          {/* Auth anomalies */}
          <div class="cmd-panel">
            <div class="cmd-panel-head">
              <span>Auth anomalies</span>
              <span class="cmd-panel-head-count">≥3 failures in 1h</span>
            </div>
            <div class="cmd-panel-body">
              {authAnomalies.length === 0 ? (
                <div class="cmd-empty">No login clusters detected this hour</div>
              ) : (
                authAnomalies.map((a) => (
                  <div class="cmd-row" key={a.email}>
                    <div class="cmd-row-icon">🔐</div>
                    <div class="cmd-row-main">
                      <div class="cmd-row-title">{a.email}</div>
                      <div class="cmd-row-sub">{a.failCount} failed attempts</div>
                    </div>
                    <div class="cmd-row-time">{relativeTime(a.lastSeen)}</div>
                  </div>
                ))
              )}
            </div>
          </div>

          {/* AI engine stats — full width */}
          <div class="cmd-panel cmd-grid-wide">
            <div class="cmd-panel-head">
              <span>AI engine — last 24h</span>
            </div>
            <div class="cmd-ai-grid">
              <div class="cmd-ai-card">
                <div class="cmd-ai-value">{aiReviews}</div>
                <div class="cmd-ai-label">Code reviews</div>
              </div>
              <div class="cmd-ai-card">
                <div class="cmd-ai-value">{autoMerges}</div>
                <div class="cmd-ai-label">Auto-merges</div>
              </div>
              <div class="cmd-ai-card">
                <div class="cmd-ai-value">{issueTriages}</div>
                <div class="cmd-ai-label">Issue triages</div>
              </div>
              <div class="cmd-ai-card">
                <div class="cmd-ai-value">{ciRepairs}</div>
                <div class="cmd-ai-label">CI repairs</div>
              </div>
            </div>
          </div>

          {/* Recent audit errors — full width */}
          <div class="cmd-panel cmd-grid-wide">
            <div class="cmd-panel-head">
              <span>Critical audit events</span>
              <span class="cmd-panel-head-count">last hour</span>
            </div>
            <div class="cmd-panel-body">
              {auditErrors.length === 0 ? (
                <div class="cmd-empty">No critical events in the last hour</div>
              ) : (
                auditErrors.map((e) => (
                  <div class="cmd-row" key={e.id}>
                    <div class="cmd-row-icon">📋</div>
                    <div class="cmd-row-main">
                      <div class="cmd-row-title">
                        <code style="font-size:12px">{e.action}</code>
                        {e.username ? ` · ${e.username}` : ""}
                      </div>
                      <div class="cmd-row-sub">{e.ip || "no IP"}</div>
                    </div>
                    <div class="cmd-row-time">{relativeTime(e.createdAt)}</div>
                  </div>
                ))
              )}
            </div>
          </div>

          {/* Quick links — full width */}
          <div class="cmd-panel cmd-grid-wide">
            <div class="cmd-panel-head">
              <span>Quick access</span>
            </div>
            <div class="cmd-links">
              {[
                ["/admin", "Dashboard"],
                ["/admin/ops", "Operations"],
                ["/admin/deploys", "Deploy log"],
                ["/admin/env-health", "Feature health"],
                ["/admin/diagnose", "AI diagnostics"],
                ["/admin/security", "Security"],
                ["/admin/users", "Users"],
                ["/admin/repos", "Repositories"],
                ["/admin/ai-costs", "AI costs"],
                ["/admin/autopilot", "Autopilot"],
                ["/admin/integrations", "Integrations"],
                ["/admin/growth", "User growth"],
                ["/admin/flags", "Site flags"],
                ["/admin/billing", "Billing"],
                ["/admin/digests", "Email digests"],
                ["/admin/sso", "SSO config"],
                ["/status", "Public status"],
              ].map(([href, label]) => (
                <a href={href} class="cmd-link" key={href}>
                  {label}
                </a>
              ))}
            </div>
          </div>
        </div>
      </div>
    </Layout>
  );
});

// ---------------------------------------------------------------------------
// Micro-Container Hosting — Phase 3 Market Moat
// Spawn/stop sovereign Bun processes per-repo for isolated environments.
// ---------------------------------------------------------------------------

interface SandboxEntry {
  repoSlug: string;
  pid: number;
  port: number;
  startedAt: Date;
  status: "running" | "stopped";
}

const sandboxRegistry = new Map<string, SandboxEntry>();
let nextSandboxPort = 4100;

function allocateSandboxPort(): number {
  return nextSandboxPort++;
}

app.post("/admin/command/sandbox/start", async (c) => {
  const body = await c.req.parseBody();
  const repoSlug = String(body.repoSlug ?? "").trim();
  if (!repoSlug || !/^[\w.-]+\/[\w.-]+$/.test(repoSlug)) {
    return c.json({ error: "Invalid repoSlug" }, 400);
  }
  if (sandboxRegistry.has(repoSlug)) {
    const entry = sandboxRegistry.get(repoSlug)!;
    if (entry.status === "running") {
      return c.json({ error: "Sandbox already running", pid: entry.pid, port: entry.port }, 409);
    }
  }
  const port = allocateSandboxPort();
  const proc = Bun.spawn(["bun", "run", "src/index.ts"], {
    env: { ...process.env, PORT: String(port), SANDBOX_REPO: repoSlug },
    stdout: "ignore",
    stderr: "ignore",
  });
  const pid = proc.pid;
  sandboxRegistry.set(repoSlug, { repoSlug, pid, port, startedAt: new Date(), status: "running" });
  return c.json({ ok: true, pid, port });
});

app.post("/admin/command/sandbox/stop", async (c) => {
  const body = await c.req.parseBody();
  const repoSlug = String(body.repoSlug ?? "").trim();
  const entry = sandboxRegistry.get(repoSlug);
  if (!entry || entry.status === "stopped") {
    return c.json({ error: "No running sandbox for that repo" }, 404);
  }
  try {
    process.kill(entry.pid, "SIGTERM");
  } catch {
    // Already dead — update status anyway
  }
  entry.status = "stopped";
  sandboxRegistry.set(repoSlug, entry);
  return c.json({ ok: true });
});

app.get("/admin/command/sandbox/list", (c) => {
  const entries = Array.from(sandboxRegistry.values());
  return c.json({ sandboxes: entries });
});

export default app;