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
events.ts22.3 KB · 706 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
/**
 * Inbound deploy-event receiver for Crontech (Signal Bus P1 — E3/E4).
 *
 * Wire contract reference: chat-defined spec for Crontech → Gluecron deploy
 * events. Gluecron's OWN copy per HTTP-only coupling rule — do NOT import any
 * types from Crontech. If the contract is renegotiated, update this comment
 * and the validation below in lock-step.
 *
 *   POST  /api/events/deploy
 *   Authorization: Bearer ${CRONTECH_EVENT_TOKEN}
 *   Content-Type: application/json
 *
 *   {
 *     "event":         "deploy.succeeded" | "deploy.failed",
 *     "eventId":       "<uuid-v4>",           // idempotency key
 *     "repository":    "owner/name",
 *     "sha":           "<40-hex>",
 *     "environment":   "production",
 *     "deploymentId":  "<crontech-id>",
 *     "durationMs":    <int>,                 // optional
 *     "errorCategory": "build|runtime|timeout|config",  // required on failed
 *     "errorSummary":  "<string ≤500>",                 // required on failed
 *     "logsUrl":       "<string>",            // optional
 *     "timestamp":     "<ISO-8601>"
 *   }
 *
 *   → 200 { ok: true, duplicate: false }
 *   → 200 { ok: true, duplicate: true }
 *   → 401 invalid bearer
 *   → 400 malformed payload
 *
 * Idempotency: an incoming `eventId` is first looked up in `processed_events`.
 * On hit we return { duplicate: true } immediately — no side-effects. On miss
 * we INSERT the idempotency record BEFORE performing the side-effect update so
 * that a retry after a crash between steps sees the record and short-circuits.
 *
 * Side-effect: look up the matching `deployments` row by
 * (repository_id, commit_sha, environment) — `deployments` has no
 * `crontech_deployment_id` column so we key off the tuple that
 * `triggerCrontechDeploy` writes on the way out.
 *
 *   E3 deploy.succeeded → status='success',  completedAt=now
 *   E4 deploy.failed    → status='failed',   blockedReason=errorSummary,
 *                         completedAt=now, notify(owner, 'deploy_failed')
 */

import { Hono } from "hono";
import { and, desc, eq } from "drizzle-orm";
import { timingSafeEqual } from "crypto";
import { db } from "../db";
import { deployments, repositories, users } from "../db/schema";
import { processedEvents } from "../db/schema-events";
import { platformDeploys } from "../db/schema-deploys";
import { notify } from "../lib/notify";
import { publish } from "../lib/sse";

const events = new Hono();

// ---------------------------------------------------------------------------
// Bearer auth — timing-safe comparison against CRONTECH_EVENT_TOKEN.
// ---------------------------------------------------------------------------

function constantTimeEq(a: string, b: string): boolean {
  const A = Buffer.from(a);
  const B = Buffer.from(b);
  if (A.length !== B.length) return false;
  try {
    return timingSafeEqual(A, B);
  } catch {
    return false;
  }
}

function verifyBearer(c: any): { ok: boolean; error?: string } {
  const expected = process.env.CRONTECH_EVENT_TOKEN || "";
  if (!expected) {
    // Refuse by default — an unset secret must NOT allow anonymous writes.
    return {
      ok: false,
      error:
        "Event endpoint not configured: set CRONTECH_EVENT_TOKEN in the environment",
    };
  }
  const auth = c.req.header("authorization") || "";
  if (!auth.startsWith("Bearer ")) {
    return { ok: false, error: "Missing Bearer token" };
  }
  const token = auth.slice(7).trim();
  if (!constantTimeEq(token, expected)) {
    return { ok: false, error: "Invalid bearer token" };
  }
  return { ok: true };
}

// ---------------------------------------------------------------------------
// Payload validation — no zod in this repo, use manual checks mirroring the
// existing hooks.ts style. Keep error messages specific enough to diagnose a
// mis-built emitter without leaking internals.
// ---------------------------------------------------------------------------

type DeployEvent = "deploy.succeeded" | "deploy.failed";
type ErrorCategory = "build" | "runtime" | "timeout" | "config";

interface DeployEventPayload {
  event: DeployEvent;
  eventId: string;
  repository: string;
  sha: string;
  environment: string;
  deploymentId: string;
  durationMs?: number;
  errorCategory?: ErrorCategory;
  errorSummary?: string;
  logsUrl?: string;
  timestamp: string;
}

const UUID_V4_RE =
  /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
const SHA_RE = /^[0-9a-f]{40}$/i;
const VALID_EVENTS: ReadonlySet<string> = new Set([
  "deploy.succeeded",
  "deploy.failed",
]);
const VALID_CATEGORIES: ReadonlySet<string> = new Set([
  "build",
  "runtime",
  "timeout",
  "config",
]);

function validatePayload(raw: unknown): {
  ok: true;
  payload: DeployEventPayload;
} | { ok: false; error: string } {
  if (!raw || typeof raw !== "object") {
    return { ok: false, error: "Body must be a JSON object" };
  }
  const p = raw as Record<string, unknown>;

  if (typeof p.event !== "string" || !VALID_EVENTS.has(p.event)) {
    return {
      ok: false,
      error: "event must be 'deploy.succeeded' or 'deploy.failed'",
    };
  }
  if (typeof p.eventId !== "string" || !UUID_V4_RE.test(p.eventId)) {
    return { ok: false, error: "eventId must be a uuid-v4 string" };
  }
  if (typeof p.repository !== "string" || !p.repository.includes("/")) {
    return { ok: false, error: "repository must be '<owner>/<name>'" };
  }
  if (typeof p.sha !== "string" || !SHA_RE.test(p.sha)) {
    return { ok: false, error: "sha must be a 40-hex commit id" };
  }
  if (typeof p.environment !== "string" || p.environment.length === 0) {
    return { ok: false, error: "environment must be a non-empty string" };
  }
  if (typeof p.deploymentId !== "string" || p.deploymentId.length === 0) {
    return { ok: false, error: "deploymentId must be a non-empty string" };
  }
  if (typeof p.timestamp !== "string" || Number.isNaN(Date.parse(p.timestamp))) {
    return { ok: false, error: "timestamp must be an ISO-8601 string" };
  }
  if (p.durationMs !== undefined) {
    if (
      typeof p.durationMs !== "number" ||
      !Number.isFinite(p.durationMs) ||
      p.durationMs < 0
    ) {
      return { ok: false, error: "durationMs must be a non-negative number" };
    }
  }
  if (p.logsUrl !== undefined && typeof p.logsUrl !== "string") {
    return { ok: false, error: "logsUrl must be a string when present" };
  }

  if (p.event === "deploy.failed") {
    if (
      typeof p.errorCategory !== "string" ||
      !VALID_CATEGORIES.has(p.errorCategory)
    ) {
      return {
        ok: false,
        error:
          "errorCategory is required for deploy.failed and must be one of build|runtime|timeout|config",
      };
    }
    if (
      typeof p.errorSummary !== "string" ||
      p.errorSummary.length === 0 ||
      p.errorSummary.length > 500
    ) {
      return {
        ok: false,
        error:
          "errorSummary is required for deploy.failed and must be 1-500 chars",
      };
    }
  }

  return { ok: true, payload: p as unknown as DeployEventPayload };
}

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

async function resolveRepo(
  full: string
): Promise<{ id: string; ownerId: string } | null> {
  if (!full.includes("/")) return null;
  const [owner, name] = full.split("/", 2);
  try {
    const [row] = await db
      .select({
        id: repositories.id,
        ownerId: repositories.ownerId,
      })
      .from(repositories)
      .innerJoin(users, eq(repositories.ownerId, users.id))
      .where(and(eq(users.username, owner), eq(repositories.name, name)))
      .limit(1);
    return row || null;
  } catch {
    return null;
  }
}

async function findTargetDeployment(
  repositoryId: string,
  commitSha: string,
  environment: string
): Promise<{ id: string } | null> {
  try {
    const [row] = await db
      .select({ id: deployments.id })
      .from(deployments)
      .where(
        and(
          eq(deployments.repositoryId, repositoryId),
          eq(deployments.commitSha, commitSha),
          eq(deployments.environment, environment)
        )
      )
      .orderBy(desc(deployments.createdAt))
      .limit(1);
    return row || null;
  } catch {
    return null;
  }
}

// ---------------------------------------------------------------------------
// POST /api/events/deploy
// ---------------------------------------------------------------------------

events.post("/deploy", async (c) => {
  const auth = verifyBearer(c);
  if (!auth.ok) {
    return c.json({ ok: false, error: auth.error || "Unauthorized" }, 401);
  }

  let raw: unknown;
  try {
    raw = await c.req.json();
  } catch {
    return c.json({ ok: false, error: "Invalid JSON body" }, 400);
  }

  const validated = validatePayload(raw);
  if (!validated.ok) {
    return c.json({ ok: false, error: validated.error }, 400);
  }
  const payload = validated.payload;

  // --- Idempotency check ---------------------------------------------------
  // If we've already processed this eventId, return duplicate:true without
  // firing any side-effects.
  try {
    const [existing] = await db
      .select({ id: processedEvents.id })
      .from(processedEvents)
      .where(eq(processedEvents.eventId, payload.eventId))
      .limit(1);
    if (existing) {
      return c.json({ ok: true, duplicate: true });
    }
  } catch (err) {
    console.error("[events/deploy] idempotency lookup failed:", err);
    // Fall through — better to process than to wedge on a transient DB blip.
  }

  // --- Record the idempotency token BEFORE side-effects --------------------
  // Race: two simultaneous deliveries of the same eventId. The UNIQUE
  // constraint on event_id makes the losing insert throw; we catch that and
  // return duplicate:true to keep behaviour stable.
  try {
    await db.insert(processedEvents).values({
      eventId: payload.eventId,
      eventType: payload.event,
      source: "crontech",
      payload: payload as unknown as Record<string, unknown>,
    });
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    if (msg.includes("unique") || msg.includes("duplicate")) {
      return c.json({ ok: true, duplicate: true });
    }
    console.error("[events/deploy] processed_events insert failed:", err);
    return c.json({ ok: false, error: "Failed to persist event" }, 500);
  }

  // --- Side-effect: update the matching deployments row --------------------
  const repo = await resolveRepo(payload.repository);
  if (!repo) {
    // The idempotency row is already committed; we accept the event so we
    // don't invite infinite retries for a repo that genuinely doesn't exist
    // on this side of the wire. Log for operator follow-up.
    console.warn(
      `[events/deploy] unknown repository ${payload.repository} — event ${payload.eventId} accepted but no deployment update applied`
    );
    return c.json({ ok: true, duplicate: false });
  }

  const target = await findTargetDeployment(
    repo.id,
    payload.sha,
    payload.environment
  );

  if (target) {
    try {
      if (payload.event === "deploy.succeeded") {
        await db
          .update(deployments)
          .set({
            status: "success",
            completedAt: new Date(),
          })
          .where(eq(deployments.id, target.id));
      } else {
        await db
          .update(deployments)
          .set({
            status: "failed",
            blockedReason: payload.errorSummary,
            completedAt: new Date(),
          })
          .where(eq(deployments.id, target.id));
      }
    } catch (err) {
      console.error("[events/deploy] deployments update failed:", err);
    }
  } else {
    console.warn(
      `[events/deploy] no deployments row found for ${payload.repository}@${payload.sha} env=${payload.environment}`
    );
  }

  // --- On failure: notify the repo owner ----------------------------------
  if (payload.event === "deploy.failed") {
    try {
      await notify(repo.ownerId, {
        kind: "deploy_failed",
        title: `Deploy failed on ${payload.repository}`,
        body:
          payload.errorSummary ||
          `Crontech reported deploy failure (${payload.errorCategory || "unknown"})`,
        url: payload.logsUrl,
        repositoryId: repo.id,
      });
    } catch (err) {
      console.error("[events/deploy] notify failed:", err);
    }
  }

  return c.json({ ok: true, duplicate: false });
});

// ---------------------------------------------------------------------------
// Block N3 — Platform deploy timeline ingest.
//
// These endpoints are FOR THIS SITE. The Hetzner deploy workflow posts a
// 'started' event when SSH begins and a 'finished' event on success/failure.
// They power the admin status pill in `src/views/layout.tsx` and the
// `/admin/deploys` timeline. NEW endpoints — they do NOT touch the Crontech
// `/deploy` receiver above (which §4.6 locks the semantics of).
//
//   POST /api/events/deploy/started
//     Authorization: Bearer ${DEPLOY_EVENT_TOKEN}
//     Body: { sha: "<40-hex>", run_id: "<string>", source: "<string>" }
//     200 { ok: true, duplicate: false | true }
//     401 invalid bearer
//     400 malformed payload
//
//   POST /api/events/deploy/finished
//     Authorization: Bearer ${DEPLOY_EVENT_TOKEN}
//     Body: { run_id, status: "succeeded"|"failed",
//             duration_ms?: number, error?: string }
//
// Idempotency: keyed on run_id via the UNIQUE constraint in migration 0046.
// A duplicate 'started' POST is a no-op. A 'finished' POST without a prior
// 'started' INSERTs a fresh row (so the timeline still records the deploy
// even if the started-step silently dropped its packet).
// ---------------------------------------------------------------------------

const SHORT_SHA_RE = /^[0-9a-f]{7,64}$/i;
const VALID_DEPLOY_STATUS: ReadonlySet<string> = new Set([
  "succeeded",
  "failed",
]);

function verifyDeployBearer(c: any): { ok: boolean; error?: string } {
  const expected = process.env.DEPLOY_EVENT_TOKEN || "";
  if (!expected) {
    return {
      ok: false,
      error:
        "Deploy event endpoint not configured: set DEPLOY_EVENT_TOKEN in the environment",
    };
  }
  const auth = c.req.header("authorization") || "";
  if (!auth.startsWith("Bearer ")) {
    return { ok: false, error: "Missing Bearer token" };
  }
  const token = auth.slice(7).trim();
  if (!constantTimeEq(token, expected)) {
    return { ok: false, error: "Invalid bearer token" };
  }
  return { ok: true };
}

interface DeployStartedPayload {
  sha: string;
  run_id: string;
  source: string;
}

interface DeployFinishedPayload {
  run_id: string;
  sha?: string;
  status: "succeeded" | "failed";
  duration_ms?: number;
  error?: string;
}

function validateStarted(raw: unknown):
  | { ok: true; payload: DeployStartedPayload }
  | { ok: false; error: string } {
  if (!raw || typeof raw !== "object") {
    return { ok: false, error: "Body must be a JSON object" };
  }
  const p = raw as Record<string, unknown>;
  if (typeof p.sha !== "string" || !SHORT_SHA_RE.test(p.sha)) {
    return { ok: false, error: "sha must be a hex commit id (7-64 chars)" };
  }
  if (typeof p.run_id !== "string" || p.run_id.length === 0 || p.run_id.length > 128) {
    return { ok: false, error: "run_id must be a non-empty string (≤128 chars)" };
  }
  if (typeof p.source !== "string" || p.source.length === 0 || p.source.length > 64) {
    return { ok: false, error: "source must be a non-empty string (≤64 chars)" };
  }
  return {
    ok: true,
    payload: { sha: p.sha, run_id: p.run_id, source: p.source },
  };
}

function validateFinished(raw: unknown):
  | { ok: true; payload: DeployFinishedPayload }
  | { ok: false; error: string } {
  if (!raw || typeof raw !== "object") {
    return { ok: false, error: "Body must be a JSON object" };
  }
  const p = raw as Record<string, unknown>;
  if (typeof p.run_id !== "string" || p.run_id.length === 0 || p.run_id.length > 128) {
    return { ok: false, error: "run_id must be a non-empty string (≤128 chars)" };
  }
  if (typeof p.status !== "string" || !VALID_DEPLOY_STATUS.has(p.status)) {
    return {
      ok: false,
      error: "status must be 'succeeded' or 'failed'",
    };
  }
  if (p.sha !== undefined && (typeof p.sha !== "string" || !SHORT_SHA_RE.test(p.sha))) {
    return { ok: false, error: "sha must be a hex commit id when provided" };
  }
  if (p.duration_ms !== undefined) {
    if (
      typeof p.duration_ms !== "number" ||
      !Number.isFinite(p.duration_ms) ||
      p.duration_ms < 0
    ) {
      return { ok: false, error: "duration_ms must be a non-negative number" };
    }
  }
  if (p.error !== undefined && typeof p.error !== "string") {
    return { ok: false, error: "error must be a string when provided" };
  }
  return {
    ok: true,
    payload: {
      run_id: p.run_id,
      sha: typeof p.sha === "string" ? p.sha : undefined,
      status: p.status as "succeeded" | "failed",
      duration_ms:
        typeof p.duration_ms === "number" ? p.duration_ms : undefined,
      // Cap error text at 8 KB so a misbehaving emitter can't blow up
      // the DB row (the workflow already truncates to 1 KB on its end).
      error:
        typeof p.error === "string" ? p.error.slice(0, 8 * 1024) : undefined,
    },
  };
}

const PLATFORM_DEPLOYS_TOPIC = "platform:deploys";

events.post("/deploy/started", async (c) => {
  const auth = verifyDeployBearer(c);
  if (!auth.ok) {
    return c.json({ ok: false, error: auth.error || "Unauthorized" }, 401);
  }

  let raw: unknown;
  try {
    raw = await c.req.json();
  } catch {
    return c.json({ ok: false, error: "Invalid JSON body" }, 400);
  }

  const validated = validateStarted(raw);
  if (!validated.ok) {
    return c.json({ ok: false, error: validated.error }, 400);
  }
  const { sha, run_id, source } = validated.payload;

  // INSERT-or-no-op on UNIQUE(run_id). If the row already exists we treat the
  // call as a duplicate and don't republish — the original publish carried
  // the canonical started-at timestamp.
  let inserted: { id: string; startedAt: Date } | null = null;
  try {
    const rows = await db
      .insert(platformDeploys)
      .values({
        runId: run_id,
        sha,
        source,
        status: "in_progress",
      })
      .onConflictDoNothing({ target: platformDeploys.runId })
      .returning({ id: platformDeploys.id, startedAt: platformDeploys.startedAt });
    inserted = rows[0] ?? null;
  } catch (err) {
    console.error("[events/deploy/started] insert failed:", err);
    return c.json({ ok: false, error: "Failed to persist deploy event" }, 500);
  }

  if (!inserted) {
    return c.json({ ok: true, duplicate: true });
  }

  publish(PLATFORM_DEPLOYS_TOPIC, {
    event: "deploy.started",
    data: {
      id: inserted.id,
      run_id,
      sha,
      source,
      status: "in_progress",
      started_at: inserted.startedAt.toISOString(),
    },
  });

  return c.json({ ok: true, duplicate: false });
});

events.post("/deploy/finished", async (c) => {
  const auth = verifyDeployBearer(c);
  if (!auth.ok) {
    return c.json({ ok: false, error: auth.error || "Unauthorized" }, 401);
  }

  let raw: unknown;
  try {
    raw = await c.req.json();
  } catch {
    return c.json({ ok: false, error: "Invalid JSON body" }, 400);
  }

  const validated = validateFinished(raw);
  if (!validated.ok) {
    return c.json({ ok: false, error: validated.error }, 400);
  }
  const payload = validated.payload;

  const finishedAt = new Date();

  let row:
    | {
        id: string;
        runId: string;
        sha: string;
        source: string;
        status: string;
        startedAt: Date;
        finishedAt: Date | null;
        durationMs: number | null;
        error: string | null;
      }
    | null = null;

  try {
    const updated = await db
      .update(platformDeploys)
      .set({
        status: payload.status,
        finishedAt,
        durationMs: payload.duration_ms ?? null,
        error: payload.error ?? null,
      })
      .where(eq(platformDeploys.runId, payload.run_id))
      .returning({
        id: platformDeploys.id,
        runId: platformDeploys.runId,
        sha: platformDeploys.sha,
        source: platformDeploys.source,
        status: platformDeploys.status,
        startedAt: platformDeploys.startedAt,
        finishedAt: platformDeploys.finishedAt,
        durationMs: platformDeploys.durationMs,
        error: platformDeploys.error,
      });
    row = updated[0] ?? null;
  } catch (err) {
    console.error("[events/deploy/finished] update failed:", err);
    return c.json({ ok: false, error: "Failed to persist deploy event" }, 500);
  }

  // No matching started row — record a finished-only entry so the timeline
  // still reflects the deploy. Source/sha fall back to defaults; this is the
  // "started packet got dropped" recovery path.
  if (!row) {
    try {
      const inserted = await db
        .insert(platformDeploys)
        .values({
          runId: payload.run_id,
          sha: payload.sha ?? "unknown",
          source: "hetzner-deploy",
          status: payload.status,
          finishedAt,
          durationMs: payload.duration_ms ?? null,
          error: payload.error ?? null,
        })
        .returning({
          id: platformDeploys.id,
          runId: platformDeploys.runId,
          sha: platformDeploys.sha,
          source: platformDeploys.source,
          status: platformDeploys.status,
          startedAt: platformDeploys.startedAt,
          finishedAt: platformDeploys.finishedAt,
          durationMs: platformDeploys.durationMs,
          error: platformDeploys.error,
        });
      row = inserted[0] ?? null;
    } catch (err) {
      console.error("[events/deploy/finished] backfill insert failed:", err);
      return c.json({ ok: false, error: "Failed to persist deploy event" }, 500);
    }
  }

  if (row) {
    publish(PLATFORM_DEPLOYS_TOPIC, {
      event: "deploy.finished",
      data: {
        id: row.id,
        run_id: row.runId,
        sha: row.sha,
        source: row.source,
        status: row.status,
        started_at: row.startedAt.toISOString(),
        finished_at: row.finishedAt ? row.finishedAt.toISOString() : null,
        duration_ms: row.durationMs,
        error: row.error,
      },
    });
  }

  return c.json({ ok: true });
});

// Test-only access for unit tests that want to exercise helpers directly.
export const __test = {
  constantTimeEq,
  validatePayload,
  resolveRepo,
  findTargetDeployment,
  validateStarted,
  validateFinished,
  verifyDeployBearer,
  PLATFORM_DEPLOYS_TOPIC,
};

export default events;