The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | import type { |
| 2 | OrchestrationV2Notification, |
| 3 | PullRequestCheck, |
| 4 | PullRequestComment, |
| 5 | PullRequestDetail, |
| 6 | ThreadPullRequestWatch, |
| 7 | } from "@t3tools/contracts"; |
| 8 | import * as DateTime from "effect/DateTime"; |
| 9 | |
| 10 | /** Bounds consecutive comment-only wakes to stop bot reply loops; check, conflict, or push news resets it. */ |
| 11 | export const PULL_REQUEST_WATCH_WAKE_LIMIT = 10; |
| 12 | /** How long a head may go without any check before the agent is told none reported. */ |
| 13 | export const PULL_REQUEST_WATCH_NO_CHECKS_MS = 15 * 60_000; |
| 14 | const LISTED_ITEMS = 10; |
| 15 | const SNIPPET_LENGTH = 200; |
| 16 | |
| 17 | export type PullRequestWatchChange = |
| 18 | | { readonly kind: "checks-failed"; readonly failed: ReadonlyArray<PullRequestCheck> } |
| 19 | | { readonly kind: "checks-passed"; readonly count: number; readonly required: boolean } |
| 20 | | { |
| 21 | readonly kind: "checks-finished"; |
| 22 | readonly passed: number; |
| 23 | readonly failing: ReadonlyArray<PullRequestCheck>; |
| 24 | } |
| 25 | | { readonly kind: "checks-awaiting-approval"; readonly checks: ReadonlyArray<PullRequestCheck> } |
| 26 | | { readonly kind: "remarks"; readonly remarks: ReadonlyArray<PullRequestComment> } |
| 27 | | { readonly kind: "no-checks"; readonly minutes: number } |
| 28 | | { readonly kind: "conflicting" } |
| 29 | | { readonly kind: "needs-rebase" } |
| 30 | | { readonly kind: "merge-queue-removed"; readonly reason: string | null }; |
| 31 | |
| 32 | export interface PullRequestWatchReport { |
| 33 | readonly changes: ReadonlyArray<PullRequestWatchChange>; |
| 34 | readonly next: ThreadPullRequestWatch; |
| 35 | readonly exhausted: boolean; |
| 36 | } |
| 37 | |
| 38 | const isFailedCheck = (check: PullRequestCheck) => |
| 39 | check.status === "failure" || check.status === "cancelled"; |
| 40 | |
| 41 | // A GitHub Actions job's URL extends its workflow run's URL; their names need not match. |
| 42 | const workflowRunOf = (url: string | null) => url?.match(/^.*\/actions\/runs\/\d+/)?.[0] ?? null; |
| 43 | const approvalKey = (check: PullRequestCheck) => workflowRunOf(check.url) ?? check.name; |
| 44 | |
| 45 | export function evaluatePullRequestWatch( |
| 46 | watch: ThreadPullRequestWatch, |
| 47 | detail: Pick< |
| 48 | PullRequestDetail, |
| 49 | | "capabilities" |
| 50 | | "headSha" |
| 51 | | "checks" |
| 52 | | "mergeability" |
| 53 | | "viewer" |
| 54 | | "author" |
| 55 | | "rebaseRequired" |
| 56 | | "mergeQueueRemoval" |
| 57 | >, |
| 58 | remarks: ReadonlyArray<PullRequestComment> | null, |
| 59 | now: number, |
| 60 | ): PullRequestWatchReport { |
| 61 | const changes: Array<PullRequestWatchChange> = []; |
| 62 | // A read without a head says nothing about pushes, so it keeps the last known one. |
| 63 | const headSha = detail.headSha ?? watch.headSha; |
| 64 | const headMoved = watch.headSha !== null && headSha !== watch.headSha; |
| 65 | const checksBaseline = watch.awaitingBaseline !== undefined && !headMoved; |
| 66 | |
| 67 | // Hosts can return no checks on read failure; preserve prior state. |
| 68 | let failedChecks = headMoved ? [] : watch.failedChecks; |
| 69 | let passed = headMoved ? false : watch.passed; |
| 70 | let passedChecks = headMoved ? [] : watch.passedChecks; |
| 71 | let owedChecks = headMoved ? [] : (watch.owedChecks ?? []); |
| 72 | const owedBefore = owedChecks; |
| 73 | let awaitingApproval = headMoved ? [] : (watch.awaitingApproval ?? []); |
| 74 | let approvalAnnounced = headMoved ? false : (watch.approvalAnnounced ?? false); |
| 75 | // A watch with no answer (saved before the field, or since a push) waits only while the clock |
| 76 | // below runs. |
| 77 | let checksPending = headMoved ? false : (watch.checksPending ?? watch.checksAwaitedSince != null); |
| 78 | // An unavailable approval read cannot establish success or that no checks exist. |
| 79 | const unread = detail.checks.some((check) => check.placeholder === true); |
| 80 | const checks = detail.checks.filter((check) => check.placeholder !== true); |
| 81 | const failed = checks.filter(isFailedCheck); |
| 82 | const awaiting = checks.filter((check) => check.status === "action-required"); |
| 83 | const failedBefore = failedChecks; |
| 84 | const newlyFailed = failed.filter((check) => !failedBefore.includes(check.name)); |
| 85 | if (checks.length > 0) { |
| 86 | // A run awaiting approval waits on a person, like a review, so only running checks count. |
| 87 | // An unfinished baseline read keeps the seed below for the next one. |
| 88 | checksPending = |
| 89 | checks.some((check) => check.status === "pending") || |
| 90 | (checksBaseline && unread && watch.checksPending === true); |
| 91 | // The baseline hides failures from before the watch, but CI running at the start can fail |
| 92 | // before the first read. |
| 93 | if (newlyFailed.length > 0 && (!checksBaseline || watch.checksPending === true)) { |
| 94 | changes.push({ kind: "checks-failed", failed: newlyFailed }); |
| 95 | } |
| 96 | if (!approvalAnnounced && awaiting.length > 0) { |
| 97 | if (!checksBaseline) changes.push({ kind: "checks-awaiting-approval", checks: awaiting }); |
| 98 | approvalAnnounced = true; |
| 99 | } |
| 100 | failedChecks = failed.map((check) => check.name); |
| 101 | |
| 102 | // Approval reads can omit gated runs. Keep each hold until its jobs finish. |
| 103 | const awaitingNow = [...new Set(awaiting.map(approvalKey))]; |
| 104 | const nameUnfinished = (name: string) => { |
| 105 | const matching = checks.filter((check) => check.name === name); |
| 106 | return ( |
| 107 | matching.length === 0 || |
| 108 | matching.some((check) => check.status === "pending" || check.status === "action-required") |
| 109 | ); |
| 110 | }; |
| 111 | // GitHub deduplicates jobs across runs, so a visible pending job may hide one in an awaited run. |
| 112 | // A pending check without a URL could be such a job; one with another host's URL cannot. |
| 113 | const jobsPending = checks.some( |
| 114 | (check) => |
| 115 | check.status === "pending" && (check.url === null || workflowRunOf(check.url) !== null), |
| 116 | ); |
| 117 | const finished = new Set( |
| 118 | jobsPending |
| 119 | ? [] |
| 120 | : checks |
| 121 | .filter((check) => check.status !== "action-required" && check.status !== "pending") |
| 122 | .map((check) => workflowRunOf(check.url)), |
| 123 | ); |
| 124 | awaitingApproval = [ |
| 125 | ...awaitingNow, |
| 126 | ...awaitingApproval.filter( |
| 127 | (key) => |
| 128 | !awaitingNow.includes(key) && |
| 129 | (workflowRunOf(key) === key ? !finished.has(key) : nameUnfinished(key)), |
| 130 | ), |
| 131 | ]; |
| 132 | } |
| 133 | const required = checks.filter((check) => check.required === true); |
| 134 | const gate = required.length > 0 ? required : checks; |
| 135 | const passedNow = |
| 136 | awaitingApproval.length === 0 && |
| 137 | gate.every((check) => check.status !== "pending" && !isFailedCheck(check)); |
| 138 | if (checks.length > 0 && !(unread && passedNow)) { |
| 139 | const gateNames = gate.map((check) => check.name); |
| 140 | const told = passed && passedChecks.length === 0 ? gateNames : passedChecks; |
| 141 | // Required checks can finish between sweeps; detect new names. With no required checks, ignore advisory gate growth. |
| 142 | const gateGrew = required.length > 0 && gateNames.some((name) => !told.includes(name)); |
| 143 | // Other checks still pending when required ones passed are owed one wake when all settle. |
| 144 | // Only those are owed, so later advisory churn never wakes. One turned required is gate news. |
| 145 | const owed = |
| 146 | passedNow && passed |
| 147 | ? checks |
| 148 | .filter((check) => check.required !== true && owedChecks.includes(check.name)) |
| 149 | .map((check) => check.name) |
| 150 | : []; |
| 151 | const settled = |
| 152 | failed.length === 0 && |
| 153 | awaitingApproval.length === 0 && |
| 154 | checks.every((check) => check.status !== "pending"); |
| 155 | owedChecks = owed; |
| 156 | if (passedNow && (!passed || gateGrew)) { |
| 157 | if (!checksBaseline) { |
| 158 | changes.push({ kind: "checks-passed", count: gate.length, required: required.length > 0 }); |
| 159 | } |
| 160 | owedChecks = |
| 161 | required.length > 0 |
| 162 | ? checks |
| 163 | .filter((check) => check.required !== true && check.status === "pending") |
| 164 | .map((check) => check.name) |
| 165 | : []; |
| 166 | } else if (settled && owed.length > 0) { |
| 167 | changes.push({ kind: "checks-passed", count: checks.length, required: false }); |
| 168 | owedChecks = []; |
| 169 | } else if (gate.some(isFailedCheck)) { |
| 170 | // A failed gate never sends the passed wake. A failure seen while other checks still run, or |
| 171 | // a failed check that ran again, owes one wake once every check has finished. Only whether |
| 172 | // the list is empty matters here, and the failed checks are never empty. |
| 173 | const rerun = failedBefore.some((name) => !failedChecks.includes(name)); |
| 174 | const running = |
| 175 | unread || |
| 176 | awaitingApproval.length > 0 || |
| 177 | checks.some((check) => check.status === "pending" || check.status === "action-required"); |
| 178 | if (running) { |
| 179 | if (owedBefore.length > 0 || rerun || newlyFailed.length > 0) owedChecks = failedChecks; |
| 180 | } else if (owedBefore.length > 0 || rerun) { |
| 181 | changes.push({ |
| 182 | kind: "checks-finished", |
| 183 | passed: checks.filter((check) => check.status === "success").length, |
| 184 | failing: failed, |
| 185 | }); |
| 186 | } |
| 187 | } |
| 188 | passed = passedNow; |
| 189 | passedChecks = passedNow ? gateNames : []; |
| 190 | } |
| 191 | |
| 192 | // Only a head never read with checks waits for them; a legacy watch's clock starts at its next |
| 193 | // push. CI can register late on any host, so every host waits, but running out of time is news |
| 194 | // only where a host always reports checks: elsewhere an empty list can mean there are none. |
| 195 | const awaitedBefore = |
| 196 | headMoved || watch.awaitingBaseline === "all" |
| 197 | ? DateTime.formatIso(DateTime.makeUnsafe(now)) |
| 198 | : (watch.checksAwaitedSince ?? null); |
| 199 | let checksAwaitedSince = checks.length > 0 ? null : awaitedBefore; |
| 200 | const awaitedMs = checksAwaitedSince === null ? 0 : now - Date.parse(checksAwaitedSince); |
| 201 | if (!unread && awaitedMs >= PULL_REQUEST_WATCH_NO_CHECKS_MS) { |
| 202 | if (detail.capabilities.checksAlwaysReport === true) { |
| 203 | changes.push({ kind: "no-checks", minutes: Math.round(awaitedMs / 60_000) }); |
| 204 | } |
| 205 | checksAwaitedSince = null; |
| 206 | checksPending = false; |
| 207 | } else if (checksAwaitedSince !== null) { |
| 208 | checksPending = true; |
| 209 | } |
| 210 | |
| 211 | const own = (detail.viewer ?? detail.author?.login)?.toLowerCase(); |
| 212 | const through = Date.parse(watch.remarksThrough); |
| 213 | const activeAt = (remark: PullRequestComment) => remark.editedAt ?? remark.createdAt; |
| 214 | // Hosts can stamp remarks to the second, so remarks at the boundary time are told apart by ID. |
| 215 | const fresh = (remarks ?? []).filter((remark) => { |
| 216 | const at = Date.parse(activeAt(remark)); |
| 217 | return ( |
| 218 | (at > through || (at === through && !watch.remarkIds.includes(remark.id))) && |
| 219 | remark.author?.login.toLowerCase() !== own |
| 220 | ); |
| 221 | }); |
| 222 | if (fresh.length > 0) changes.push({ kind: "remarks", remarks: fresh }); |
| 223 | const latest = Math.max(through, ...fresh.map((remark) => Date.parse(activeAt(remark)))); |
| 224 | const atLatest = fresh.filter((remark) => Date.parse(activeAt(remark)) === latest); |
| 225 | const remarksThrough = latest === through ? watch.remarksThrough : activeAt(atLatest[0]!); |
| 226 | const remarkIds = [ |
| 227 | ...(latest === through ? watch.remarkIds : []), |
| 228 | ...atLatest.map((remark) => remark.id), |
| 229 | ]; |
| 230 | |
| 231 | // Like a failed check, a conflict or rebase a push did not resolve is news for the new head. |
| 232 | const toldConflict = !headMoved && watch.conflicting; |
| 233 | if (watch.awaitingBaseline !== "all" && detail.mergeability === "conflicting" && !toldConflict) { |
| 234 | changes.push({ kind: "conflicting" }); |
| 235 | } |
| 236 | const toldRebase = !headMoved && watch.rebaseRequired === true; |
| 237 | if (watch.awaitingBaseline !== "all" && detail.rebaseRequired === true && !toldRebase) { |
| 238 | changes.push({ kind: "needs-rebase" }); |
| 239 | } |
| 240 | const rebaseRequired = detail.rebaseRequired ?? watch.rebaseRequired; |
| 241 | // "unknown" is a host still computing after a push; only a clean answer clears a conflict. |
| 242 | const conflicting = |
| 243 | detail.mergeability === "unknown" ? toldConflict : detail.mergeability === "conflicting"; |
| 244 | |
| 245 | // The queue's checks run on a commit of its own, so its head can stay green after the queue |
| 246 | // drops it. After the first read, IDs avoid comparing the server clock with the host clock. |
| 247 | // The initial read uses whole seconds to exclude historical removals. |
| 248 | const removal = detail.mergeQueueRemoval; |
| 249 | if ( |
| 250 | removal !== undefined && |
| 251 | // Merging also records a removal, up to a second before the pull request reads as merged. |
| 252 | removal.reason !== "merged" && |
| 253 | removal.id !== watch.mergeQueueRemovalId && |
| 254 | (watch.mergeQueueRemovalId !== undefined || |
| 255 | Date.parse(removal.removedAt) >= Math.floor(Date.parse(watch.startedAt) / 1000) * 1000) |
| 256 | ) { |
| 257 | changes.push({ kind: "merge-queue-removed", reason: removal.reason }); |
| 258 | } |
| 259 | // Null records an empty baseline; historical IDs are saved without waking the watch. |
| 260 | const mergeQueueRemovalId = removal?.id ?? watch.mergeQueueRemovalId ?? null; |
| 261 | |
| 262 | const commentsOnly = changes.length > 0 && changes.every((change) => change.kind === "remarks"); |
| 263 | const progress = headMoved || (changes.length > 0 && !commentsOnly); |
| 264 | const wakes = (progress ? 0 : watch.wakes) + (commentsOnly ? 1 : 0); |
| 265 | return { |
| 266 | changes, |
| 267 | next: { |
| 268 | startedAt: watch.startedAt, |
| 269 | headSha, |
| 270 | failedChecks, |
| 271 | passed, |
| 272 | passedChecks, |
| 273 | owedChecks, |
| 274 | awaitingApproval, |
| 275 | approvalAnnounced, |
| 276 | remarksThrough, |
| 277 | remarkIds, |
| 278 | conflicting, |
| 279 | rebaseRequired, |
| 280 | mergeQueueRemovalId, |
| 281 | wakes, |
| 282 | // Only a read that cannot be trusted to show the checks leaves the baseline to the next one. |
| 283 | ...(checksBaseline && |
| 284 | (unread || (detail.headSha === undefined && checks.length === 0)) && { |
| 285 | awaitingBaseline: "checks" as const, |
| 286 | }), |
| 287 | checksAwaitedSince, |
| 288 | checksPending, |
| 289 | ...(watch.until !== undefined && { until: watch.until }), |
| 290 | }, |
| 291 | exhausted: commentsOnly && wakes >= PULL_REQUEST_WATCH_WAKE_LIMIT, |
| 292 | }; |
| 293 | } |
| 294 | |
| 295 | // GitHub renders these, so in a remark's prose they are presentation, not what the reviewer said. |
| 296 | // Lowercase only: `Promise<T>` is a type argument. |
| 297 | const TAG_NAMES = |
| 298 | "a|abbr|b|blockquote|br|caption|cite|code|dd|del|details|div|dl|dt|em|h[1-6]|hr|i|img|ins|kbd|li|mark|ol|p|picture|pre|q|s|samp|small|source|span|strike|strong|sub|summary|sup|table|tbody|td|tfoot|th|thead|tr|tt|ul|var"; |
| 299 | // A code span comes first so its tags stay literal; it cannot cross a blank line. A tag stops at |
| 300 | // the next `<`, which keeps unclosed openers from rescanning the rest of the body. |
| 301 | const PROSE_MARKUP = new RegExp( |
| 302 | "(?<!`)(?<ticks>`+)(?!`)(?:(?!\\n[ \\t\\r]*\\n)[\\s\\S])*?(?<!`)\\k<ticks>(?!`)" + |
| 303 | `|<(?<closing>/?)(?<name>${TAG_NAMES})(?=[\\s/>])(?:[^<>"']|"[^"]*"|'[^']*')*>`, |
| 304 | "g", |
| 305 | ); |
| 306 | |
| 307 | function withoutTags(prose: string): string { |
| 308 | // An opener glued to an identifier is a type argument (`Vec<code>`); it and its closer stay. |
| 309 | const kept = new Map<string, number>(); |
| 310 | let text = ""; |
| 311 | let from = 0; |
| 312 | for (const match of prose.matchAll(PROSE_MARKUP)) { |
| 313 | const name = match.groups?.name; |
| 314 | if (name === undefined) continue; |
| 315 | const held = kept.get(name) ?? 0; |
| 316 | if (match.groups?.closing === "/") { |
| 317 | if (held > 0) { |
| 318 | kept.set(name, held - 1); |
| 319 | continue; |
| 320 | } |
| 321 | } else if (/\w/.test(prose.charAt(match.index - 1))) { |
| 322 | kept.set(name, held + 1); |
| 323 | continue; |
| 324 | } |
| 325 | text += `${prose.slice(from, match.index)} `; |
| 326 | from = match.index + match[0].length; |
| 327 | } |
| 328 | return text + prose.slice(from); |
| 329 | } |
| 330 | |
| 331 | // Drops HTML tags from Markdown prose. Fenced and indented code blocks pass through untouched. |
| 332 | function withoutMarkup(body: string): string { |
| 333 | const parts: Array<string> = []; |
| 334 | let prose: Array<string> = []; |
| 335 | let fence: string | undefined; |
| 336 | let afterText = false; |
| 337 | const code = (line: string) => { |
| 338 | if (prose.length > 0) parts.push(withoutTags(prose.join("\n"))); |
| 339 | prose = []; |
| 340 | parts.push(line); |
| 341 | afterText = false; |
| 342 | }; |
| 343 | for (const line of body.split("\n")) { |
| 344 | if (fence !== undefined) { |
| 345 | const closer = line.trim(); |
| 346 | if (closer.length >= fence.length && closer.replaceAll(fence.charAt(0), "") === "") { |
| 347 | fence = undefined; |
| 348 | } |
| 349 | code(line); |
| 350 | continue; |
| 351 | } |
| 352 | const opener = /^ {0,3}(`{3,}|~{3,})([\s\S]*)$/.exec(line); |
| 353 | if (opener?.[1] !== undefined && !(opener[1].startsWith("`") && opener[2]?.includes("`"))) { |
| 354 | fence = opener[1]; |
| 355 | code(line); |
| 356 | } else if (!afterText && /^(?: {4}| {0,3}\t)\s*\S/.test(line)) { |
| 357 | // Indented code needs a blank line before it; after text the indent is a continuation. |
| 358 | code(line); |
| 359 | } else { |
| 360 | prose.push(line); |
| 361 | afterText = line.trim() !== ""; |
| 362 | } |
| 363 | } |
| 364 | if (prose.length > 0) parts.push(withoutTags(prose.join("\n"))); |
| 365 | return parts.join("\n"); |
| 366 | } |
| 367 | |
| 368 | function snippet(body: string): string { |
| 369 | const text = withoutMarkup(body.replaceAll(/<!--[\s\S]*?-->/g, " ")) |
| 370 | .replaceAll(/\s+/g, " ") |
| 371 | .trim(); |
| 372 | if (text.length <= SNIPPET_LENGTH) return text; |
| 373 | // Half an emoji serializes to a lone surrogate escape, which provider JSON parsers reject. |
| 374 | const last = text.charCodeAt(SNIPPET_LENGTH - 4); |
| 375 | const end = last >= 0xd800 && last <= 0xdbff ? SNIPPET_LENGTH - 4 : SNIPPET_LENGTH - 3; |
| 376 | return `${text.slice(0, end)}...`; |
| 377 | } |
| 378 | |
| 379 | function listed<T>(items: ReadonlyArray<T>, line: (item: T) => string): Array<string> { |
| 380 | const lines = items.slice(0, LISTED_ITEMS).map(line); |
| 381 | if (items.length > LISTED_ITEMS) lines.push(` - and ${items.length - LISTED_ITEMS} more`); |
| 382 | return lines; |
| 383 | } |
| 384 | |
| 385 | const failedCheckLine = (check: PullRequestCheck) => |
| 386 | ` - ${check.name}${check.status === "failure" ? "" : ` (${check.status})`}${check.url ? ` ${check.url}` : ""}`; |
| 387 | |
| 388 | function changeLines( |
| 389 | change: PullRequestWatchChange, |
| 390 | context: { readonly baseBranch: string; readonly commit: string }, |
| 391 | ): Array<string> { |
| 392 | switch (change.kind) { |
| 393 | case "checks-failed": |
| 394 | return [`- Checks failed${context.commit}:`, ...listed(change.failed, failedCheckLine)]; |
| 395 | case "checks-finished": |
| 396 | return [ |
| 397 | `- Every check has finished${context.commit}: ${change.passed} passed, ${change.failing.length} still failing:`, |
| 398 | ...listed(change.failing, failedCheckLine), |
| 399 | ]; |
| 400 | case "checks-awaiting-approval": |
| 401 | return [ |
| 402 | `- Checks are waiting for approval or action from a maintainer${context.commit}:`, |
| 403 | ...listed(change.checks, (check) => ` - ${check.name}${check.url ? ` ${check.url}` : ""}`), |
| 404 | ]; |
| 405 | case "checks-passed": |
| 406 | return [ |
| 407 | `- All ${change.count} ${change.required ? "required " : ""}${change.count === 1 ? "check" : "checks"} passed${context.commit}.`, |
| 408 | ]; |
| 409 | case "remarks": |
| 410 | return [ |
| 411 | `- ${change.remarks.length} new ${change.remarks.length === 1 ? "comment" : "comments"}:`, |
| 412 | ...listed(change.remarks, (remark) => { |
| 413 | const where = remark.path === null ? "" : ` on ${remark.path}`; |
| 414 | const body = snippet(remark.body); |
| 415 | const said = body.length === 0 ? (remark.reviewState ?? "reviewed") : `"${body}"`; |
| 416 | return ` - ${remark.author?.login ?? "someone"}${where}: ${said}${remark.url ? ` ${remark.url}` : ""}`; |
| 417 | }), |
| 418 | ]; |
| 419 | case "no-checks": |
| 420 | return [ |
| 421 | `- No checks have reported${context.commit} after ${change.minutes} minutes. None may be configured to run on this change.`, |
| 422 | ]; |
| 423 | case "needs-rebase": |
| 424 | return [`- The branch requires a rebase onto ${context.baseBranch}.`]; |
| 425 | case "conflicting": |
| 426 | return [`- The branch now conflicts with ${context.baseBranch}.`]; |
| 427 | case "merge-queue-removed": |
| 428 | return [ |
| 429 | `- It was removed from the merge queue without merging${change.reason === null ? "" : `: ${change.reason}`}.`, |
| 430 | ]; |
| 431 | } |
| 432 | } |
| 433 | |
| 434 | const SUMMARY: Record<PullRequestWatchChange["kind"], string> = { |
| 435 | "checks-failed": "checks failed", |
| 436 | "checks-passed": "checks passed", |
| 437 | "checks-finished": "checks finished", |
| 438 | "checks-awaiting-approval": "checks await approval", |
| 439 | remarks: "new comments", |
| 440 | "no-checks": "no checks reported", |
| 441 | conflicting: "merge conflict", |
| 442 | "needs-rebase": "rebase required", |
| 443 | "merge-queue-removed": "removed from merge queue", |
| 444 | }; |
| 445 | |
| 446 | const WATCHING_CLOSING = |
| 447 | "Look into each item and act on it as your task requires. This PR stays linked and watched, so do not link, watch, or list it again. End your turn when you are done, and T3 Code wakes you on the next change. When you hand the work back to the user, call unwatch_pull_request first so the thread returns to their inbox."; |
| 448 | const WATCHING_CLOSING_PLURAL = |
| 449 | "Look into each item and act on it as your task requires. Each PR T3 Code still watches stays linked and watched, so do not link, watch, or list them again. End your turn when you are done, and T3 Code wakes you on the next change. When you hand the work back to the user, call unwatch_pull_request for each first so the thread returns to their inbox."; |
| 450 | |
| 451 | export interface PullRequestWatchWake { |
| 452 | readonly text: string; |
| 453 | readonly notification: OrchestrationV2Notification; |
| 454 | } |
| 455 | |
| 456 | /** One wake for news on several pull requests, with the closing instructions said once. */ |
| 457 | export function combinePullRequestWatchWakes( |
| 458 | wakes: readonly [PullRequestWatchWake, ...ReadonlyArray<PullRequestWatchWake>], |
| 459 | ): PullRequestWatchWake { |
| 460 | if (wakes.length === 1) return wakes[0]; |
| 461 | const closing = `\n\n${WATCHING_CLOSING}`; |
| 462 | const watching = wakes.some((wake) => wake.text.endsWith(closing)); |
| 463 | const outcomes = wakes.map((wake) => wake.notification.outcome); |
| 464 | return { |
| 465 | text: [ |
| 466 | ...wakes.map((wake) => |
| 467 | wake.text.endsWith(closing) ? wake.text.slice(0, -closing.length) : wake.text, |
| 468 | ), |
| 469 | ...(watching ? [WATCHING_CLOSING_PLURAL] : []), |
| 470 | ].join("\n\n"), |
| 471 | notification: { |
| 472 | source: { kind: "monitor" }, |
| 473 | outcome: outcomes.includes("failed") |
| 474 | ? "failed" |
| 475 | : outcomes.every((outcome) => outcome === "completed") |
| 476 | ? "completed" |
| 477 | : "updated", |
| 478 | summary: wakes.map((wake) => wake.notification.summary).join("; "), |
| 479 | }, |
| 480 | }; |
| 481 | } |
| 482 | |
| 483 | export function pullRequestWatchEndMessage(input: { |
| 484 | readonly number: number; |
| 485 | readonly url: string; |
| 486 | readonly detail: Pick<PullRequestDetail, "state" | "baseBranch" | "mergeCommitSha" | "mergedBy">; |
| 487 | }): { readonly text: string; readonly notification: OrchestrationV2Notification } { |
| 488 | const { detail } = input; |
| 489 | const merged = detail.state === "merged"; |
| 490 | const how = merged |
| 491 | ? [ |
| 492 | `was merged into ${detail.baseBranch}`, |
| 493 | detail.mergedBy ? ` by ${detail.mergedBy.login}` : "", |
| 494 | detail.mergeCommitSha ? ` as ${detail.mergeCommitSha.slice(0, 7)}` : "", |
| 495 | ].join("") |
| 496 | : "was closed without merging"; |
| 497 | return { |
| 498 | text: [ |
| 499 | `Pull request #${input.number} (${input.url}) ${how}, so T3 Code stopped watching it.`, |
| 500 | ...(merged ? [] : ["If it is reopened, call watch_pull_request to watch it again."]), |
| 501 | ].join(" "), |
| 502 | notification: { |
| 503 | source: { kind: "monitor" }, |
| 504 | outcome: merged ? "completed" : "updated", |
| 505 | summary: `#${input.number}: ${merged ? "merged" : "closed"}, stopped watching`, |
| 506 | }, |
| 507 | }; |
| 508 | } |
| 509 | |
| 510 | export function pullRequestWatchMessage(input: { |
| 511 | readonly number: number; |
| 512 | readonly url: string; |
| 513 | readonly baseBranch: string; |
| 514 | readonly headSha: string | null; |
| 515 | readonly report: PullRequestWatchReport; |
| 516 | }): { readonly text: string; readonly notification: OrchestrationV2Notification } { |
| 517 | const { changes, exhausted } = input.report; |
| 518 | const context = { |
| 519 | baseBranch: input.baseBranch, |
| 520 | commit: input.headSha === null ? "" : ` on ${input.headSha.slice(0, 7)}`, |
| 521 | }; |
| 522 | const text = [ |
| 523 | `Update on pull request #${input.number} (${input.url}), which T3 Code is watching for you:`, |
| 524 | ...changes.flatMap((change) => changeLines(change, context)), |
| 525 | "", |
| 526 | exhausted |
| 527 | ? `T3 Code stopped watching after ${PULL_REQUEST_WATCH_WAKE_LIMIT} comment-only updates in a row. Call watch_pull_request to watch it again.` |
| 528 | : WATCHING_CLOSING, |
| 529 | ].join("\n"); |
| 530 | const failed = changes.some( |
| 531 | (change) => |
| 532 | change.kind === "checks-failed" || |
| 533 | change.kind === "checks-finished" || |
| 534 | change.kind === "conflicting" || |
| 535 | change.kind === "needs-rebase" || |
| 536 | change.kind === "merge-queue-removed", |
| 537 | ); |
| 538 | const summary = changes.map((change) => SUMMARY[change.kind]); |
| 539 | if (exhausted) summary.push("stopped watching"); |
| 540 | return { |
| 541 | text, |
| 542 | notification: { |
| 543 | source: { kind: "monitor" }, |
| 544 | outcome: failed |
| 545 | ? "failed" |
| 546 | : changes.every((change) => change.kind === "checks-passed") |
| 547 | ? "completed" |
| 548 | : "updated", |
| 549 | summary: `#${input.number}: ${summary.join(", ")}`, |
| 550 | }, |
| 551 | }; |
| 552 | } |