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
hooks.ts21.5 KB · 714 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
/**
 * Inbound API hooks — endpoints that external systems (GateTest, CI runners,
 * Crontech deploy) call into to report async results.
 *
 * Security: every hook is authenticated via a shared-secret Bearer token OR
 * HMAC signature over the raw body. Configure secrets via env vars:
 *   GATETEST_CALLBACK_SECRET   — bearer token GateTest must present
 *   GATETEST_HMAC_SECRET       — optional HMAC-SHA256 secret over the raw body
 *
 * Endpoints:
 *   POST /api/hooks/gatetest         — GateTest scan result callback
 *   POST /api/hooks/gatetest/status  — periodic status / heartbeat (optional)
 *
 * The GateTest service should POST JSON of shape:
 *   {
 *     "repository": "owner/repo",
 *     "sha": "<full-commit-sha>",
 *     "ref": "refs/heads/main",
 *     "pullRequestNumber": 42,          // optional
 *     "status": "passed" | "failed" | "error",
 *     "summary": "12 tests passed, 0 failed",
 *     "details": { ... }                // optional, persisted as JSON
 *   }
 *
 * Response: 200 OK with {ok:true, gateRunId} on success, 401 on auth failure,
 * 400 on malformed payload, 404 if the repo is unknown.
 */

import { Hono } from "hono";
import { and, desc, eq } from "drizzle-orm";
import { createHmac, timingSafeEqual } from "crypto";
import { db } from "../db";
import {
  apiTokens,
  gateRuns,
  prComments,
  pullRequests,
  repositories,
  users,
  flywheelTelemetry,
} from "../db/schema";
import { notify, audit } from "../lib/notify";
import {
  generatePatchForGateTestFinding,
  severityAtOrAboveMedium,
  type GateTestFinding,
} from "../lib/ai-patch-generator";
import { triggerCiAutofix, applyAutofix } from "../lib/ci-autofix";
import { config } from "../lib/config";

const hooks = new Hono();

/**
 * Best-effort extraction of an array of GateTest findings from a
 * webhook payload's `details` blob. GateTest's schema isn't pinned in
 * code yet, so we accept a handful of common shapes:
 *   - `details.findings: [...]`
 *   - `details.issues:   [...]`
 *   - `details.results:  [...]`
 *   - `details:          [...]` (raw array)
 */
function extractFindings(details: unknown): GateTestFinding[] {
  if (!details) return [];
  if (Array.isArray(details)) return details as GateTestFinding[];
  if (typeof details === "object") {
    const d = details as Record<string, unknown>;
    for (const key of ["findings", "issues", "results", "violations"]) {
      const v = d[key];
      if (Array.isArray(v)) return v as GateTestFinding[];
    }
  }
  return [];
}

interface GateTestPayload {
  repository?: string;
  sha?: string;
  ref?: string;
  pullRequestNumber?: number;
  status?: "passed" | "failed" | "error" | "success";
  summary?: string;
  details?: unknown;
  durationMs?: number;
}

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 verifyGateTestAuth(c: any, rawBody: string): { ok: boolean; error?: string } {
  const bearerSecret = process.env.GATETEST_CALLBACK_SECRET || "";
  const hmacSecret = process.env.GATETEST_HMAC_SECRET || "";

  // If no secret is configured, refuse by default — do NOT allow anonymous writes.
  if (!bearerSecret && !hmacSecret) {
    return {
      ok: false,
      error:
        "Callback endpoint not configured: set GATETEST_CALLBACK_SECRET or GATETEST_HMAC_SECRET",
    };
  }

  // Bearer auth (simpler, preferred for server-to-server)
  if (bearerSecret) {
    const auth = c.req.header("authorization") || "";
    if (auth.startsWith("Bearer ")) {
      const token = auth.slice(7).trim();
      if (constantTimeEq(token, bearerSecret)) return { ok: true };
    }
    // Alternative header for tools that don't send Authorization
    const xTok = c.req.header("x-gatetest-token") || "";
    if (xTok && constantTimeEq(xTok, bearerSecret)) return { ok: true };
  }

  // HMAC signature over the raw body
  if (hmacSecret) {
    const sigHeader =
      c.req.header("x-gatetest-signature") ||
      c.req.header("x-signature-sha256") ||
      "";
    if (sigHeader) {
      const expected =
        "sha256=" +
        createHmac("sha256", hmacSecret).update(rawBody).digest("hex");
      if (constantTimeEq(sigHeader, expected)) return { ok: true };
    }
  }

  return { ok: false, error: "Invalid or missing GateTest credentials" };
}

async function resolveRepo(full: string): Promise<{ id: string; ownerId: string; name: string } | null> {
  if (!full || !full.includes("/")) return null;
  const [owner, name] = full.split("/", 2);
  try {
    const [row] = await db
      .select({
        id: repositories.id,
        ownerId: repositories.ownerId,
        name: repositories.name,
      })
      .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 resolvePullRequestId(
  repositoryId: string,
  number: number | undefined
): Promise<string | null> {
  if (!number) return null;
  try {
    const [row] = await db
      .select({ id: pullRequests.id })
      .from(pullRequests)
      .where(
        and(
          eq(pullRequests.repositoryId, repositoryId),
          eq(pullRequests.number, number)
        )
      )
      .limit(1);
    return row?.id || null;
  } catch {
    return null;
  }
}

/**
 * POST /api/hooks/gatetest
 * Async scan result callback from GateTest.
 */
hooks.post("/api/hooks/gatetest", async (c) => {
  const rawBody = await c.req.text();

  const auth = verifyGateTestAuth(c, rawBody);
  if (!auth.ok) {
    return c.json({ ok: false, error: auth.error || "Unauthorized" }, 401);
  }

  let payload: GateTestPayload;
  try {
    payload = JSON.parse(rawBody) as GateTestPayload;
  } catch {
    return c.json({ ok: false, error: "Invalid JSON body" }, 400);
  }

  if (!payload.repository || !payload.sha || !payload.status) {
    return c.json(
      {
        ok: false,
        error: "Required fields: repository (owner/name), sha, status",
      },
      400
    );
  }

  const repo = await resolveRepo(payload.repository);
  if (!repo) {
    return c.json(
      { ok: false, error: `Unknown repository: ${payload.repository}` },
      404
    );
  }

  const normalisedStatus =
    payload.status === "passed" || payload.status === "success"
      ? "passed"
      : payload.status === "failed"
        ? "failed"
        : "failed"; // treat "error" as a hard fail

  const pullRequestId = await resolvePullRequestId(
    repo.id,
    payload.pullRequestNumber
  );

  let gateRunId: string | null = null;
  try {
    const [row] = await db
      .insert(gateRuns)
      .values({
        repositoryId: repo.id,
        pullRequestId: pullRequestId || undefined,
        commitSha: payload.sha,
        ref: payload.ref || "refs/heads/main",
        gateName: "GateTest",
        status: normalisedStatus,
        summary: payload.summary || `GateTest reported ${normalisedStatus}`,
        details: payload.details ? JSON.stringify(payload.details) : null,
        durationMs: payload.durationMs,
        completedAt: new Date(),
      })
      .returning({ id: gateRuns.id });
    gateRunId = row?.id || null;
  } catch (err) {
    console.error("[hooks/gatetest] insert failed:", err);
    return c.json({ ok: false, error: "Failed to record gate run" }, 500);
  }

  // Notify the repo owner on failure
  if (normalisedStatus === "failed") {
    try {
      await notify(repo.ownerId, {
        kind: "gate_failed",
        title: `GateTest failed on ${payload.repository}`,
        body: payload.summary || "GateTest reported failure via callback",
        repositoryId: repo.id,
      });
    } catch (err) {
      console.error("[hooks/gatetest] notify failed:", err);
    }
  }

  try {
    await audit({
      userId: null,
      action: "gate_callback",
      repositoryId: repo.id,
      metadata: {
        gateName: "GateTest",
        sha: payload.sha,
        status: normalisedStatus,
        source: "gatetest-callback",
      },
    });
  } catch {
    /* swallow */
  }

  // AI patch generator — if the gate failed AND the env flag is on AND
  // an Anthropic key is configured, fire-and-forget a patch PR for the
  // first actionable medium+ severity finding. Never blocks the
  // webhook response.
  if (
    normalisedStatus === "failed" &&
    process.env.AI_PATCH_GENERATOR_ENABLED === "1" &&
    config.anthropicApiKey
  ) {
    const findings = extractFindings(payload.details).filter((f) =>
      severityAtOrAboveMedium(f.severity)
    );
    if (findings.length > 0) {
      generatePatchForGateTestFinding({
        repositoryId: repo.id,
        baseSha: payload.sha,
        findings,
        reportUrl:
          typeof (payload.details as Record<string, unknown> | null)?.reportUrl === "string"
            ? ((payload.details as Record<string, string>).reportUrl)
            : null,
      }).catch((err) =>
        console.error(
          "[hooks/gatetest] AI patch generator crashed:",
          err instanceof Error ? err.message : err
        )
      );
    }
  }

  // CI auto-fix — if the gate failed on a PR, post a ready-to-apply patch
  // comment. Fire-and-forget; never blocks the webhook response.
  if (normalisedStatus === "failed" && gateRunId && pullRequestId) {
    triggerCiAutofix(gateRunId).catch((err) =>
      console.error(
        "[hooks/gatetest] ci-autofix crashed:",
        err instanceof Error ? err.message : err
      )
    );
  }

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

/**
 * GET /api/hooks/gatetest/recent
 * Small read-only endpoint GateTest can hit to verify connectivity +
 * see the 10 most recent gate runs for sanity checks.
 */
hooks.get("/api/hooks/gatetest/recent", async (c) => {
  const rawBody = "";
  const auth = verifyGateTestAuth(c, rawBody);
  if (!auth.ok) {
    return c.json({ ok: false, error: auth.error || "Unauthorized" }, 401);
  }

  try {
    const rows = await db
      .select({
        id: gateRuns.id,
        gateName: gateRuns.gateName,
        status: gateRuns.status,
        summary: gateRuns.summary,
        createdAt: gateRuns.createdAt,
      })
      .from(gateRuns)
      .orderBy(desc(gateRuns.createdAt))
      .limit(10);
    return c.json({ ok: true, runs: rows });
  } catch (err) {
    console.error("[hooks/gatetest] recent failed:", err);
    return c.json({ ok: false, error: "DB error" }, 500);
  }
});

/**
 * GET /api/hooks/ping
 * Unauthenticated liveness — for GateTest to probe reachability without
 * needing credentials. Returns 200 + version info.
 */
hooks.get("/api/hooks/ping", (c) => {
  return c.json({
    ok: true,
    service: "gluecron",
    hooks: ["gatetest", "gatetest/recent", "api/v1/gate-runs (backup)"],
    timestamp: new Date().toISOString(),
  });
});

// ---------------------------------------------------------------------------
// Backup API: personal-access-token path
//
// If for any reason the shared-secret callback path is unavailable,
// GateTest can authenticate with a standard GlueCron personal access token
// and POST the same payload to /api/v1/gate-runs.
//
// Advantages of the backup path:
//   - no new secrets to provision (reuses existing PAT infra)
//   - scoped per-user (audit trail points at a real account)
//   - revocable from /settings/tokens
//
// Trade-off: slightly heavier auth (DB lookup per call), so prefer
// /api/hooks/gatetest for high-volume traffic.
// ---------------------------------------------------------------------------

async function hashPat(token: string): Promise<string> {
  const data = new TextEncoder().encode(token);
  const hash = await crypto.subtle.digest("SHA-256", data);
  return Array.from(new Uint8Array(hash))
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("");
}

async function verifyPatAuth(
  c: any
): Promise<{ ok: boolean; userId?: string; error?: string }> {
  const auth = c.req.header("authorization") || "";
  const rawToken =
    (auth.startsWith("Bearer ") ? auth.slice(7) : "").trim() ||
    (c.req.header("x-api-token") || "").trim();
  if (!rawToken) {
    return { ok: false, error: "Missing Bearer token" };
  }
  if (!rawToken.startsWith("glc_")) {
    return { ok: false, error: "Invalid token format" };
  }
  try {
    const hashed = await hashPat(rawToken);
    const [row] = await db
      .select({ id: apiTokens.id, userId: apiTokens.userId, expiresAt: apiTokens.expiresAt })
      .from(apiTokens)
      .where(eq(apiTokens.tokenHash, hashed))
      .limit(1);
    if (!row) return { ok: false, error: "Unknown token" };
    if (row.expiresAt && row.expiresAt < new Date()) {
      return { ok: false, error: "Token expired" };
    }
    // Update last-used timestamp (fire and forget). Log persistent
    // failures so DB issues surface (was silent .catch(() => {}).)
    db.update(apiTokens)
      .set({ lastUsedAt: new Date() })
      .where(eq(apiTokens.id, row.id))
      .catch((err) => {
        console.warn(
          "[hooks] PAT lastUsedAt update failed:",
          err instanceof Error ? err.message : err
        );
      });
    return { ok: true, userId: row.userId };
  } catch {
    return { ok: false, error: "Auth lookup failed" };
  }
}

/**
 * POST /api/v1/gate-runs
 * Backup path — accepts a personal access token and records a gate run.
 * Identical payload shape to /api/hooks/gatetest.
 */
hooks.post("/api/v1/gate-runs", async (c) => {
  const rawBody = await c.req.text();

  const auth = await verifyPatAuth(c);
  if (!auth.ok) {
    return c.json({ ok: false, error: auth.error || "Unauthorized" }, 401);
  }

  let payload: GateTestPayload & { gateName?: string };
  try {
    payload = JSON.parse(rawBody);
  } catch {
    return c.json({ ok: false, error: "Invalid JSON body" }, 400);
  }

  if (!payload.repository || !payload.sha || !payload.status) {
    return c.json(
      { ok: false, error: "Required: repository, sha, status" },
      400
    );
  }

  const repo = await resolveRepo(payload.repository);
  if (!repo) {
    return c.json(
      { ok: false, error: `Unknown repository: ${payload.repository}` },
      404
    );
  }

  // Scope check: the PAT's owner must own the repo OR have admin/write scope.
  // For MVP, require the token owner to match the repo owner.
  if (repo.ownerId !== auth.userId) {
    return c.json(
      { ok: false, error: "Token does not own this repository" },
      403
    );
  }

  const normalisedStatus =
    payload.status === "passed" || payload.status === "success"
      ? "passed"
      : payload.status === "failed"
        ? "failed"
        : "failed";

  const pullRequestId = await resolvePullRequestId(
    repo.id,
    payload.pullRequestNumber
  );

  let gateRunId: string | null = null;
  try {
    const [row] = await db
      .insert(gateRuns)
      .values({
        repositoryId: repo.id,
        pullRequestId: pullRequestId || undefined,
        commitSha: payload.sha,
        ref: payload.ref || "refs/heads/main",
        gateName: payload.gateName || "GateTest",
        status: normalisedStatus,
        summary: payload.summary || `${payload.gateName || "GateTest"} reported ${normalisedStatus}`,
        details: payload.details ? JSON.stringify(payload.details) : null,
        durationMs: payload.durationMs,
        completedAt: new Date(),
      })
      .returning({ id: gateRuns.id });
    gateRunId = row?.id || null;
  } catch (err) {
    console.error("[hooks/backup] insert failed:", err);
    return c.json({ ok: false, error: "Failed to record gate run" }, 500);
  }

  if (normalisedStatus === "failed") {
    try {
      await notify(repo.ownerId, {
        kind: "gate_failed",
        title: `${payload.gateName || "GateTest"} failed on ${payload.repository}`,
        body: payload.summary || "Gate failure reported via backup API",
        repositoryId: repo.id,
      });
    } catch {
      /* swallow */
    }
  }

  try {
    await audit({
      userId: auth.userId,
      action: "gate_callback_backup",
      repositoryId: repo.id,
      metadata: {
        gateName: payload.gateName || "GateTest",
        sha: payload.sha,
        status: normalisedStatus,
        source: "pat-api",
      },
    });
  } catch {
    /* swallow */
  }

  // Same fire-and-forget AI patch hook as the primary callback path.
  if (
    normalisedStatus === "failed" &&
    process.env.AI_PATCH_GENERATOR_ENABLED === "1" &&
    config.anthropicApiKey
  ) {
    const findings = extractFindings(payload.details).filter((f) =>
      severityAtOrAboveMedium(f.severity)
    );
    if (findings.length > 0) {
      generatePatchForGateTestFinding({
        repositoryId: repo.id,
        baseSha: payload.sha,
        findings,
        reportUrl:
          typeof (payload.details as Record<string, unknown> | null)?.reportUrl === "string"
            ? ((payload.details as Record<string, string>).reportUrl)
            : null,
      }).catch((err) =>
        console.error(
          "[hooks/backup] AI patch generator crashed:",
          err instanceof Error ? err.message : err
        )
      );
    }
  }

  // CI auto-fix — post a ready-to-apply patch comment on the PR.
  if (normalisedStatus === "failed" && gateRunId && pullRequestId) {
    triggerCiAutofix(gateRunId).catch((err) =>
      console.error(
        "[hooks/backup] ci-autofix crashed:",
        err instanceof Error ? err.message : err
      )
    );
  }

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

/**
 * GET /api/v1/gate-runs?repository=owner/name&limit=20
 * Backup read path — list recent gate runs for a repo (PAT-authed).
 */
hooks.get("/api/v1/gate-runs", async (c) => {
  const auth = await verifyPatAuth(c);
  if (!auth.ok) {
    return c.json({ ok: false, error: auth.error || "Unauthorized" }, 401);
  }

  const repoFull = c.req.query("repository") || "";
  const limit = Math.min(100, Math.max(1, Number(c.req.query("limit") || 20)));
  if (!repoFull) {
    return c.json({ ok: false, error: "Query param 'repository' required" }, 400);
  }

  const repo = await resolveRepo(repoFull);
  if (!repo) return c.json({ ok: false, error: "Unknown repository" }, 404);
  if (repo.ownerId !== auth.userId) {
    return c.json({ ok: false, error: "Forbidden" }, 403);
  }

  try {
    const rows = await db
      .select()
      .from(gateRuns)
      .where(eq(gateRuns.repositoryId, repo.id))
      .orderBy(desc(gateRuns.createdAt))
      .limit(limit);
    return c.json({ ok: true, runs: rows });
  } catch {
    return c.json({ ok: false, error: "DB error" }, 500);
  }
});

/**
 * POST /api/pr-comments/:commentId/apply-autofix
 *
 * Applies the patch embedded in a CI autofix comment to a new branch, then
 * redirects to the compare view. Authenticated via a personal access token
 * (same mechanism as /api/v1/gate-runs).
 *
 * Response on success (JSON): { ok: true, branchName, compareUrl }
 * Response on failure (JSON): { ok: false, error }
 */
hooks.post("/api/pr-comments/:commentId/apply-autofix", async (c) => {
  const auth = await verifyPatAuth(c);
  if (!auth.ok || !auth.userId) {
    return c.json({ ok: false, error: auth.error || "Unauthorized" }, 401);
  }

  const { commentId } = c.req.param();
  if (!commentId) {
    return c.json({ ok: false, error: "commentId param required" }, 400);
  }

  let result: { branchName: string };
  try {
    result = await applyAutofix(commentId, auth.userId);
  } catch (err) {
    const msg = err instanceof Error ? err.message : "Unknown error";
    return c.json({ ok: false, error: msg }, 400);
  }

  // Look up the PR to build the compare URL
  const commentRows = await db
    .select({ pullRequestId: prComments.pullRequestId })
    .from(prComments)
    .where(eq(prComments.id, commentId))
    .limit(1);

  let compareUrl: string | null = null;
  if (commentRows[0]) {
    const prRows = await db
      .select({
        repositoryId: pullRequests.repositoryId,
        number: pullRequests.number,
        baseBranch: pullRequests.baseBranch,
      })
      .from(pullRequests)
      .where(eq(pullRequests.id, commentRows[0].pullRequestId))
      .limit(1);

    if (prRows[0]) {
      const repoRows = await db
        .select({ name: repositories.name, ownerUsername: users.username })
        .from(repositories)
        .innerJoin(users, eq(repositories.ownerId, users.id))
        .where(eq(repositories.id, prRows[0].repositoryId))
        .limit(1);

      if (repoRows[0]) {
        compareUrl = `/${repoRows[0].ownerUsername}/${repoRows[0].name}/compare/${result.branchName}`;
      }
    }
  }

  return c.json({ ok: true, branchName: result.branchName, compareUrl });
});

// ---------------------------------------------------------------------------
// Phase 2: Flywheel telemetry feedback endpoint
// POST /api/flywheel-telemetry/feedback
// Body: gateRunId, verdict ("helpful" | "hallucination")
// ---------------------------------------------------------------------------
hooks.post("/flywheel-telemetry/feedback", async (c) => {
  const body = await c.req.parseBody();
  const gateRunId = String(body.gateRunId ?? "").trim();
  const verdict = String(body.verdict ?? "").trim();

  if (!gateRunId) return c.json({ error: "gateRunId required" }, 400);
  if (verdict !== "helpful" && verdict !== "hallucination") {
    return c.json({ error: "verdict must be 'helpful' or 'hallucination'" }, 400);
  }

  const reworkRateStatus = verdict === "helpful" ? "confirmed_helpful" : "hallucination_flagged";

  try {
    await db
      .update(flywheelTelemetry)
      .set({ reworkRateStatus })
      .where(eq(flywheelTelemetry.gateRunId, gateRunId));
    return c.json({ ok: true, reworkRateStatus });
  } catch (err) {
    console.error("[flywheel-feedback] db error:", err);
    return c.json({ error: "db error" }, 500);
  }
});

export default hooks;