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