Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesPull RequestsActionsSecurityInsightsSettings
✨ AI
More
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-diagnose.tsx19.0 KB · 596 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
/**
 * /admin/diagnose — comprehensive AI health scan.
 *
 * Single page the site admin opens to see, at a glance, every config knob
 * the platform depends on and whether it is wired up. Each row is one
 * check; status is green / yellow / red with a one-line "what to do".
 *
 * Categories covered:
 *   - Email delivery       (EMAIL_PROVIDER, RESEND_API_KEY)
 *   - AI                   (ANTHROPIC_API_KEY presence)
 *   - GateTest integration (URL + API key)
 *   - Service worker SHA   (BUILD_SHA pinned vs dev-stable fallback)
 *   - Database             (DATABASE_URL well-formed, latest migration applied)
 *   - Canonical URL        (APP_BASE_URL matches request host)
 *   - Self-host            (SELF_HOST_REPO declared + post-receive hook present)
 *   - Auto-merge           (branch_protection.enable_auto_merge for main)
 *   - Synthetic monitor    (any RED checks in last hour)
 *   - Email smoke          (POST /admin/diagnose/test-email fires a test)
 *
 * Gating: requireAuth + isSiteAdmin via the same gate() pattern as
 * /admin/ops + /admin/status. No data leaks to non-admins.
 */

import { Hono } from "hono";
import { eq, and, desc, gt } from "drizzle-orm";
import { readdir } from "fs/promises";
import { join } from "path";
import {
  branchProtection,
  repositories,
  syntheticChecks,
  users,
} from "../db/schema";
import { db } from "../db";
import { Layout } from "../views/layout";
import { softAuth } from "../middleware/auth";
import type { AuthEnv } from "../middleware/auth";
import { isSiteAdmin } from "../lib/admin";
import { config } from "../lib/config";
import { sendEmail } from "../lib/email";
import { latestMigration } from "../lib/post-deploy-smoke";

type CheckStatus = "green" | "yellow" | "red";

interface CheckResult {
  category: string;
  name: string;
  status: CheckStatus;
  detail: string;
  fix?: string;
}

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

async function gate(c: any): Promise<{ user: any } | Response> {
  const user = c.get("user");
  if (!user) return c.redirect("/login?next=/admin/diagnose");
  if (!(await isSiteAdmin(user.id))) {
    return c.html(
      <Layout title="Forbidden" user={user}>
        <div class="empty-state">
          <h2>403 — Not a site admin</h2>
          <p>You don't have permission to view this page.</p>
        </div>
      </Layout>,
      403
    );
  }
  return { user };
}

// ─── Individual checks ───────────────────────────────────────────────────

function checkEmail(): CheckResult {
  if (config.emailProvider !== "resend") {
    return {
      category: "Email",
      name: "Provider",
      status: "red",
      detail: `EMAIL_PROVIDER=${config.emailProvider} — verification + magic-link emails go to stderr, not inboxes.`,
      fix: "Set EMAIL_PROVIDER=resend in /etc/gluecron.env, then `systemctl restart gluecron`.",
    };
  }
  if (!config.resendApiKey) {
    return {
      category: "Email",
      name: "Provider",
      status: "red",
      detail: "EMAIL_PROVIDER=resend but RESEND_API_KEY is empty — every send will fail.",
      fix: "Add RESEND_API_KEY=re_xxx to /etc/gluecron.env, then restart.",
    };
  }
  return {
    category: "Email",
    name: "Provider",
    status: "green",
    detail: `Resend wired (from: ${config.emailFrom}). Use the test button below to confirm.`,
  };
}

function checkAnthropic(): CheckResult {
  if (!config.anthropicApiKey) {
    return {
      category: "AI",
      name: "Anthropic API key",
      status: "yellow",
      detail: "ANTHROPIC_API_KEY unset — AI PR review + AI deploy-failure analysis disabled.",
      fix: "Add ANTHROPIC_API_KEY=sk-ant-xxx to /etc/gluecron.env.",
    };
  }
  return {
    category: "AI",
    name: "Anthropic API key",
    status: "green",
    detail: `Key present (length ${config.anthropicApiKey.length}).`,
  };
}

function checkGateTest(): CheckResult {
  const hasUrl = !!process.env.GATETEST_URL;
  const hasKey = !!process.env.GATETEST_API_KEY;
  if (!hasUrl && !hasKey) {
    return {
      category: "GateTest",
      name: "Scanner integration",
      status: "yellow",
      detail: "Unconfigured — push-time GateTest scans skip silently.",
      fix: "Set GATETEST_URL + GATETEST_API_KEY in /etc/gluecron.env to enable per-push scans.",
    };
  }
  if (hasUrl && !hasKey) {
    return {
      category: "GateTest",
      name: "Scanner integration",
      status: "red",
      detail: "GATETEST_URL set but GATETEST_API_KEY empty — calls will 401.",
      fix: "Add GATETEST_API_KEY to /etc/gluecron.env.",
    };
  }
  return {
    category: "GateTest",
    name: "Scanner integration",
    status: "green",
    detail: `Configured — pushes POST to ${process.env.GATETEST_URL}.`,
  };
}

function checkBuildSha(): CheckResult {
  const sha = process.env.BUILD_SHA?.trim();
  if (sha) {
    return {
      category: "Deploy",
      name: "BUILD_SHA pinned",
      status: "green",
      detail: `${sha.slice(0, 12)} — service worker rotates per deploy.`,
    };
  }
  return {
    category: "Deploy",
    name: "BUILD_SHA pinned",
    status: "yellow",
    detail: "BUILD_SHA unset — falling back to dev-stable. Browsers won't see new deploys reflected in the SW cache.",
    fix: "Latest scripts/self-deploy.sh + hetzner-deploy.yml pin this automatically; trigger a deploy.",
  };
}

function checkAppBaseUrl(c: any): CheckResult {
  const expected = config.appBaseUrl;
  const host = c.req.header("host") || "";
  const proto =
    c.req.header("x-forwarded-proto") ||
    (c.req.url.startsWith("https://") ? "https" : "http");
  const actual = `${proto}://${host}`;
  if (!expected || expected === "http://localhost:3000") {
    return {
      category: "Config",
      name: "APP_BASE_URL canonical",
      status: "yellow",
      detail: `APP_BASE_URL is "${expected}" — outbound email links + WebAuthn origin will be wrong.`,
      fix: "Set APP_BASE_URL=https://gluecron.com in /etc/gluecron.env.",
    };
  }
  if (host && !expected.endsWith(host)) {
    return {
      category: "Config",
      name: "APP_BASE_URL canonical",
      status: "yellow",
      detail: `APP_BASE_URL=${expected} but request arrived at ${actual}. WebAuthn passkeys issued for one host can't be used at the other.`,
      fix: "Align APP_BASE_URL with the host you actually serve from.",
    };
  }
  return {
    category: "Config",
    name: "APP_BASE_URL canonical",
    status: "green",
    detail: expected,
  };
}

function checkDatabase(): CheckResult {
  const url = config.databaseUrl;
  if (!url) {
    return {
      category: "Database",
      name: "Connection string",
      status: "red",
      detail: "DATABASE_URL unset — every page that queries the DB will 500.",
      fix: "Set DATABASE_URL in /etc/gluecron.env.",
    };
  }
  let masked = url;
  try {
    const u = new URL(url);
    masked = `${u.protocol}//${u.username ? "***" : ""}@${u.host}${u.pathname}`;
  } catch {
    // unparseable
    return {
      category: "Database",
      name: "Connection string",
      status: "red",
      detail: "DATABASE_URL is not a valid URL.",
      fix: "Fix the URL format: postgres://user:pass@host:port/dbname",
    };
  }
  return {
    category: "Database",
    name: "Connection string",
    status: "green",
    detail: masked,
  };
}

async function checkMigrations(): Promise<CheckResult> {
  try {
    const drizzleDir = join(process.cwd(), "drizzle");
    const files = (await readdir(drizzleDir)).filter((f) => f.endsWith(".sql"));
    const latest = latestMigration(files);
    if (!latest) {
      return {
        category: "Database",
        name: "Migrations applied",
        status: "yellow",
        detail: "No migration files found in drizzle/.",
      };
    }
    const rows = (await db.execute(
      `SELECT name FROM _migrations ORDER BY name DESC LIMIT 1` as never
    )) as any;
    const list = rows?.rows ?? (Array.isArray(rows) ? rows : []);
    const applied: string | undefined = list[0]?.name;
    if (!applied) {
      return {
        category: "Database",
        name: "Migrations applied",
        status: "red",
        detail: "_migrations table is empty.",
        fix: "Run `bun run db:migrate` on the box.",
      };
    }
    if (applied !== latest) {
      return {
        category: "Database",
        name: "Migrations applied",
        status: "red",
        detail: `DB at ${applied}, drizzle/ has ${latest}.`,
        fix: "Run `bun run db:migrate` on the box, or redeploy (the workflow runs it).",
      };
    }
    return {
      category: "Database",
      name: "Migrations applied",
      status: "green",
      detail: `Latest: ${applied}`,
    };
  } catch (err) {
    return {
      category: "Database",
      name: "Migrations applied",
      status: "yellow",
      detail: `Couldn't read migration state: ${(err as Error).message.slice(0, 100)}`,
    };
  }
}

async function checkAutoMerge(): Promise<CheckResult> {
  try {
    const [owner] = await db
      .select({ id: users.id })
      .from(users)
      .where(eq(users.username, "ccantynz"))
      .limit(1);
    if (!owner) {
      return {
        category: "Auto-merge",
        name: "main protection",
        status: "yellow",
        detail: "Owner user 'ccantynz' not found.",
      };
    }
    const [repo] = await db
      .select({ id: repositories.id })
      .from(repositories)
      .where(
        and(
          eq(repositories.ownerId, owner.id),
          eq(repositories.name, "Gluecron.com")
        )
      )
      .limit(1);
    if (!repo) {
      return {
        category: "Auto-merge",
        name: "main protection",
        status: "yellow",
        detail: "Repository row for ccantynz/Gluecron.com not found.",
      };
    }
    const [bp] = await db
      .select({ enableAutoMerge: branchProtection.enableAutoMerge })
      .from(branchProtection)
      .where(
        and(
          eq(branchProtection.repositoryId, repo.id),
          eq(branchProtection.pattern, "main")
        )
      )
      .limit(1);
    if (!bp) {
      return {
        category: "Auto-merge",
        name: "main protection",
        status: "yellow",
        detail: "No branch_protection row for main yet.",
        fix: "Visit /ccantynz/Gluecron.com/gates/protection to configure.",
      };
    }
    return {
      category: "Auto-merge",
      name: "main protection",
      status: bp.enableAutoMerge ? "green" : "yellow",
      detail: bp.enableAutoMerge
        ? "Auto-merge ENABLED on main."
        : "Auto-merge DISABLED on main.",
      fix: bp.enableAutoMerge
        ? undefined
        : "Visit /admin/ops to enable.",
    };
  } catch (err) {
    return {
      category: "Auto-merge",
      name: "main protection",
      status: "yellow",
      detail: `Couldn't read: ${(err as Error).message.slice(0, 100)}`,
    };
  }
}

async function checkSyntheticMonitor(): Promise<CheckResult> {
  try {
    const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000);
    const reds = await db
      .select({ name: syntheticChecks.checkName })
      .from(syntheticChecks)
      .where(
        and(
          eq(syntheticChecks.status, "red"),
          gt(syntheticChecks.checkedAt, oneHourAgo)
        )
      )
      .orderBy(desc(syntheticChecks.checkedAt))
      .limit(10);
    if (reds.length === 0) {
      return {
        category: "Monitor",
        name: "Synthetic checks (1h)",
        status: "green",
        detail: "All synthetic checks green in the last hour.",
      };
    }
    const names = Array.from(new Set(reds.map((r) => r.name))).slice(0, 5);
    return {
      category: "Monitor",
      name: "Synthetic checks (1h)",
      status: "red",
      detail: `Red in last hour: ${names.join(", ")}.`,
      fix: "Open /admin/status for the full row table.",
    };
  } catch (err) {
    return {
      category: "Monitor",
      name: "Synthetic checks (1h)",
      status: "yellow",
      detail: `Couldn't read: ${(err as Error).message.slice(0, 100)}`,
    };
  }
}

function checkSelfHost(): CheckResult {
  const repo = process.env.SELF_HOST_REPO;
  if (!repo) {
    return {
      category: "Self-host",
      name: "Bootstrap",
      status: "yellow",
      detail: "SELF_HOST_REPO unset — pushes to this repo don't trigger self-deploy.",
      fix: "Run scripts/self-host-bootstrap.ts on the box and add SELF_HOST_REPO=ccantynz/Gluecron.com to /etc/gluecron.env.",
    };
  }
  return {
    category: "Self-host",
    name: "Bootstrap",
    status: "green",
    detail: `Self-hosting ${repo} — push to main fires self-deploy.sh.`,
  };
}

// ─── Page handler ────────────────────────────────────────────────────────

function pill(status: CheckStatus): any {
  const map: Record<CheckStatus, { bg: string; fg: string; label: string }> = {
    green: { bg: "rgba(52,211,153,0.16)", fg: "#34d399", label: "✓ OK" },
    yellow: { bg: "rgba(245,158,11,0.16)", fg: "#f59e0b", label: "! WARN" },
    red: { bg: "rgba(248,113,113,0.16)", fg: "#f87171", label: "× FAIL" },
  };
  const s = map[status];
  return (
    <span
      style={`display:inline-flex;align-items:center;padding:2px 10px;border-radius:999px;font-size:12px;font-weight:600;background:${s.bg};color:${s.fg};white-space:nowrap`}
    >
      {s.label}
    </span>
  );
}

diagnose.get("/admin/diagnose", async (c) => {
  const g = await gate(c);
  if (g instanceof Response) return g;
  const { user } = g;

  const results: CheckResult[] = [
    checkEmail(),
    checkAnthropic(),
    checkGateTest(),
    checkBuildSha(),
    checkAppBaseUrl(c),
    checkDatabase(),
    await checkMigrations(),
    await checkAutoMerge(),
    await checkSyntheticMonitor(),
    checkSelfHost(),
  ];

  const counts = {
    green: results.filter((r) => r.status === "green").length,
    yellow: results.filter((r) => r.status === "yellow").length,
    red: results.filter((r) => r.status === "red").length,
  };
  const headline =
    counts.red > 0
      ? `${counts.red} failing`
      : counts.yellow > 0
        ? `${counts.yellow} needs attention`
        : "All green";
  const headlineColor =
    counts.red > 0
      ? "var(--red, #cf222e)"
      : counts.yellow > 0
        ? "#d97706"
        : "var(--green, #2da44e)";

  const flash = c.req.query("test_email");

  return c.html(
    <Layout title="Diagnose — admin" user={user}>
      <div style="max-width:920px;margin:0 auto;padding:var(--space-5) var(--space-3)">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:var(--space-3)">
          <h1 style="margin:0">Diagnose</h1>
          <a href="/admin" class="btn btn-sm">
            Back to admin
          </a>
        </div>
        <p style="color:var(--text-muted);margin-bottom:var(--space-4)">
          Read-only health scan of every config knob the platform depends on.
          One row per check. Green = wired, yellow = degraded, red = broken.
        </p>

        <div
          style={`background:var(--bg-elevated);border:1px solid var(--border);border-radius:8px;padding:var(--space-3) var(--space-4);margin-bottom:var(--space-4);display:flex;align-items:center;gap:var(--space-3)`}
        >
          <span
            style={`display:inline-block;width:14px;height:14px;border-radius:50%;background:${headlineColor}`}
          />
          <strong style="font-size:18px">{headline}</strong>
          <span style="color:var(--text-muted);font-size:13px">
            {counts.green} green · {counts.yellow} warn · {counts.red} fail
          </span>
        </div>

        {flash && (
          <div
            class={flash === "ok" ? "banner" : "auth-error"}
            style="margin-bottom:var(--space-4)"
          >
            {flash === "ok"
              ? "Test email dispatched. If the provider is 'log' you'll see it in journalctl, not your inbox."
              : `Test email failed: ${decodeURIComponent(flash)}`}
          </div>
        )}

        <div
          style="background:var(--bg-elevated);border:1px solid var(--border);border-radius:8px;overflow:hidden;margin-bottom:var(--space-4)"
        >
          {results.map((r, i) => (
            <div
              style={`padding:var(--space-3) var(--space-4);${i < results.length - 1 ? "border-bottom:1px solid var(--border);" : ""}display:grid;grid-template-columns:120px 80px 1fr;gap:var(--space-3);align-items:start`}
            >
              <div>
                <div style="font-size:11px;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.04em">
                  {r.category}
                </div>
                <div style="font-weight:600;font-size:14px;margin-top:2px">
                  {r.name}
                </div>
              </div>
              <div>{pill(r.status)}</div>
              <div>
                <div style="font-size:13px;line-height:1.45">{r.detail}</div>
                {r.fix && (
                  <div
                    style="font-size:12px;color:var(--text-muted);margin-top:4px;line-height:1.4"
                  >
                    → {r.fix}
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>

        <div
          style="background:var(--bg-elevated);border:1px solid var(--border);border-radius:8px;padding:var(--space-3) var(--space-4)"
        >
          <h3
            style="margin:0 0 var(--space-2) 0;font-size:14px;letter-spacing:0.04em;text-transform:uppercase;color:var(--text-muted)"
          >
            Test email delivery
          </h3>
          <p style="font-size:13px;color:var(--text-muted);margin:0 0 var(--space-3) 0">
            Fires a one-line test email to <strong>{user.email}</strong> using
            the configured provider. If EMAIL_PROVIDER=log it appears in
            journalctl; if resend, in your inbox in &lt;30s.
          </p>
          <form method="post" action="/admin/diagnose/test-email" style="margin:0">
            <input
              type="hidden"
              name="_csrf"
              value={(c.get("csrfToken") as string | undefined) || ""}
            />
            <button type="submit" class="btn btn-sm btn-primary">
              Send test email
            </button>
          </form>
        </div>
      </div>
    </Layout>
  );
});

diagnose.post("/admin/diagnose/test-email", async (c) => {
  const g = await gate(c);
  if (g instanceof Response) return g;
  const { user } = g;
  if (!user.email) {
    return c.redirect(
      `/admin/diagnose?test_email=${encodeURIComponent("admin has no email on record")}`
    );
  }
  const stamp = new Date().toISOString();
  const result = await sendEmail({
    to: user.email,
    subject: "Gluecron — diagnose test email",
    text:
      `This is a test email from /admin/diagnose at ${stamp}.\n\n` +
      `If you received this in your inbox, EMAIL_PROVIDER=resend is wired correctly.\n` +
      `If you only see it in journalctl, EMAIL_PROVIDER is still 'log'.\n`,
  });
  if (!result.ok) {
    return c.redirect(
      `/admin/diagnose?test_email=${encodeURIComponent(result.error || result.skipped || "unknown failure")}`
    );
  }
  return c.redirect("/admin/diagnose?test_email=ok");
});

export default diagnose;