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