|
| 1 | +import { createInstallationToken } from "../github/app"; |
| 2 | +import { githubRateLimitAdmissionKeyForInstallation, makeInstallationOctokit } from "../github/client"; |
| 3 | +import { createIssueComment } from "../github/pr-actions"; |
| 4 | +import { termOverlap, tokenize, type CollisionTerms } from "../signals/engine"; |
| 5 | +import { errorMessage } from "../utils/json"; |
| 6 | + |
| 7 | +/** Repo-scoped context shared by every ProjectTrackerAdapter call (#3183). */ |
| 8 | +export type ProjectTrackerContext = { |
| 9 | + env: Env; |
| 10 | + installationId: number; |
| 11 | + repoFullName: string; |
| 12 | +}; |
| 13 | + |
| 14 | +/** A single open Project or Milestone, normalized to a string `id` regardless of the backend's native ID shape |
| 15 | + * (a GitHub Milestone's REST `number` vs. a GitHub Projects v2 GraphQL node ID vs. a Linear UUID). */ |
| 16 | +export type ProjectTrackerRef = { |
| 17 | + id: string; |
| 18 | + title: string; |
| 19 | +}; |
| 20 | + |
| 21 | +export type ProjectTrackerAttachResult = { |
| 22 | + attached: boolean; |
| 23 | +}; |
| 24 | + |
| 25 | +/** |
| 26 | + * Pluggable project/milestone tracker backend (#3183). `GitHubMilestonesAdapter` below implements the |
| 27 | + * milestone half now; Projects v2 (#3184) and a Linear backend (#3186) implement the same interface without |
| 28 | + * reshaping the matching/suggestion logic that calls it. |
| 29 | + */ |
| 30 | +export interface ProjectTrackerAdapter { |
| 31 | + listOpenProjects(ctx: ProjectTrackerContext): Promise<ProjectTrackerRef[]>; |
| 32 | + listOpenMilestones(ctx: ProjectTrackerContext): Promise<ProjectTrackerRef[]>; |
| 33 | + attachToProject(ctx: ProjectTrackerContext, pullNumber: number, projectId: string): Promise<ProjectTrackerAttachResult>; |
| 34 | + attachToMilestone(ctx: ProjectTrackerContext, pullNumber: number, milestoneId: string): Promise<ProjectTrackerAttachResult>; |
| 35 | +} |
| 36 | + |
| 37 | +function parseRepoFullName(repoFullName: string): { owner: string; repo: string } { |
| 38 | + const parts = repoFullName.split("/"); |
| 39 | + const owner = parts[0]; |
| 40 | + const repo = parts[1]; |
| 41 | + if (parts.length !== 2 || !owner || !repo || /\s/.test(repoFullName)) { |
| 42 | + throw new Error(`Invalid repository full name: ${repoFullName}`); |
| 43 | + } |
| 44 | + return { owner, repo }; |
| 45 | +} |
| 46 | + |
| 47 | +type GitHubMilestone = { |
| 48 | + number: number; |
| 49 | + title: string; |
| 50 | +}; |
| 51 | + |
| 52 | +// Bounded pagination for both the milestone list and the comment-marker search below (mirrors |
| 53 | +// src/github/comments.ts's COMMENT_SEARCH_PAGE_LIMIT): 3 pages * 100 = 300 items is generously above any |
| 54 | +// realistic open-milestone or PR-comment count, while still bounding worst-case GitHub API calls per PR event. |
| 55 | +const GITHUB_LIST_PAGE_LIMIT = 3; |
| 56 | + |
| 57 | +/** A positive-integer milestone/issue number as a string, or null if `value` isn't one. Guards against a |
| 58 | + * malformed/forged `milestoneId` reaching GitHub's PATCH as `NaN` or a negative/zero number. */ |
| 59 | +function parsePositiveIntegerId(value: string): number | null { |
| 60 | + const parsed = Number(value); |
| 61 | + return Number.isInteger(parsed) && parsed > 0 ? parsed : null; |
| 62 | +} |
| 63 | + |
| 64 | +/** GitHub REST implementation of {@link ProjectTrackerAdapter}. Only the Milestone half is real (#3183) -- |
| 65 | + * Projects v2 is GraphQL-only and needs a separate `organization_projects` App permission not yet granted, so |
| 66 | + * those two methods are inert placeholders until #3184. */ |
| 67 | +export class GitHubMilestonesAdapter implements ProjectTrackerAdapter { |
| 68 | + // Inert placeholder until #3184 (Projects v2 needs GraphQL + a separate App permission). |
| 69 | + async listOpenProjects(): Promise<ProjectTrackerRef[]> { |
| 70 | + return []; |
| 71 | + } |
| 72 | + |
| 73 | + async listOpenMilestones(ctx: ProjectTrackerContext): Promise<ProjectTrackerRef[]> { |
| 74 | + const { owner, repo } = parseRepoFullName(ctx.repoFullName); |
| 75 | + const token = await createInstallationToken(ctx.env, ctx.installationId); |
| 76 | + const octokit = makeInstallationOctokit(ctx.env, token, "live", githubRateLimitAdmissionKeyForInstallation(ctx.installationId)); |
| 77 | + const milestones: GitHubMilestone[] = []; |
| 78 | + for (let page = 1; page <= GITHUB_LIST_PAGE_LIMIT; page += 1) { |
| 79 | + const response = await octokit.request("GET /repos/{owner}/{repo}/milestones", { |
| 80 | + owner, |
| 81 | + repo, |
| 82 | + state: "open", |
| 83 | + per_page: 100, |
| 84 | + page, |
| 85 | + }); |
| 86 | + const batch = response.data as GitHubMilestone[]; |
| 87 | + milestones.push(...batch); |
| 88 | + if (batch.length < 100) break; |
| 89 | + } |
| 90 | + return milestones.map((milestone) => ({ id: String(milestone.number), title: milestone.title })); |
| 91 | + } |
| 92 | + |
| 93 | + // Inert placeholder until #3184 (Projects v2 needs GraphQL + a separate App permission). |
| 94 | + async attachToProject(): Promise<ProjectTrackerAttachResult> { |
| 95 | + return { attached: false }; |
| 96 | + } |
| 97 | + |
| 98 | + async attachToMilestone(ctx: ProjectTrackerContext, pullNumber: number, milestoneId: string): Promise<ProjectTrackerAttachResult> { |
| 99 | + const milestoneNumber = parsePositiveIntegerId(milestoneId); |
| 100 | + if (milestoneNumber === null) return { attached: false }; |
| 101 | + const { owner, repo } = parseRepoFullName(ctx.repoFullName); |
| 102 | + const token = await createInstallationToken(ctx.env, ctx.installationId); |
| 103 | + const octokit = makeInstallationOctokit(ctx.env, token, "live", githubRateLimitAdmissionKeyForInstallation(ctx.installationId)); |
| 104 | + await octokit.request("PATCH /repos/{owner}/{repo}/issues/{issue_number}", { |
| 105 | + owner, |
| 106 | + repo, |
| 107 | + issue_number: pullNumber, |
| 108 | + milestone: milestoneNumber, |
| 109 | + }); |
| 110 | + return { attached: true }; |
| 111 | + } |
| 112 | +} |
| 113 | + |
| 114 | +// Stricter than the duplicate-PR collision gate's 0.58/2 (src/signals/engine.ts) -- misattaching a PR to the |
| 115 | +// wrong milestone corrupts tracked progress, whereas a missed duplicate just skips an advisory note. |
| 116 | +const MILESTONE_MATCH_MIN_SCORE = 0.65; |
| 117 | +const MILESTONE_MATCH_MIN_SHARED = 3; |
| 118 | + |
| 119 | +export type ProjectTrackerMatch = { |
| 120 | + milestone: ProjectTrackerRef; |
| 121 | + score: number; |
| 122 | + shared: number; |
| 123 | +}; |
| 124 | + |
| 125 | +function termsFor(value: string): CollisionTerms { |
| 126 | + const terms = new Set(tokenize(value)); |
| 127 | + return { terms, size: terms.size }; |
| 128 | +} |
| 129 | + |
| 130 | +/** |
| 131 | + * Match PR title+body text against a list of open milestones (#3183), reusing the same tokenize/termOverlap |
| 132 | + * heuristic as duplicate-PR collision detection. Returns null on no match -- AND on an ambiguous multi-match |
| 133 | + * (more than one milestone clears the threshold): guessing between two plausible milestones is worse than |
| 134 | + * suggesting neither, since a maintainer can always link one manually. |
| 135 | + */ |
| 136 | +export function matchOpenMilestones(prTitle: string, prBody: string | null | undefined, milestones: ProjectTrackerRef[]): ProjectTrackerMatch | null { |
| 137 | + if (milestones.length === 0) return null; |
| 138 | + const prTerms = termsFor([prTitle, prBody ?? ""].join(" ")); |
| 139 | + const candidates = milestones |
| 140 | + .map((milestone) => ({ milestone, ...termOverlap(prTerms, termsFor(milestone.title)) })) |
| 141 | + .filter((candidate) => candidate.score >= MILESTONE_MATCH_MIN_SCORE && candidate.shared >= MILESTONE_MATCH_MIN_SHARED); |
| 142 | + if (candidates.length !== 1) return null; |
| 143 | + const best = candidates[0]; |
| 144 | + /* v8 ignore next -- defensive: candidates.length === 1 above guarantees index 0 exists. */ |
| 145 | + if (!best) return null; |
| 146 | + return { milestone: best.milestone, score: best.score, shared: best.shared }; |
| 147 | +} |
| 148 | + |
| 149 | +export const MILESTONE_SUGGEST_COMMENT_MARKER = "<!-- gittensory-milestone-suggest:v1 -->"; |
| 150 | + |
| 151 | +/** Code-formats a maintainer-authored title for safe Markdown embedding: backticks strip any literal backtick |
| 152 | + * from the title (so it can't break out of the code span) rather than escaping them, since a broken-out title |
| 153 | + * could otherwise re-enable `@mentions` or `**`/`_` emphasis the code span exists to neutralize. */ |
| 154 | +function codeFormat(title: string): string { |
| 155 | + return `\`${title.replace(/`/g, "")}\``; |
| 156 | +} |
| 157 | + |
| 158 | +function renderSuggestionComment(match: ProjectTrackerMatch): string { |
| 159 | + const confidencePercent = Math.round(match.score * 100); |
| 160 | + return [ |
| 161 | + MILESTONE_SUGGEST_COMMENT_MARKER, |
| 162 | + `This PR looks like it's part of the ${codeFormat(match.milestone.title)} milestone (${confidencePercent}% title/body term overlap).`, |
| 163 | + "", |
| 164 | + "This is an advisory suggestion only — nothing has been attached automatically.", |
| 165 | + ].join("\n"); |
| 166 | +} |
| 167 | + |
| 168 | +type IssueComment = { |
| 169 | + body?: string | null; |
| 170 | + user?: { type?: string; login?: string } | null; |
| 171 | +}; |
| 172 | + |
| 173 | +/** |
| 174 | + * Best-effort, idempotent suggest-mode comment (#3183): posts ONCE per PR (never updates or reposts), so a |
| 175 | + * repeated sweep/webhook pass never spams the thread. Never calls attachToMilestone -- suggest mode only ever |
| 176 | + * comments; #3185 wires the real attach path behind the "auto" config value. |
| 177 | + */ |
| 178 | +export async function maybeSuggestMilestoneMatch(ctx: ProjectTrackerContext, pullNumber: number, prTitle: string, prBody: string | null | undefined): Promise<{ suggested: boolean }> { |
| 179 | + const adapter = new GitHubMilestonesAdapter(); |
| 180 | + const milestones = await adapter.listOpenMilestones(ctx); |
| 181 | + const match = matchOpenMilestones(prTitle, prBody, milestones); |
| 182 | + if (!match) return { suggested: false }; |
| 183 | + |
| 184 | + const { owner, repo } = parseRepoFullName(ctx.repoFullName); |
| 185 | + const token = await createInstallationToken(ctx.env, ctx.installationId); |
| 186 | + const octokit = makeInstallationOctokit(ctx.env, token, "live", githubRateLimitAdmissionKeyForInstallation(ctx.installationId)); |
| 187 | + const botLogin = `${ctx.env.GITHUB_APP_SLUG}[bot]`; |
| 188 | + let alreadyPosted = false; |
| 189 | + for (let page = 1; page <= GITHUB_LIST_PAGE_LIMIT && !alreadyPosted; page += 1) { |
| 190 | + const existing = await octokit.request("GET /repos/{owner}/{repo}/issues/{issue_number}/comments", { |
| 191 | + owner, |
| 192 | + repo, |
| 193 | + issue_number: pullNumber, |
| 194 | + per_page: 100, |
| 195 | + page, |
| 196 | + }); |
| 197 | + const batch = existing.data as IssueComment[]; |
| 198 | + alreadyPosted = batch.some((comment) => comment.user?.type === "Bot" && comment.user.login?.toLowerCase() === botLogin.toLowerCase() && comment.body?.includes(MILESTONE_SUGGEST_COMMENT_MARKER)); |
| 199 | + if (batch.length < 100) break; |
| 200 | + } |
| 201 | + if (alreadyPosted) return { suggested: false }; |
| 202 | + |
| 203 | + await createIssueComment(ctx.env, ctx.installationId, ctx.repoFullName, pullNumber, renderSuggestionComment(match)); |
| 204 | + return { suggested: true }; |
| 205 | +} |
| 206 | + |
| 207 | +/** |
| 208 | + * Webhook-level entry point (#3183): folds the "should this even run" gating (installed app, PR still open, |
| 209 | + * feature opted in) AND the best-effort error logging into one call, so the PR-webhook handler in |
| 210 | + * processors.ts has a single, unconditional call site with no logic/logging body of its own -- everything |
| 211 | + * testable lives here, where it already has dedicated, isolated coverage, rather than in an inline closure |
| 212 | + * inside the huge webhook file that only a full pipeline test could exercise. |
| 213 | + */ |
| 214 | +export async function maybeSuggestMilestoneMatchForPr(args: { |
| 215 | + env: Env; |
| 216 | + installationId: number | null | undefined; |
| 217 | + repoFullName: string; |
| 218 | + pullNumber: number; |
| 219 | + prState: string; |
| 220 | + prTitle: string; |
| 221 | + prBody: string | null | undefined; |
| 222 | + mode: ProjectMilestoneMatchModeInput; |
| 223 | + deliveryId: string; |
| 224 | +}): Promise<void> { |
| 225 | + if (!args.installationId) return; |
| 226 | + if (args.prState !== "open") return; |
| 227 | + if (!args.mode || args.mode === "off") return; |
| 228 | + await maybeSuggestMilestoneMatch({ env: args.env, installationId: args.installationId, repoFullName: args.repoFullName }, args.pullNumber, args.prTitle, args.prBody).catch((error) => { |
| 229 | + console.error( |
| 230 | + JSON.stringify({ |
| 231 | + level: "warn", |
| 232 | + event: "milestone_suggest_failed", |
| 233 | + deliveryId: args.deliveryId, |
| 234 | + repoFullName: args.repoFullName, |
| 235 | + pullNumber: args.pullNumber, |
| 236 | + error: errorMessage(error), |
| 237 | + }), |
| 238 | + ); |
| 239 | + }); |
| 240 | +} |
| 241 | + |
| 242 | +// Kept as a standalone alias (rather than importing RepositorySettings from ../types) so this integrations |
| 243 | +// module has no dependency on the settings type -- it only needs to know "off" vs. anything else. |
| 244 | +type ProjectMilestoneMatchModeInput = "off" | "suggest" | "auto" | null | undefined; |
0 commit comments