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

pullRequestWatch.ts

400 lines17.1 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: "merge-queue-removed"; readonly reason: string | null };
25​
26export interface PullRequestWatchReport {
27 readonly changes: ReadonlyArray<PullRequestWatchChange>;
28 readonly next: ThreadPullRequestWatch;
29 readonly exhausted: boolean;
31​
32const isFailedCheck = (check: PullRequestCheck) =>
33 check.status === "failure" || check.status === "cancelled";
34​
35// A GitHub Actions job's URL extends its workflow run's URL; their names need not match.
36const workflowRunOf = (url: string | null) => url?.match(/^.*\/actions\/runs\/\d+/)?.[0] ?? null;
37const approvalKey = (check: PullRequestCheck) => workflowRunOf(check.url) ?? check.name;
38​
39export function evaluatePullRequestWatch(
40 watch: ThreadPullRequestWatch,
41 detail: Pick<
42 PullRequestDetail,
43 | "capabilities"
44 | "headSha"
45 | "checks"
46 | "mergeability"
47 | "viewer"
48 | "author"
49 | "mergeQueueRemoval"
50 >,
51 remarks: ReadonlyArray<PullRequestComment> | null,
52 now: number,
53): PullRequestWatchReport {
54 const changes: Array<PullRequestWatchChange> = [];
55 // A read without a head says nothing about pushes, so it keeps the last known one.
56 const headSha = detail.headSha ?? watch.headSha;
57 const headMoved = watch.headSha !== null && headSha !== watch.headSha;
58 const checksBaseline = watch.awaitingBaseline !== undefined && !headMoved;
59​
60 // Hosts can return no checks on read failure; preserve prior state.
61 let failedChecks = headMoved ? [] : watch.failedChecks;
62 let passed = headMoved ? false : watch.passed;
63 let passedChecks = headMoved ? [] : watch.passedChecks;
64 let owedChecks = headMoved ? [] : (watch.owedChecks ?? []);
65 let awaitingApproval = headMoved ? [] : (watch.awaitingApproval ?? []);
66 let approvalAnnounced = headMoved ? false : (watch.approvalAnnounced ?? false);
67 // An unavailable approval read cannot establish success or that no checks exist.
68 const unread = detail.checks.some((check) => check.placeholder === true);
69 const checks = detail.checks.filter((check) => check.placeholder !== true);
70 const failed = checks.filter(isFailedCheck);
71 const awaiting = checks.filter((check) => check.status === "action-required");
72 if (checks.length > 0) {
73 const newlyFailed = failed.filter((check) => !failedChecks.includes(check.name));
74 if (!checksBaseline && newlyFailed.length > 0) {
75 changes.push({ kind: "checks-failed", failed: newlyFailed });
76 }
77 if (!approvalAnnounced && awaiting.length > 0) {
78 if (!checksBaseline) changes.push({ kind: "checks-awaiting-approval", checks: awaiting });
79 approvalAnnounced = true;
80 }
81 failedChecks = failed.map((check) => check.name);
82​
83 // Approval reads can omit gated runs. Keep each hold until its jobs finish.
84 const awaitingNow = [...new Set(awaiting.map(approvalKey))];
85 const nameUnfinished = (name: string) => {
86 const matching = checks.filter((check) => check.name === name);
87 return (
88 matching.length === 0 ||
89 matching.some((check) => check.status === "pending" || check.status === "action-required")
90 );
91 };
92 // GitHub deduplicates jobs across runs, so a visible pending job may hide one in an awaited run.
93 // A pending check without a URL could be such a job; one with another host's URL cannot.
94 const jobsPending = checks.some(
95 (check) =>
96 check.status === "pending" && (check.url === null || workflowRunOf(check.url) !== null),
97 );
98 const finished = new Set(
99 jobsPending
100 ? []
101 : checks
102 .filter((check) => check.status !== "action-required" && check.status !== "pending")
103 .map((check) => workflowRunOf(check.url)),
104 );
105 awaitingApproval = [
106 ...awaitingNow,
107 ...awaitingApproval.filter(
108 (key) =>
109 !awaitingNow.includes(key) &&
110 (workflowRunOf(key) === key ? !finished.has(key) : nameUnfinished(key)),
111 ),
112 ];
113 }
114 const required = checks.filter((check) => check.required === true);
115 const gate = required.length > 0 ? required : checks;
116 const passedNow =
117 awaitingApproval.length === 0 &&
118 gate.every((check) => check.status !== "pending" && !isFailedCheck(check));
119 if (checks.length > 0 && !(unread && passedNow)) {
120 const gateNames = gate.map((check) => check.name);
121 const told = passed && passedChecks.length === 0 ? gateNames : passedChecks;
122 // Required checks can finish between sweeps; detect new names. With no required checks, ignore advisory gate growth.
123 const gateGrew = required.length > 0 && gateNames.some((name) => !told.includes(name));
124 // Other checks still pending when required ones passed are owed one wake when all settle.
125 // Only those are owed, so later advisory churn never wakes. One turned required is gate news.
126 const owed =
127 passedNow && passed
128 ? checks
129 .filter((check) => check.required !== true && owedChecks.includes(check.name))
130 .map((check) => check.name)
131 : [];
132 const settled =
133 failed.length === 0 &&
134 awaitingApproval.length === 0 &&
135 checks.every((check) => check.status !== "pending");
136 owedChecks = owed;
137 if (passedNow && (!passed || gateGrew)) {
138 if (!checksBaseline) {
139 changes.push({ kind: "checks-passed", count: gate.length, required: required.length > 0 });
140 }
141 owedChecks =
142 required.length > 0
143 ? checks
144 .filter((check) => check.required !== true && check.status === "pending")
145 .map((check) => check.name)
146 : [];
147 } else if (settled && owed.length > 0) {
148 changes.push({ kind: "checks-passed", count: checks.length, required: false });
149 owedChecks = [];
150 }
151 passed = passedNow;
152 passedChecks = passedNow ? gateNames : [];
153 }
154​
155 // Only a head never read with checks waits for them: an empty read after checks were seen is
156 // the failed read above. A watch saved before this field may have seen pending checks on its
157 // head, so its clock starts only at the next push. Where a host's empty list can mean the
158 // repository runs no checks at all, nothing waits.
159 let checksAwaitedSince = watch.checksAwaitedSince;
160 if (detail.capabilities.checksAlwaysReport === true) {
161 const awaitedBefore =
162 headMoved || watch.awaitingBaseline === "all"
163 ? DateTime.formatIso(DateTime.makeUnsafe(now))
164 : (watch.checksAwaitedSince ?? null);
165 checksAwaitedSince = checks.length > 0 ? null : awaitedBefore;
166 const awaitedMs = checksAwaitedSince === null ? 0 : now - Date.parse(checksAwaitedSince);
167 if (!unread && awaitedMs >= PULL_REQUEST_WATCH_NO_CHECKS_MS) {
168 changes.push({ kind: "no-checks", minutes: Math.round(awaitedMs / 60_000) });
169 checksAwaitedSince = null;
170 }
171 }
172​
173 const own = (detail.viewer ?? detail.author?.login)?.toLowerCase();
174 const through = Date.parse(watch.remarksThrough);
175 const activeAt = (remark: PullRequestComment) => remark.editedAt ?? remark.createdAt;
176 // Hosts can stamp remarks to the second, so remarks at the boundary time are told apart by ID.
177 const fresh = (remarks ?? []).filter((remark) => {
178 const at = Date.parse(activeAt(remark));
179 return (
180 (at > through || (at === through && !watch.remarkIds.includes(remark.id))) &&
181 remark.author?.login.toLowerCase() !== own
182 );
183 });
184 if (fresh.length > 0) changes.push({ kind: "remarks", remarks: fresh });
185 const latest = Math.max(through, ...fresh.map((remark) => Date.parse(activeAt(remark))));
186 const atLatest = fresh.filter((remark) => Date.parse(activeAt(remark)) === latest);
187 const remarksThrough = latest === through ? watch.remarksThrough : activeAt(atLatest[0]!);
188 const remarkIds = [
189 ...(latest === through ? watch.remarkIds : []),
190 ...atLatest.map((remark) => remark.id),
191 ];
192​
193 // Like a failed check, a conflict a push did not resolve is news for the new head.
194 const toldConflict = !headMoved && watch.conflicting;
195 if (watch.awaitingBaseline !== "all" && detail.mergeability === "conflicting" && !toldConflict) {
196 changes.push({ kind: "conflicting" });
197 }
198 // "unknown" is a host still computing after a push; only a clean answer clears a conflict.
199 const conflicting =
200 detail.mergeability === "unknown" ? toldConflict : detail.mergeability === "conflicting";
201​
202 // The queue's checks run on a commit of its own, so its head can stay green after the queue
203 // drops it. After the first read, IDs avoid comparing the server clock with the host clock.
204 // The initial read uses whole seconds to exclude historical removals.
205 const removal = detail.mergeQueueRemoval;
206 if (
207 removal !== undefined &&
208 // Merging also records a removal, up to a second before the pull request reads as merged.
209 removal.reason !== "merged" &&
210 removal.id !== watch.mergeQueueRemovalId &&
211 (watch.mergeQueueRemovalId !== undefined ||
212 Date.parse(removal.removedAt) >= Math.floor(Date.parse(watch.startedAt) / 1000) * 1000)
213 ) {
214 changes.push({ kind: "merge-queue-removed", reason: removal.reason });
215 }
216 // Null records an empty baseline; historical IDs are saved without waking the watch.
217 const mergeQueueRemovalId = removal?.id ?? watch.mergeQueueRemovalId ?? null;
218​
219 const commentsOnly = changes.length > 0 && changes.every((change) => change.kind === "remarks");
220 const progress = headMoved || (changes.length > 0 && !commentsOnly);
221 const wakes = (progress ? 0 : watch.wakes) + (commentsOnly ? 1 : 0);
222 return {
223 changes,
224 next: {
225 startedAt: watch.startedAt,
226 headSha,
227 failedChecks,
228 passed,
229 passedChecks,
230 owedChecks,
231 awaitingApproval,
232 approvalAnnounced,
233 remarksThrough,
234 remarkIds,
235 conflicting,
236 mergeQueueRemovalId,
237 wakes,
238 // Only a read that cannot be trusted to show the checks leaves the baseline to the next one.
239 ...(checksBaseline &&
240 (unread || (detail.headSha === undefined && checks.length === 0)) && {
241 awaitingBaseline: "checks" as const,
242 }),
243 checksAwaitedSince,
244 },
245 exhausted: commentsOnly && wakes >= PULL_REQUEST_WATCH_WAKE_LIMIT,
246 };
248​
249function snippet(body: string): string {
250 const text = body
251 .replaceAll(/<!--[\s\S]*?-->/g, " ")
252 .replaceAll(/\s+/g, " ")
253 .trim();
254 if (text.length <= SNIPPET_LENGTH) return text;
255 // Half an emoji serializes to a lone surrogate escape, which provider JSON parsers reject.
256 const last = text.charCodeAt(SNIPPET_LENGTH - 4);
257 const end = last >= 0xd800 && last <= 0xdbff ? SNIPPET_LENGTH - 4 : SNIPPET_LENGTH - 3;
258 return `${text.slice(0, end)}...`;
260​
261function listed<T>(items: ReadonlyArray<T>, line: (item: T) => string): Array<string> {
262 const lines = items.slice(0, LISTED_ITEMS).map(line);
263 if (items.length > LISTED_ITEMS) lines.push(` - and ${items.length - LISTED_ITEMS} more`);
264 return lines;
266​
267function changeLines(
268 change: PullRequestWatchChange,
269 context: { readonly baseBranch: string; readonly commit: string },
270): Array<string> {
271 switch (change.kind) {
272 case "checks-failed":
273 return [
274 `- Checks failed${context.commit}:`,
275 ...listed(
276 change.failed,
277 (check) =>
278 ` - ${check.name}${check.status === "failure" ? "" : ` (${check.status})`}${check.url ? ` ${check.url}` : ""}`,
279 ),
280 ];
281 case "checks-awaiting-approval":
282 return [
283 `- Checks are waiting for approval or action from a maintainer${context.commit}:`,
284 ...listed(change.checks, (check) => ` - ${check.name}${check.url ? ` ${check.url}` : ""}`),
285 ];
286 case "checks-passed":
287 return [
288 `- All ${change.count} ${change.required ? "required " : ""}${change.count === 1 ? "check" : "checks"} passed${context.commit}.`,
289 ];
290 case "remarks":
291 return [
292 `- ${change.remarks.length} new ${change.remarks.length === 1 ? "comment" : "comments"}:`,
293 ...listed(change.remarks, (remark) => {
294 const where = remark.path === null ? "" : ` on ${remark.path}`;
295 const body = snippet(remark.body);
296 const said = body.length === 0 ? (remark.reviewState ?? "reviewed") : `"${body}"`;
297 return ` - ${remark.author?.login ?? "someone"}${where}: ${said}${remark.url ? ` ${remark.url}` : ""}`;
298 }),
299 ];
300 case "no-checks":
301 return [
302 `- No checks have reported${context.commit} after ${change.minutes} minutes. None may be configured to run on this change.`,
303 ];
304 case "conflicting":
305 return [`- The branch now conflicts with ${context.baseBranch}.`];
306 case "merge-queue-removed":
307 return [
308 `- It was removed from the merge queue without merging${change.reason === null ? "" : `: ${change.reason}`}.`,
309 ];
310 }
312​
313const SUMMARY: Record<PullRequestWatchChange["kind"], string> = {
314 "checks-failed": "checks failed",
315 "checks-passed": "checks passed",
316 "checks-awaiting-approval": "checks await approval",
317 remarks: "new comments",
318 "no-checks": "no checks reported",
319 conflicting: "merge conflict",
320 "merge-queue-removed": "removed from merge queue",
321};
322​
323const WATCHING_CLOSING =
324 "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.";
325const WATCHING_CLOSING_PLURAL =
326 "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.";
327​
328export interface PullRequestWatchWake {
329 readonly text: string;
330 readonly notification: OrchestrationV2Notification;
332​
333/** One wake for news on several pull requests, with the closing instructions said once. */
334export function combinePullRequestWatchWakes(
335 wakes: readonly [PullRequestWatchWake, ...ReadonlyArray<PullRequestWatchWake>],
336): PullRequestWatchWake {
337 if (wakes.length === 1) return wakes[0];
338 const closing = `\n\n${WATCHING_CLOSING}`;
339 const watching = wakes.some((wake) => wake.text.endsWith(closing));
340 const outcomes = wakes.map((wake) => wake.notification.outcome);
341 return {
342 text: [
343 ...wakes.map((wake) =>
344 wake.text.endsWith(closing) ? wake.text.slice(0, -closing.length) : wake.text,
345 ),
346 ...(watching ? [WATCHING_CLOSING_PLURAL] : []),
347 ].join("\n\n"),
348 notification: {
349 source: { kind: "monitor" },
350 outcome: outcomes.includes("failed")
351 ? "failed"
352 : outcomes.every((outcome) => outcome === "completed")
353 ? "completed"
354 : "updated",
355 summary: wakes.map((wake) => wake.notification.summary).join("; "),
356 },
357 };
359​
360export function pullRequestWatchMessage(input: {
361 readonly number: number;
362 readonly url: string;
363 readonly baseBranch: string;
364 readonly headSha: string | null;
365 readonly report: PullRequestWatchReport;
366}): { readonly text: string; readonly notification: OrchestrationV2Notification } {
367 const { changes, exhausted } = input.report;
368 const context = {
369 baseBranch: input.baseBranch,
370 commit: input.headSha === null ? "" : ` on ${input.headSha.slice(0, 7)}`,
371 };
372 const text = [
373 `Update on pull request #${input.number} (${input.url}), which T3 Code is watching for you:`,
374 ...changes.flatMap((change) => changeLines(change, context)),
375 "",
376 exhausted
377 ? `T3 Code stopped watching after ${PULL_REQUEST_WATCH_WAKE_LIMIT} comment-only updates in a row. Call watch_pull_request to watch it again.`
378 : WATCHING_CLOSING,
379 ].join("\n");
380 const failed = changes.some(
381 (change) =>
382 change.kind === "checks-failed" ||
383 change.kind === "conflicting" ||
384 change.kind === "merge-queue-removed",
385 );
386 const summary = changes.map((change) => SUMMARY[change.kind]);
387 if (exhausted) summary.push("stopped watching");
388 return {
389 text,
390 notification: {
391 source: { kind: "monitor" },
392 outcome: failed
393 ? "failed"
394 : changes.every((change) => change.kind === "checks-passed")
395 ? "completed"
396 : "updated",
397 summary: `#${input.number}: ${summary.join(", ")}`,
398 },
399 };