Open History to see the last commit
1import type {
2 OrchestrationV2Notification,
3 PullRequestCheck,
4 PullRequestComment,
5 PullRequestDetail,
6 ThreadPullRequestWatch,
7} from "@t3tools/contracts";
8
9/**
10 * Wakes in a row that bring only comments. Check, conflict, or push news resets the count, so
11 * this only stops a chatty bot looping an agent that is replying to it.
12 */
13export const PULL_REQUEST_WATCH_WAKE_LIMIT = 10;
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: "remarks"; readonly remarks: ReadonlyArray<PullRequestComment> }
21 | { readonly kind: "conflicting" };
22
23export interface PullRequestWatchReport {
24 readonly changes: ReadonlyArray<PullRequestWatchChange>;
25 readonly next: ThreadPullRequestWatch;
26 readonly exhausted: boolean;
27}
28
29// "action-required" is a finished check that needs someone, so the agent hears about it.
30const isFailedCheck = (check: PullRequestCheck) =>
31 check.status === "failure" || check.status === "cancelled" || check.status === "action-required";
32
33export function evaluatePullRequestWatch(
34 watch: ThreadPullRequestWatch,
35 detail: Pick<PullRequestDetail, "headSha" | "checks" | "mergeability" | "viewer" | "author">,
36 remarks: ReadonlyArray<PullRequestComment> | null,
37): PullRequestWatchReport {
38 const changes: Array<PullRequestWatchChange> = [];
39 const headSha = detail.headSha ?? null;
40 const headMoved = headSha !== watch.headSha;
41
42 // An empty list keeps the last state: a host can answer with one when its check read fails.
43 let failedChecks = headMoved ? [] : watch.failedChecks;
44 let passed = headMoved ? false : watch.passed;
45 let passedChecks = headMoved ? [] : watch.passedChecks;
46 if (detail.checks.length > 0) {
47 const failed = detail.checks.filter(isFailedCheck);
48 const newlyFailed = failed.filter((check) => !failedChecks.includes(check.name));
49 if (newlyFailed.length > 0) changes.push({ kind: "checks-failed", failed: newlyFailed });
50 failedChecks = failed.map((check) => check.name);
51
52 const required = detail.checks.filter((check) => check.required === true);
53 const gate = required.length > 0 ? required : detail.checks;
54 const passedNow = gate.every((check) => check.status !== "pending" && !isFailedCheck(check));
55 const gateNames = gate.map((check) => check.name);
56 const told = passed && passedChecks.length === 0 ? gateNames : passedChecks;
57 // A required job created and finished between two passes is never seen pending. Without
58 // required checks, any check counts, and advisory bots keep adding passed ones: no wake.
59 const gateGrew = required.length > 0 && gateNames.some((name) => !told.includes(name));
60 if (passedNow && (!passed || gateGrew)) {
61 changes.push({ kind: "checks-passed", count: gate.length, required: required.length > 0 });
62 }
63 passed = passedNow;
64 passedChecks = passedNow ? gateNames : [];
65 }
66
67 const own = (detail.viewer ?? detail.author?.login)?.toLowerCase();
68 const through = Date.parse(watch.remarksThrough);
69 const activeAt = (remark: PullRequestComment) => remark.editedAt ?? remark.createdAt;
70 // GitHub times are per second, so remarks at the boundary time are told apart by ID.
71 const fresh = (remarks ?? []).filter((remark) => {
72 const at = Date.parse(activeAt(remark));
73 return (
74 (at > through || (at === through && !watch.remarkIds.includes(remark.id))) &&
75 remark.author?.login.toLowerCase() !== own
76 );
77 });
78 if (fresh.length > 0) changes.push({ kind: "remarks", remarks: fresh });
79 const latest = Math.max(through, ...fresh.map((remark) => Date.parse(activeAt(remark))));
80 const atLatest = fresh.filter((remark) => Date.parse(activeAt(remark)) === latest);
81 const remarksThrough = latest === through ? watch.remarksThrough : activeAt(atLatest[0]!);
82 const remarkIds = [
83 ...(latest === through ? watch.remarkIds : []),
84 ...atLatest.map((remark) => remark.id),
85 ];
86
87 if (detail.mergeability === "conflicting" && !watch.conflicting) {
88 changes.push({ kind: "conflicting" });
89 }
90 // "unknown" is GitHub still computing after a push; only a clean answer clears a conflict.
91 const conflicting =
92 detail.mergeability === "unknown" ? watch.conflicting : detail.mergeability === "conflicting";
93
94 const commentsOnly = changes.length > 0 && changes.every((change) => change.kind === "remarks");
95 const progress = headMoved || (changes.length > 0 && !commentsOnly);
96 const wakes = (progress ? 0 : watch.wakes) + (commentsOnly ? 1 : 0);
97 return {
98 changes,
99 next: {
100 startedAt: watch.startedAt,
101 headSha,
102 failedChecks,
103 passed,
104 passedChecks,
105 remarksThrough,
106 remarkIds,
107 conflicting,
108 wakes,
109 },
110 exhausted: commentsOnly && wakes >= PULL_REQUEST_WATCH_WAKE_LIMIT,
111 };
112}
113
114function snippet(body: string): string {
115 const text = body
116 .replaceAll(/<!--[\s\S]*?-->/g, " ")
117 .replaceAll(/\s+/g, " ")
118 .trim();
119 return text.length <= SNIPPET_LENGTH ? text : `${text.slice(0, SNIPPET_LENGTH - 3)}...`;
120}
121
122function listed<T>(items: ReadonlyArray<T>, line: (item: T) => string): Array<string> {
123 const lines = items.slice(0, LISTED_ITEMS).map(line);
124 if (items.length > LISTED_ITEMS) lines.push(` - and ${items.length - LISTED_ITEMS} more`);
125 return lines;
126}
127
128function changeLines(
129 change: PullRequestWatchChange,
130 context: { readonly baseBranch: string; readonly commit: string },
131): Array<string> {
132 switch (change.kind) {
133 case "checks-failed":
134 return [
135 `- Checks failed${context.commit}:`,
136 ...listed(
137 change.failed,
138 (check) =>
139 ` - ${check.name}${check.status === "failure" ? "" : ` (${check.status})`}${check.url ? ` ${check.url}` : ""}`,
140 ),
141 ];
142 case "checks-passed":
143 return [
144 `- All ${change.count} ${change.required ? "required " : ""}${change.count === 1 ? "check" : "checks"} passed${context.commit}.`,
145 ];
146 case "remarks":
147 return [
148 `- ${change.remarks.length} new ${change.remarks.length === 1 ? "comment" : "comments"}:`,
149 ...listed(change.remarks, (remark) => {
150 const where = remark.path === null ? "" : ` on ${remark.path}`;
151 const body = snippet(remark.body);
152 const said = body.length === 0 ? (remark.reviewState ?? "reviewed") : `"${body}"`;
153 return ` - ${remark.author?.login ?? "someone"}${where}: ${said}${remark.url ? ` ${remark.url}` : ""}`;
154 }),
155 ];
156 case "conflicting":
157 return [`- The branch now conflicts with ${context.baseBranch}.`];
158 }
159}
160
161const SUMMARY: Record<PullRequestWatchChange["kind"], string> = {
162 "checks-failed": "checks failed",
163 "checks-passed": "checks passed",
164 remarks: "new comments",
165 conflicting: "merge conflict",
166};
167
168export function pullRequestWatchMessage(input: {
169 readonly number: number;
170 readonly url: string;
171 readonly baseBranch: string;
172 readonly headSha: string | null;
173 readonly report: PullRequestWatchReport;
174}): { readonly text: string; readonly notification: OrchestrationV2Notification } {
175 const { changes, exhausted } = input.report;
176 const context = {
177 baseBranch: input.baseBranch,
178 commit: input.headSha === null ? "" : ` on ${input.headSha.slice(0, 7)}`,
179 };
180 const text = [
181 `Update on pull request #${input.number} (${input.url}), which T3 Code is watching for you:`,
182 ...changes.flatMap((change) => changeLines(change, context)),
183 "",
184 exhausted
185 ? `T3 Code stopped watching after ${PULL_REQUEST_WATCH_WAKE_LIMIT} comment-only updates in a row. Call watch_pull_request to watch it again.`
186 : "Look into each item and act on it as your task requires. T3 Code keeps watching and wakes you on the next change, so end your turn when you are done. When you hand the work back to the user, call unwatch_pull_request first so the thread returns to their inbox.",
187 ].join("\n");
188 const failed = changes.some(
189 (change) => change.kind === "checks-failed" || change.kind === "conflicting",
190 );
191 const summary = changes.map((change) => SUMMARY[change.kind]);
192 if (exhausted) summary.push("stopped watching");
193 return {
194 text,
195 notification: {
196 source: { kind: "monitor" },
197 outcome: failed
198 ? "failed"
199 : changes.every((change) => change.kind === "checks-passed")
200 ? "completed"
201 : "updated",
202 summary: `#${input.number}: ${summary.join(", ")}`,
203 },
204 };
205}