CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
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 | /**
* PR triage — fire-and-forget hook on PR open. Runs the AI-driven
* triage helper from ai-generators.ts and posts a "## AI Triage"
* comment with suggestions (labels, reviewers, priority, risk area,
* one-line summary).
*
* Suggestions only — nothing is applied automatically. The PR author
* stays in control. The Bible §3 D3 documents this contract.
*
* Idempotency: every comment carries an HTML-comment marker so a second
* trigger (e.g. draft → ready toggle) won't re-post the same advice.
*
* Failure modes (DB hiccup, missing key, AI parse error) are all
* funnelled through fallback / try-catch paths so the autopilot loop
* and the route handler never see a thrown promise.
*/
import { and, asc, eq, like } from "drizzle-orm";
import { db } from "../db";
import {
labels,
prComments,
pullRequests,
repositories,
users,
} from "../db/schema";
import { getRepoPath } from "../git/repository";
import { triagePullRequest, type PrTriage } from "./ai-generators";
import { isAiAvailable } from "./ai-client";
export const PR_TRIAGE_MARKER = "<!-- gluecron-pr-triage:summary -->";
const DIFF_BYTE_CAP = 8_000;
export interface PrTriageInput {
ownerName: string;
repoName: string;
repositoryId: string;
prId: string;
prAuthorId: string;
title: string;
body: string;
baseBranch: string;
headBranch: string;
}
async function alreadyTriaged(prId: string): Promise<boolean> {
try {
const [row] = await db
.select({ id: prComments.id })
.from(prComments)
.where(
and(
eq(prComments.pullRequestId, prId),
eq(prComments.isAiReview, true),
like(prComments.body, `%${PR_TRIAGE_MARKER}%`)
)
)
.limit(1);
return !!row;
} catch {
return false;
}
}
async function loadAvailableLabels(repositoryId: string): Promise<string[]> {
try {
const rows = await db
.select({ name: labels.name })
.from(labels)
.where(eq(labels.repositoryId, repositoryId))
.orderBy(asc(labels.name));
return rows.map((r) => r.name);
} catch {
return [];
}
}
/**
* Candidate reviewers v1: the repo owner + recent contributors via the
* `pull_requests.authorId` join (last 50 PRs). Excludes the current PR
* author. Truncated to 12 entries to keep the prompt small.
*/
async function loadCandidateReviewers(
repositoryId: string,
excludeUserId: string
): Promise<string[]> {
try {
const out = new Set<string>();
const [repoRow] = await db
.select({ ownerId: repositories.ownerId })
.from(repositories)
.where(eq(repositories.id, repositoryId))
.limit(1);
if (repoRow && repoRow.ownerId !== excludeUserId) {
const [owner] = await db
.select({ username: users.username })
.from(users)
.where(eq(users.id, repoRow.ownerId))
.limit(1);
if (owner) out.add(owner.username);
}
const recent = await db
.select({ authorId: pullRequests.authorId })
.from(pullRequests)
.where(eq(pullRequests.repositoryId, repositoryId))
.limit(50);
const ids = [
...new Set(
recent
.map((r) => r.authorId)
.filter((id): id is string => !!id && id !== excludeUserId)
),
];
if (ids.length > 0) {
const us = await db
.select({ id: users.id, username: users.username })
.from(users);
const byId = new Map(us.map((u) => [u.id, u.username]));
for (const id of ids) {
const u = byId.get(id);
if (u) out.add(u);
if (out.size >= 12) break;
}
}
return [...out];
} catch {
return [];
}
}
/**
* Build a tiny diff summary suitable for the prompt — file path, +/-
* lines per file. Skips bodies entirely (we only need shape, not
* content). Cap total size at DIFF_BYTE_CAP. Empty string on failure.
*/
async function buildDiffSummary(
ownerName: string,
repoName: string,
baseBranch: string,
headBranch: string
): Promise<string> {
try {
const cwd = getRepoPath(ownerName, repoName);
const proc = Bun.spawn(
[
"git",
"diff",
"--numstat",
`${baseBranch}...${headBranch}`,
"--",
],
{ cwd, stdout: "pipe", stderr: "pipe" }
);
let text = await new Response(proc.stdout).text();
await proc.exited;
text = text.trim();
if (!text) return "";
if (text.length > DIFF_BYTE_CAP) {
text = text.slice(0, DIFF_BYTE_CAP) + "\n...(truncated)";
}
return text;
} catch {
return "";
}
}
/**
* Pure helper: render the "## AI Triage" comment body. Exported for
* unit tests so we can pin the format without an Anthropic dependency.
*/
export function renderTriageComment(t: PrTriage): string {
const labels = t.suggestedLabels.length
? t.suggestedLabels.map((l) => `\`${l}\``).join(", ")
: "_(no label suggestions)_";
const reviewers = t.suggestedReviewerUsernames.length
? t.suggestedReviewerUsernames.map((u) => `@${u}`).join(", ")
: "_(no reviewer suggestions)_";
const summary = t.summary?.trim() || "_(no summary)_";
return [
PR_TRIAGE_MARKER,
"## AI Triage",
"",
`> ${summary}`,
"",
`**Priority:** ${t.priority}`,
`**Risk area:** ${t.riskArea}`,
"",
`**Suggested labels:** ${labels}`,
`**Suggested reviewers:** ${reviewers}`,
"",
"_Suggestions only — nothing has been applied. The PR author stays in control._",
].join("\n");
}
export async function triggerPrTriage(input: PrTriageInput): Promise<void> {
try {
if (process.env.DEBUG_PR_TRIAGE === "1") {
console.log(
"[pr-triage] queued",
input.ownerName,
input.repoName,
input.prId
);
}
if (!isAiAvailable()) return;
if (await alreadyTriaged(input.prId)) return;
const [diffSummary, availableLabels, candidateReviewers] = await Promise.all([
buildDiffSummary(
input.ownerName,
input.repoName,
input.baseBranch,
input.headBranch
),
loadAvailableLabels(input.repositoryId),
loadCandidateReviewers(input.repositoryId, input.prAuthorId),
]);
const triage = await triagePullRequest(
input.title,
input.body,
diffSummary,
availableLabels,
candidateReviewers
);
const body = renderTriageComment(triage);
await db
.insert(prComments)
.values({
pullRequestId: input.prId,
authorId: input.prAuthorId,
body,
isAiReview: true,
})
.catch((err) => {
console.error(
`[pr-triage] failed to insert triage comment for PR ${input.prId}:`,
err instanceof Error ? err.message : err
);
});
} catch (err) {
if (process.env.DEBUG_PR_TRIAGE === "1") {
console.error("[pr-triage] crashed:", err);
}
}
}
/** Test-only export of internals so DB-less tests can reach the helpers. */
export const __test = {
alreadyTriaged,
loadAvailableLabels,
loadCandidateReviewers,
buildDiffSummary,
renderTriageComment,
};
|