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
pr-risk.ts20.9 KB · 716 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
/**
 * Block M3 — AI pre-merge risk score.
 *
 * For every open PR we compute a transparent, auditable 0-10 risk score
 * the reviewer can see at a glance before clicking Merge. The score is a
 * pure function over a small set of signals (file count, line count,
 * teams affected, schema migrations touched, dependency churn, test
 * ratio). The LLM (Haiku — fast + cheap) only writes the one-paragraph
 * prose summary; it never influences the numeric score.
 *
 * Architecture:
 *
 *   1. `computePrRiskScore(signals)` — pure helper. Same input always
 *      yields the same score. Documented inline; auditable.
 *   2. `generatePrRiskSummary(args)` — calls Haiku for prose. Never
 *      throws — falls back to a deterministic sentence when no API key
 *      is set or the call fails.
 *   3. `computePrRiskForPullRequest(prId)` — DB-backed orchestrator.
 *      Resolves the PR + head SHA, gathers signals, computes the score,
 *      persists it to `pr_risk_scores`, returns the full row.
 *   4. `getCachedPrRisk(prId)` — cheap lookup for the current head SHA.
 *
 * Cache key: `(pull_request_id, commit_sha)`. When the head branch is
 * force-pushed (new SHA), the cache miss naturally re-triggers a score
 * computation.
 */

import { and, desc, eq } from "drizzle-orm";
import { db } from "../db";
import {
  codeOwners,
  prRiskScores,
  pullRequests,
  repoDependencies,
  repositories,
  users,
  type PrRiskScoreRow,
} from "../db/schema";
import { getDiff, getRepoPath, resolveRef } from "../git/repository";
import {
  getAnthropic,
  isAiAvailable,
  MODEL_HAIKU,
  extractText,
} from "./ai-client";
import { ownersForPath, parseCodeowners, type OwnerRule } from "./codeowners";

// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------

export type PrRiskBand = "low" | "medium" | "high" | "critical";

export interface PrRiskSignals {
  filesChanged: number;
  linesAdded: number;
  linesRemoved: number;
  /** Distinct CODEOWNERS owners touched (count). */
  teamsAffected: number;
  schemaMigrationTouched: boolean;
  /** Paths under sensitive/ etc. */
  lockedPathTouched: boolean;
  addsNewDependency: boolean;
  bumpsMajorDependency: boolean;
  testsAddedForNewCode: boolean;
  /** 0..1, 0 = lots of tests, 1 = no tests. */
  diffMinusTestRatio: number;
}

export interface PrRiskScore {
  score: number;
  band: PrRiskBand;
  signals: PrRiskSignals;
  aiSummary: string;
  generatedAt: Date;
  commitSha: string;
}

// ---------------------------------------------------------------------------
// Pure score formula
// ---------------------------------------------------------------------------

/**
 * Transparent risk formula (intentionally simple, intentionally not LLM):
 *
 *   + 0.3 per file changed (cap at 3.0)
 *   + 0.005 per (linesAdded + linesRemoved) (cap at 2.0)
 *   + 0.8 per team beyond the first (cap at 2.0)
 *   + 1.5 if schemaMigrationTouched
 *   + 1.0 if lockedPathTouched
 *   + 0.5 if addsNewDependency
 *   + 1.2 if bumpsMajorDependency
 *   + 1.0 * (testsAddedForNewCode ? 0 : diffMinusTestRatio)
 *
 * Clamp to [0, 10] and round to nearest integer.
 *
 * Band thresholds:
 *   0–2  → low
 *   3–4  → medium
 *   5–7  → high
 *   8–10 → critical
 *
 * Monotonicity: every weight is non-negative, so flipping any boolean
 * signal from false to true (or increasing any counter) can only raise
 * the score (until the cap). Verified by tests.
 */
export function computePrRiskScore(
  signals: PrRiskSignals
): { score: number; band: PrRiskBand } {
  let raw = 0;

  // File count contribution (cap at 3.0).
  raw += Math.min(3.0, Math.max(0, signals.filesChanged) * 0.3);

  // Line count contribution (cap at 2.0).
  const totalLines =
    Math.max(0, signals.linesAdded) + Math.max(0, signals.linesRemoved);
  raw += Math.min(2.0, totalLines * 0.005);

  // Teams-beyond-the-first contribution (cap at 2.0). teamsAffected=0 or 1
  // contributes nothing; each additional team adds 0.8.
  const extraTeams = Math.max(0, signals.teamsAffected - 1);
  raw += Math.min(2.0, extraTeams * 0.8);

  // Boolean signals.
  if (signals.schemaMigrationTouched) raw += 1.5;
  if (signals.lockedPathTouched) raw += 1.0;
  if (signals.addsNewDependency) raw += 0.5;
  if (signals.bumpsMajorDependency) raw += 1.2;

  // Test-coverage penalty.
  if (!signals.testsAddedForNewCode) {
    const ratio = clamp01(signals.diffMinusTestRatio);
    raw += 1.0 * ratio;
  }

  const score = Math.max(0, Math.min(10, Math.round(raw)));
  return { score, band: bandFor(score) };
}

function clamp01(n: number): number {
  if (!Number.isFinite(n)) return 0;
  return Math.max(0, Math.min(1, n));
}

function bandFor(score: number): PrRiskBand {
  if (score <= 2) return "low";
  if (score <= 4) return "medium";
  if (score <= 7) return "high";
  return "critical";
}

// ---------------------------------------------------------------------------
// AI prose summary — Haiku call with deterministic fallback
// ---------------------------------------------------------------------------

/**
 * Generate a 1-3 sentence prose summary of the risk profile. Calls Haiku
 * for fluency; on any failure (no key, API error, malformed response)
 * falls back to a deterministic sentence built from the signal map.
 *
 * Never throws. Always returns a non-empty string.
 */
export async function generatePrRiskSummary(args: {
  signals: PrRiskSignals;
  title: string;
  baseBranch: string;
  headBranch: string;
}): Promise<string> {
  const fallback = deterministicSummary(args.signals);

  if (!isAiAvailable()) return fallback;

  try {
    const client = getAnthropic();
    const message = await client.messages.create({
      model: MODEL_HAIKU,
      max_tokens: 200,
      messages: [
        {
          role: "user",
          content: `You are summarising the risk profile of a pull request for a reviewer who is about to click Merge.

PR title: ${args.title}
Base branch: ${args.baseBranch}
Head branch: ${args.headBranch}

Signals (these are the FACTS — do not invent any others):
- files changed: ${args.signals.filesChanged}
- lines added: ${args.signals.linesAdded}
- lines removed: ${args.signals.linesRemoved}
- distinct CODEOWNERS owners touched: ${args.signals.teamsAffected}
- schema migration touched: ${args.signals.schemaMigrationTouched}
- locked / sensitive path touched: ${args.signals.lockedPathTouched}
- adds a new dependency: ${args.signals.addsNewDependency}
- bumps a major dependency: ${args.signals.bumpsMajorDependency}
- tests added for new code: ${args.signals.testsAddedForNewCode}
- diff-minus-test ratio (0=lots of tests, 1=no tests): ${args.signals.diffMinusTestRatio.toFixed(2)}

Write ONE to THREE plain sentences describing the riskiest aspects of this PR.
Tone: blunt, factual, no marketing. Do not include a numeric score (the reviewer
already sees that). Do not use bullet points. Output the prose only.`,
        },
      ],
    });
    const text = extractText(message).trim();
    if (!text) return fallback;
    return text.slice(0, 600);
  } catch {
    return fallback;
  }
}

/**
 * Deterministic prose composed from the signal map. Used as the always-
 * available fallback. Public-internal — exported for tests.
 */
export function deterministicSummary(signals: PrRiskSignals): string {
  const parts: string[] = [];
  parts.push(
    `Touches ${signals.filesChanged} file(s) with ${signals.linesAdded} added and ${signals.linesRemoved} removed across ${signals.teamsAffected} owner(s).`
  );
  const hotspots: string[] = [];
  if (signals.schemaMigrationTouched) hotspots.push("a schema migration");
  if (signals.lockedPathTouched) hotspots.push("a locked / sensitive path");
  if (signals.bumpsMajorDependency) hotspots.push("a major dependency bump");
  else if (signals.addsNewDependency) hotspots.push("a new dependency");
  if (hotspots.length > 0) {
    parts.push(`Includes ${joinList(hotspots)}.`);
  }
  if (!signals.testsAddedForNewCode && signals.diffMinusTestRatio > 0.5) {
    parts.push("No tests were added for the new code.");
  }
  return parts.join(" ");
}

function joinList(items: string[]): string {
  if (items.length === 0) return "";
  if (items.length === 1) return items[0];
  if (items.length === 2) return `${items[0]} and ${items[1]}`;
  return `${items.slice(0, -1).join(", ")}, and ${items[items.length - 1]}`;
}

// ---------------------------------------------------------------------------
// Signal-gathering helpers (DB + git)
// ---------------------------------------------------------------------------

const SCHEMA_MIGRATION_PATTERNS = [
  /^drizzle\//i,
  /^db\/migrations\//i,
  /^migrations\//i,
  /\/migrations\//i,
  /^src\/db\/schema\.ts$/i,
];

const LOCKED_PATH_PATTERNS = [
  /^sensitive\//i,
  /^secrets\//i,
  /^infra\/secrets\//i,
  /\.pem$/i,
  /\.key$/i,
];

const TEST_PATH_PATTERNS = [
  /(^|\/)__tests__\//i,
  /\.test\.[tj]sx?$/i,
  /\.spec\.[tj]sx?$/i,
  /(^|\/)tests?\//i,
];

function matchesAny(path: string, patterns: RegExp[]): boolean {
  for (const re of patterns) if (re.test(path)) return true;
  return false;
}

function isSchemaMigrationPath(path: string): boolean {
  return matchesAny(path, SCHEMA_MIGRATION_PATTERNS);
}

function isLockedPath(path: string): boolean {
  return matchesAny(path, LOCKED_PATH_PATTERNS);
}

function isTestPath(path: string): boolean {
  return matchesAny(path, TEST_PATH_PATTERNS);
}

/** Diff-file shape we accept — keeps signal gather DI-friendly for tests. */
export interface DiffFileInput {
  path: string;
  additions: number;
  deletions: number;
}

/**
 * Compute the raw signal map from a parsed diff plus owner rules and the
 * pre/post dependency sets. Pure helper — no DB, no git, no LLM. Exported
 * so it can be exercised directly by tests with synthetic inputs.
 */
export function buildSignalsFromDiff(args: {
  files: DiffFileInput[];
  raw: string;
  ownerRules: OwnerRule[];
  /** Existing dep set on the base side, keyed `ecosystem:name`. */
  baseDeps: Map<string, string | null>;
  /** Dep set after the PR's changes (best-effort), same key shape. */
  headDeps: Map<string, string | null>;
}): PrRiskSignals {
  let linesAdded = 0;
  let linesRemoved = 0;
  let schemaMigrationTouched = false;
  let lockedPathTouched = false;
  let testFiles = 0;
  let testLines = 0;
  const ownerSet = new Set<string>();

  for (const f of args.files) {
    linesAdded += Math.max(0, f.additions || 0);
    linesRemoved += Math.max(0, f.deletions || 0);
    if (isSchemaMigrationPath(f.path)) schemaMigrationTouched = true;
    if (isLockedPath(f.path)) lockedPathTouched = true;
    if (isTestPath(f.path)) {
      testFiles += 1;
      testLines += Math.max(0, (f.additions || 0) + (f.deletions || 0));
    }
    if (args.ownerRules.length > 0) {
      for (const o of ownersForPath(f.path, args.ownerRules)) {
        ownerSet.add(o);
      }
    }
  }

  const filesChanged = args.files.length;
  const teamsAffected = ownerSet.size;
  const testsAddedForNewCode = testFiles > 0 && linesAdded > 0;
  const totalLines = linesAdded + linesRemoved;
  const diffMinusTestRatio =
    totalLines === 0 ? 0 : 1 - Math.min(1, testLines / totalLines);

  // Dependency comparison — adds vs bumps.
  let addsNewDependency = false;
  let bumpsMajorDependency = false;
  for (const [key, headVersion] of args.headDeps) {
    if (!args.baseDeps.has(key)) {
      addsNewDependency = true;
      continue;
    }
    const baseVersion = args.baseDeps.get(key) ?? null;
    if (isMajorBump(baseVersion, headVersion)) {
      bumpsMajorDependency = true;
    }
  }

  return {
    filesChanged,
    linesAdded,
    linesRemoved,
    teamsAffected,
    schemaMigrationTouched,
    lockedPathTouched,
    addsNewDependency,
    bumpsMajorDependency,
    testsAddedForNewCode,
    diffMinusTestRatio,
  };
}

/**
 * Heuristic semver-major detector. Strips leading ^ ~ = v and compares
 * the leading integer chunks. Anything we cannot parse returns false so
 * we err toward "no false positive bump".
 */
export function isMajorBump(
  before: string | null | undefined,
  after: string | null | undefined
): boolean {
  const a = leadingMajor(before);
  const b = leadingMajor(after);
  if (a === null || b === null) return false;
  return b > a;
}

function leadingMajor(spec: string | null | undefined): number | null {
  if (!spec) return null;
  const stripped = spec.trim().replace(/^[~^=v]+/, "");
  const match = stripped.match(/^(\d+)/);
  if (!match) return null;
  const n = parseInt(match[1], 10);
  return Number.isFinite(n) ? n : null;
}

// ---------------------------------------------------------------------------
// DB-touching orchestrator
// ---------------------------------------------------------------------------

interface PrRow {
  id: string;
  title: string;
  baseBranch: string;
  headBranch: string;
  repositoryId: string;
}

interface RepoRow {
  id: string;
  name: string;
  ownerUsername: string;
}

async function loadPrRow(prId: string): Promise<{
  pr: PrRow;
  repo: RepoRow;
} | null> {
  try {
    const [row] = await db
      .select({
        prId: pullRequests.id,
        title: pullRequests.title,
        baseBranch: pullRequests.baseBranch,
        headBranch: pullRequests.headBranch,
        repositoryId: pullRequests.repositoryId,
        repoName: repositories.name,
        ownerUsername: users.username,
      })
      .from(pullRequests)
      .innerJoin(repositories, eq(repositories.id, pullRequests.repositoryId))
      .innerJoin(users, eq(users.id, repositories.ownerId))
      .where(eq(pullRequests.id, prId))
      .limit(1);
    if (!row) return null;
    return {
      pr: {
        id: row.prId,
        title: row.title,
        baseBranch: row.baseBranch,
        headBranch: row.headBranch,
        repositoryId: row.repositoryId,
      },
      repo: {
        id: row.repositoryId,
        name: row.repoName,
        ownerUsername: row.ownerUsername,
      },
    };
  } catch {
    return null;
  }
}

async function loadOwnerRules(repoId: string): Promise<OwnerRule[]> {
  try {
    const rows = await db
      .select({
        pattern: codeOwners.pathPattern,
        owners: codeOwners.ownerUsernames,
      })
      .from(codeOwners)
      .where(eq(codeOwners.repositoryId, repoId));
    return rows.map((r) => ({
      pattern: r.pattern,
      owners: (r.owners || "").split(",").filter(Boolean),
    }));
  } catch {
    return [];
  }
}

async function loadCurrentDeps(
  repoId: string
): Promise<Map<string, string | null>> {
  try {
    const rows = await db
      .select({
        ecosystem: repoDependencies.ecosystem,
        name: repoDependencies.name,
        versionSpec: repoDependencies.versionSpec,
      })
      .from(repoDependencies)
      .where(eq(repoDependencies.repositoryId, repoId));
    const out = new Map<string, string | null>();
    for (const r of rows) {
      out.set(`${r.ecosystem}:${r.name}`, r.versionSpec);
    }
    return out;
  } catch {
    return new Map();
  }
}

/**
 * Parse the dependency state shown by the PR's head commit. We re-use
 * the indexed base-side `repo_dependencies` rows as a baseline and look
 * for additions/changes by parsing a head-side `package.json` blob via
 * `git show`. If git access fails we return null which the caller treats
 * as "no signal" (addsNewDependency = bumpsMajorDependency = false).
 */
async function loadHeadDeps(
  ownerName: string,
  repoName: string,
  baseBranch: string,
  headBranch: string
): Promise<Map<string, string | null>> {
  const out = new Map<string, string | null>();
  // We only sniff package.json on the head side (the most common manifest);
  // the base-side counts come from the indexed snapshot already. This is a
  // best-effort signal — false negatives are fine, false positives would be
  // worse.
  try {
    const cwd = getRepoPath(ownerName, repoName);
    const proc = Bun.spawn(
      ["git", "show", `${headBranch}:package.json`],
      { cwd, stdout: "pipe", stderr: "pipe" }
    );
    const text = await new Response(proc.stdout).text();
    const exit = await proc.exited;
    if (exit !== 0 || !text.trim()) return out;
    const parsed = JSON.parse(text) as Record<string, unknown>;
    for (const key of [
      "dependencies",
      "devDependencies",
      "peerDependencies",
      "optionalDependencies",
    ]) {
      const block = parsed[key];
      if (!block || typeof block !== "object") continue;
      for (const [name, spec] of Object.entries(block as Record<string, unknown>)) {
        out.set(
          `npm:${name}`,
          typeof spec === "string" ? spec : null
        );
      }
    }
    // Mark baseBranch silently used so the args object stays meaningful
    // even if a future refactor adds a base-side diff.
    void baseBranch;
  } catch {
    /* swallow — return whatever we have */
  }
  return out;
}

/**
 * Compute + persist the risk score for one PR. Returns null when the PR
 * cannot be found or the git head SHA cannot be resolved. Idempotent on
 * the unique (pull_request_id, commit_sha) constraint.
 */
export async function computePrRiskForPullRequest(
  pullRequestId: string,
  opts: { now?: Date } = {}
): Promise<PrRiskScore | null> {
  const loaded = await loadPrRow(pullRequestId);
  if (!loaded) return null;

  const { pr, repo } = loaded;
  const headSha = await resolveRef(
    repo.ownerUsername,
    repo.name,
    pr.headBranch
  ).catch(() => null);
  if (!headSha) return null;

  let diffFiles: DiffFileInput[] = [];
  let diffRaw = "";
  try {
    const d = await getDiff(repo.ownerUsername, repo.name, headSha);
    diffFiles = d.files.map((f) => ({
      path: f.path,
      additions: f.additions,
      deletions: f.deletions,
    }));
    diffRaw = d.raw;
  } catch {
    /* swallow — buildSignalsFromDiff handles empty arrays */
  }

  const ownerRules = await loadOwnerRules(repo.id);
  const baseDeps = await loadCurrentDeps(repo.id);
  const headDeps = await loadHeadDeps(
    repo.ownerUsername,
    repo.name,
    pr.baseBranch,
    pr.headBranch
  );

  const signals = buildSignalsFromDiff({
    files: diffFiles,
    raw: diffRaw,
    ownerRules,
    baseDeps,
    headDeps,
  });

  const { score, band } = computePrRiskScore(signals);

  const aiSummary = await generatePrRiskSummary({
    signals,
    title: pr.title,
    baseBranch: pr.baseBranch,
    headBranch: pr.headBranch,
  });

  const generatedAt = opts.now ?? new Date();

  // Best-effort upsert: try insert, fall back to existing row on the
  // unique-constraint hit.
  try {
    await db.insert(prRiskScores).values({
      pullRequestId,
      commitSha: headSha,
      score,
      band,
      signals,
      aiSummary,
      generatedAt,
    });
  } catch {
    // Already cached for this SHA — that's fine, the caller's view
    // converges on the same shape via getCachedPrRisk below. No throw.
  }

  return {
    score,
    band,
    signals,
    aiSummary,
    generatedAt,
    commitSha: headSha,
  };
}

/**
 * Return the cached risk score for the current head SHA of a PR, if any.
 * Returns null when no row matches (cache miss) — the caller is expected
 * to kick off `computePrRiskForPullRequest` async and show a placeholder.
 */
export async function getCachedPrRisk(
  pullRequestId: string
): Promise<PrRiskScore | null> {
  try {
    const loaded = await loadPrRow(pullRequestId);
    if (!loaded) return null;
    const headSha = await resolveRef(
      loaded.repo.ownerUsername,
      loaded.repo.name,
      loaded.pr.headBranch
    ).catch(() => null);
    if (!headSha) return null;

    const [row] = await db
      .select()
      .from(prRiskScores)
      .where(
        and(
          eq(prRiskScores.pullRequestId, pullRequestId),
          eq(prRiskScores.commitSha, headSha)
        )
      )
      .orderBy(desc(prRiskScores.generatedAt))
      .limit(1);

    if (!row) return null;
    return rowToPrRiskScore(row);
  } catch {
    return null;
  }
}

/**
 * Lookup variant that doesn't need git access — returns the most-recent
 * cached score for a PR regardless of which SHA it was pinned to. Used
 * by the MCP merge tool where we want the score even if the SHA has
 * since moved on.
 */
export async function getLatestCachedPrRisk(
  pullRequestId: string
): Promise<PrRiskScore | null> {
  try {
    const [row] = await db
      .select()
      .from(prRiskScores)
      .where(eq(prRiskScores.pullRequestId, pullRequestId))
      .orderBy(desc(prRiskScores.generatedAt))
      .limit(1);
    if (!row) return null;
    return rowToPrRiskScore(row);
  } catch {
    return null;
  }
}

function rowToPrRiskScore(row: PrRiskScoreRow): PrRiskScore {
  return {
    score: row.score,
    band: row.band as PrRiskBand,
    signals: (row.signals as unknown) as PrRiskSignals,
    aiSummary: row.aiSummary ?? "",
    generatedAt: row.generatedAt,
    commitSha: row.commitSha,
  };
}

// ---------------------------------------------------------------------------
// Test-only surface
// ---------------------------------------------------------------------------

export const __test = {
  bandFor,
  clamp01,
  deterministicSummary,
  isMajorBump,
  leadingMajor,
  isSchemaMigrationPath,
  isLockedPath,
  isTestPath,
  rowToPrRiskScore,
};