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 | { 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;
31}
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 ...(watch.until !== undefined && { until: watch.until }),
260 },
261 exhausted: commentsOnly && wakes >= PULL_REQUEST_WATCH_WAKE_LIMIT,
262 };
263}
264
265// GitHub renders these, so in a remark's prose they are presentation, not what the reviewer said.
266// Lowercase only: `Promise<T>` is a type argument.
267const TAG_NAMES =
268 "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";
269// A code span comes first so its tags stay literal; it cannot cross a blank line. A tag stops at
270// the next `<`, which keeps unclosed openers from rescanning the rest of the body.
271const PROSE_MARKUP = new RegExp(
272 "(?<!`)(?<ticks>`+)(?!`)(?:(?!\\n[ \\t\\r]*\\n)[\\s\\S])*?(?<!`)\\k<ticks>(?!`)" +
273 `|<(?<closing>/?)(?<name>${TAG_NAMES})(?=[\\s/>])(?:[^<>"']|"[^"]*"|'[^']*')*>`,
274 "g",
275);
276
277function withoutTags(prose: string): string {
278 // An opener glued to an identifier is a type argument (`Vec<code>`); it and its closer stay.
279 const kept = new Map<string, number>();
280 let text = "";
281 let from = 0;
282 for (const match of prose.matchAll(PROSE_MARKUP)) {
283 const name = match.groups?.name;
284 if (name === undefined) continue;
285 const held = kept.get(name) ?? 0;
286 if (match.groups?.closing === "/") {
287 if (held > 0) {
288 kept.set(name, held - 1);
289 continue;
290 }
291 } else if (/\w/.test(prose.charAt(match.index - 1))) {
292 kept.set(name, held + 1);
293 continue;
294 }
295 text += `${prose.slice(from, match.index)} `;
296 from = match.index + match[0].length;
297 }
298 return text + prose.slice(from);
299}
300
301// Drops HTML tags from Markdown prose. Fenced and indented code blocks pass through untouched.
302function withoutMarkup(body: string): string {
303 const parts: Array<string> = [];
304 let prose: Array<string> = [];
305 let fence: string | undefined;
306 let afterText = false;
307 const code = (line: string) => {
308 if (prose.length > 0) parts.push(withoutTags(prose.join("\n")));
309 prose = [];
310 parts.push(line);
311 afterText = false;
312 };
313 for (const line of body.split("\n")) {
314 if (fence !== undefined) {
315 const closer = line.trim();
316 if (closer.length >= fence.length && closer.replaceAll(fence.charAt(0), "") === "") {
317 fence = undefined;
318 }
319 code(line);
320 continue;
321 }
322 const opener = /^ {0,3}(`{3,}|~{3,})([\s\S]*)$/.exec(line);
323 if (opener?.[1] !== undefined && !(opener[1].startsWith("`") && opener[2]?.includes("`"))) {
324 fence = opener[1];
325 code(line);
326 } else if (!afterText && /^(?: {4}| {0,3}\t)\s*\S/.test(line)) {
327 // Indented code needs a blank line before it; after text the indent is a continuation.
328 code(line);
329 } else {
330 prose.push(line);
331 afterText = line.trim() !== "";
332 }
333 }
334 if (prose.length > 0) parts.push(withoutTags(prose.join("\n")));
335 return parts.join("\n");
336}
337
338function snippet(body: string): string {
339 const text = withoutMarkup(body.replaceAll(/<!--[\s\S]*?-->/g, " "))
340 .replaceAll(/\s+/g, " ")
341 .trim();
342 if (text.length <= SNIPPET_LENGTH) return text;
343 // Half an emoji serializes to a lone surrogate escape, which provider JSON parsers reject.
344 const last = text.charCodeAt(SNIPPET_LENGTH - 4);
345 const end = last >= 0xd800 && last <= 0xdbff ? SNIPPET_LENGTH - 4 : SNIPPET_LENGTH - 3;
346 return `${text.slice(0, end)}...`;
347}
348
349function listed<T>(items: ReadonlyArray<T>, line: (item: T) => string): Array<string> {
350 const lines = items.slice(0, LISTED_ITEMS).map(line);
351 if (items.length > LISTED_ITEMS) lines.push(` - and ${items.length - LISTED_ITEMS} more`);
352 return lines;
353}
354
355function changeLines(
356 change: PullRequestWatchChange,
357 context: { readonly baseBranch: string; readonly commit: string },
358): Array<string> {
359 switch (change.kind) {
360 case "checks-failed":
361 return [
362 `- Checks failed${context.commit}:`,
363 ...listed(
364 change.failed,
365 (check) =>
366 ` - ${check.name}${check.status === "failure" ? "" : ` (${check.status})`}${check.url ? ` ${check.url}` : ""}`,
367 ),
368 ];
369 case "checks-awaiting-approval":
370 return [
371 `- Checks are waiting for approval or action from a maintainer${context.commit}:`,
372 ...listed(change.checks, (check) => ` - ${check.name}${check.url ? ` ${check.url}` : ""}`),
373 ];
374 case "checks-passed":
375 return [
376 `- All ${change.count} ${change.required ? "required " : ""}${change.count === 1 ? "check" : "checks"} passed${context.commit}.`,
377 ];
378 case "remarks":
379 return [
380 `- ${change.remarks.length} new ${change.remarks.length === 1 ? "comment" : "comments"}:`,
381 ...listed(change.remarks, (remark) => {
382 const where = remark.path === null ? "" : ` on ${remark.path}`;
383 const body = snippet(remark.body);
384 const said = body.length === 0 ? (remark.reviewState ?? "reviewed") : `"${body}"`;
385 return ` - ${remark.author?.login ?? "someone"}${where}: ${said}${remark.url ? ` ${remark.url}` : ""}`;
386 }),
387 ];
388 case "no-checks":
389 return [
390 `- No checks have reported${context.commit} after ${change.minutes} minutes. None may be configured to run on this change.`,
391 ];
392 case "needs-rebase":
393 return [`- The branch requires a rebase onto ${context.baseBranch}.`];
394 case "conflicting":
395 return [`- The branch now conflicts with ${context.baseBranch}.`];
396 case "merge-queue-removed":
397 return [
398 `- It was removed from the merge queue without merging${change.reason === null ? "" : `: ${change.reason}`}.`,
399 ];
400 }
401}
402
403const SUMMARY: Record<PullRequestWatchChange["kind"], string> = {
404 "checks-failed": "checks failed",
405 "checks-passed": "checks passed",
406 "checks-awaiting-approval": "checks await approval",
407 remarks: "new comments",
408 "no-checks": "no checks reported",
409 conflicting: "merge conflict",
410 "needs-rebase": "rebase required",
411 "merge-queue-removed": "removed from merge queue",
412};
413
414const WATCHING_CLOSING =
415 "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.";
416const WATCHING_CLOSING_PLURAL =
417 "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.";
418
419export interface PullRequestWatchWake {
420 readonly text: string;
421 readonly notification: OrchestrationV2Notification;
422}
423
424/** One wake for news on several pull requests, with the closing instructions said once. */
425export function combinePullRequestWatchWakes(
426 wakes: readonly [PullRequestWatchWake, ...ReadonlyArray<PullRequestWatchWake>],
427): PullRequestWatchWake {
428 if (wakes.length === 1) return wakes[0];
429 const closing = `\n\n${WATCHING_CLOSING}`;
430 const watching = wakes.some((wake) => wake.text.endsWith(closing));
431 const outcomes = wakes.map((wake) => wake.notification.outcome);
432 return {
433 text: [
434 ...wakes.map((wake) =>
435 wake.text.endsWith(closing) ? wake.text.slice(0, -closing.length) : wake.text,
436 ),
437 ...(watching ? [WATCHING_CLOSING_PLURAL] : []),
438 ].join("\n\n"),
439 notification: {
440 source: { kind: "monitor" },
441 outcome: outcomes.includes("failed")
442 ? "failed"
443 : outcomes.every((outcome) => outcome === "completed")
444 ? "completed"
445 : "updated",
446 summary: wakes.map((wake) => wake.notification.summary).join("; "),
447 },
448 };
449}
450
451export function pullRequestWatchEndMessage(input: {
452 readonly number: number;
453 readonly url: string;
454 readonly detail: Pick<PullRequestDetail, "state" | "baseBranch" | "mergeCommitSha" | "mergedBy">;
455}): { readonly text: string; readonly notification: OrchestrationV2Notification } {
456 const { detail } = input;
457 const merged = detail.state === "merged";
458 const how = merged
459 ? [
460 `was merged into ${detail.baseBranch}`,
461 detail.mergedBy ? ` by ${detail.mergedBy.login}` : "",
462 detail.mergeCommitSha ? ` as ${detail.mergeCommitSha.slice(0, 7)}` : "",
463 ].join("")
464 : "was closed without merging";
465 return {
466 text: [
467 `Pull request #${input.number} (${input.url}) ${how}, so T3 Code stopped watching it.`,
468 ...(merged ? [] : ["If it is reopened, call watch_pull_request to watch it again."]),
469 ].join(" "),
470 notification: {
471 source: { kind: "monitor" },
472 outcome: merged ? "completed" : "updated",
473 summary: `#${input.number}: ${merged ? "merged" : "closed"}, stopped watching`,
474 },
475 };
476}
477
478export function pullRequestWatchMessage(input: {
479 readonly number: number;
480 readonly url: string;
481 readonly baseBranch: string;
482 readonly headSha: string | null;
483 readonly report: PullRequestWatchReport;
484}): { readonly text: string; readonly notification: OrchestrationV2Notification } {
485 const { changes, exhausted } = input.report;
486 const context = {
487 baseBranch: input.baseBranch,
488 commit: input.headSha === null ? "" : ` on ${input.headSha.slice(0, 7)}`,
489 };
490 const text = [
491 `Update on pull request #${input.number} (${input.url}), which T3 Code is watching for you:`,
492 ...changes.flatMap((change) => changeLines(change, context)),
493 "",
494 exhausted
495 ? `T3 Code stopped watching after ${PULL_REQUEST_WATCH_WAKE_LIMIT} comment-only updates in a row. Call watch_pull_request to watch it again.`
496 : WATCHING_CLOSING,
497 ].join("\n");
498 const failed = changes.some(
499 (change) =>
500 change.kind === "checks-failed" ||
501 change.kind === "conflicting" ||
502 change.kind === "needs-rebase" ||
503 change.kind === "merge-queue-removed",
504 );
505 const summary = changes.map((change) => SUMMARY[change.kind]);
506 if (exhausted) summary.push("stopped watching");
507 return {
508 text,
509 notification: {
510 source: { kind: "monitor" },
511 outcome: failed
512 ? "failed"
513 : changes.every((change) => change.kind === "checks-passed")
514 ? "completed"
515 : "updated",
516 summary: `#${input.number}: ${summary.join(", ")}`,
517 },
518 };
519}