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

pullRequestWatch.ts

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