Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

pullRequestWatch.ts

564 lines24.3 KB

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