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: "remarks"; readonly remarks: ReadonlyArray<PullRequestComment> }
21 | { readonly kind: "no-checks"; readonly minutes: number }
22 | { readonly kind: "conflicting" };
23
24export interface PullRequestWatchReport {
25 readonly changes: ReadonlyArray<PullRequestWatchChange>;
26 readonly next: ThreadPullRequestWatch;
27 readonly exhausted: boolean;
28}
29
30// action-required is a finished check needing human input.
31const isFailedCheck = (check: PullRequestCheck) =>
32 check.status === "failure" || check.status === "cancelled" || check.status === "action-required";
33
34export function evaluatePullRequestWatch(
35 watch: ThreadPullRequestWatch,
36 detail: Pick<
37 PullRequestDetail,
38 "capabilities" | "headSha" | "checks" | "mergeability" | "viewer" | "author"
39 >,
40 remarks: ReadonlyArray<PullRequestComment> | null,
41 now: number,
42): PullRequestWatchReport {
43 const changes: Array<PullRequestWatchChange> = [];
44 // Azure DevOps omits the head when its iteration read fails; that is not a push.
45 const headSha = detail.headSha ?? watch.headSha;
46 const headMoved = headSha !== watch.headSha;
47
48 // Hosts can return no checks on read failure; preserve prior state.
49 let failedChecks = headMoved ? [] : watch.failedChecks;
50 let passed = headMoved ? false : watch.passed;
51 let passedChecks = headMoved ? [] : watch.passedChecks;
52 let owedChecks = headMoved ? [] : (watch.owedChecks ?? []);
53 if (detail.checks.length > 0) {
54 const failed = detail.checks.filter(isFailedCheck);
55 const newlyFailed = failed.filter((check) => !failedChecks.includes(check.name));
56 if (newlyFailed.length > 0) changes.push({ kind: "checks-failed", failed: newlyFailed });
57 failedChecks = failed.map((check) => check.name);
58
59 const required = detail.checks.filter((check) => check.required === true);
60 const gate = required.length > 0 ? required : detail.checks;
61 const passedNow = gate.every((check) => check.status !== "pending" && !isFailedCheck(check));
62 const gateNames = gate.map((check) => check.name);
63 const told = passed && passedChecks.length === 0 ? gateNames : passedChecks;
64 // Required checks can finish between sweeps; detect new names. With no required checks, ignore advisory gate growth.
65 const gateGrew = required.length > 0 && gateNames.some((name) => !told.includes(name));
66 // Other checks still pending when required ones passed are owed one wake when all settle.
67 // Only those are owed, so later advisory churn never wakes. One turned required is gate news.
68 const owed =
69 passedNow && passed
70 ? detail.checks
71 .filter((check) => check.required !== true && owedChecks.includes(check.name))
72 .map((check) => check.name)
73 : [];
74 const settled =
75 failed.length === 0 && detail.checks.every((check) => check.status !== "pending");
76 owedChecks = owed;
77 if (passedNow && (!passed || gateGrew)) {
78 changes.push({ kind: "checks-passed", count: gate.length, required: required.length > 0 });
79 owedChecks =
80 required.length > 0
81 ? detail.checks
82 .filter((check) => check.required !== true && check.status === "pending")
83 .map((check) => check.name)
84 : [];
85 } else if (settled && owed.length > 0) {
86 changes.push({ kind: "checks-passed", count: detail.checks.length, required: false });
87 owedChecks = [];
88 }
89 passed = passedNow;
90 passedChecks = passedNow ? gateNames : [];
91 }
92
93 // Only a head never read with checks waits for them: an empty read after checks were seen is
94 // the failed read above. A watch saved before this field may have seen pending checks on its
95 // head, so its clock starts only at the next push. Where a host's empty list can mean the
96 // repository runs no checks at all, nothing waits.
97 let checksAwaitedSince = watch.checksAwaitedSince;
98 if (detail.capabilities.checksAlwaysReport === true) {
99 const awaitedBefore = headMoved
100 ? DateTime.formatIso(DateTime.makeUnsafe(now))
101 : (watch.checksAwaitedSince ?? null);
102 checksAwaitedSince = detail.checks.length > 0 ? null : awaitedBefore;
103 const awaitedMs = checksAwaitedSince === null ? 0 : now - Date.parse(checksAwaitedSince);
104 if (awaitedMs >= PULL_REQUEST_WATCH_NO_CHECKS_MS) {
105 changes.push({ kind: "no-checks", minutes: Math.round(awaitedMs / 60_000) });
106 checksAwaitedSince = null;
107 }
108 }
109
110 const own = (detail.viewer ?? detail.author?.login)?.toLowerCase();
111 const through = Date.parse(watch.remarksThrough);
112 const activeAt = (remark: PullRequestComment) => remark.editedAt ?? remark.createdAt;
113 // Hosts can stamp remarks to the second, so remarks at the boundary time are told apart by ID.
114 const fresh = (remarks ?? []).filter((remark) => {
115 const at = Date.parse(activeAt(remark));
116 return (
117 (at > through || (at === through && !watch.remarkIds.includes(remark.id))) &&
118 remark.author?.login.toLowerCase() !== own
119 );
120 });
121 if (fresh.length > 0) changes.push({ kind: "remarks", remarks: fresh });
122 const latest = Math.max(through, ...fresh.map((remark) => Date.parse(activeAt(remark))));
123 const atLatest = fresh.filter((remark) => Date.parse(activeAt(remark)) === latest);
124 const remarksThrough = latest === through ? watch.remarksThrough : activeAt(atLatest[0]!);
125 const remarkIds = [
126 ...(latest === through ? watch.remarkIds : []),
127 ...atLatest.map((remark) => remark.id),
128 ];
129
130 // Like a failed check, a conflict a push did not resolve is news for the new head.
131 const toldConflict = !headMoved && watch.conflicting;
132 if (detail.mergeability === "conflicting" && !toldConflict) {
133 changes.push({ kind: "conflicting" });
134 }
135 // "unknown" is a host still computing after a push; only a clean answer clears a conflict.
136 const conflicting =
137 detail.mergeability === "unknown" ? toldConflict : detail.mergeability === "conflicting";
138
139 const commentsOnly = changes.length > 0 && changes.every((change) => change.kind === "remarks");
140 const progress = headMoved || (changes.length > 0 && !commentsOnly);
141 const wakes = (progress ? 0 : watch.wakes) + (commentsOnly ? 1 : 0);
142 return {
143 changes,
144 next: {
145 startedAt: watch.startedAt,
146 headSha,
147 failedChecks,
148 passed,
149 passedChecks,
150 owedChecks,
151 remarksThrough,
152 remarkIds,
153 conflicting,
154 wakes,
155 checksAwaitedSince,
156 },
157 exhausted: commentsOnly && wakes >= PULL_REQUEST_WATCH_WAKE_LIMIT,
158 };
159}
160
161function snippet(body: string): string {
162 const text = body
163 .replaceAll(/<!--[\s\S]*?-->/g, " ")
164 .replaceAll(/\s+/g, " ")
165 .trim();
166 if (text.length <= SNIPPET_LENGTH) return text;
167 // Half an emoji serializes to a lone surrogate escape, which provider JSON parsers reject.
168 const last = text.charCodeAt(SNIPPET_LENGTH - 4);
169 const end = last >= 0xd800 && last <= 0xdbff ? SNIPPET_LENGTH - 4 : SNIPPET_LENGTH - 3;
170 return `${text.slice(0, end)}...`;
171}
172
173function listed<T>(items: ReadonlyArray<T>, line: (item: T) => string): Array<string> {
174 const lines = items.slice(0, LISTED_ITEMS).map(line);
175 if (items.length > LISTED_ITEMS) lines.push(` - and ${items.length - LISTED_ITEMS} more`);
176 return lines;
177}
178
179function changeLines(
180 change: PullRequestWatchChange,
181 context: { readonly baseBranch: string; readonly commit: string },
182): Array<string> {
183 switch (change.kind) {
184 case "checks-failed":
185 return [
186 `- Checks failed${context.commit}:`,
187 ...listed(
188 change.failed,
189 (check) =>
190 ` - ${check.name}${check.status === "failure" ? "" : ` (${check.status})`}${check.url ? ` ${check.url}` : ""}`,
191 ),
192 ];
193 case "checks-passed":
194 return [
195 `- All ${change.count} ${change.required ? "required " : ""}${change.count === 1 ? "check" : "checks"} passed${context.commit}.`,
196 ];
197 case "remarks":
198 return [
199 `- ${change.remarks.length} new ${change.remarks.length === 1 ? "comment" : "comments"}:`,
200 ...listed(change.remarks, (remark) => {
201 const where = remark.path === null ? "" : ` on ${remark.path}`;
202 const body = snippet(remark.body);
203 const said = body.length === 0 ? (remark.reviewState ?? "reviewed") : `"${body}"`;
204 return ` - ${remark.author?.login ?? "someone"}${where}: ${said}${remark.url ? ` ${remark.url}` : ""}`;
205 }),
206 ];
207 case "no-checks":
208 return [
209 `- No checks have reported${context.commit} after ${change.minutes} minutes. None may be configured to run on this change.`,
210 ];
211 case "conflicting":
212 return [`- The branch now conflicts with ${context.baseBranch}.`];
213 }
214}
215
216const SUMMARY: Record<PullRequestWatchChange["kind"], string> = {
217 "checks-failed": "checks failed",
218 "checks-passed": "checks passed",
219 remarks: "new comments",
220 "no-checks": "no checks reported",
221 conflicting: "merge conflict",
222};
223
224export function pullRequestWatchMessage(input: {
225 readonly number: number;
226 readonly url: string;
227 readonly baseBranch: string;
228 readonly headSha: string | null;
229 readonly report: PullRequestWatchReport;
230}): { readonly text: string; readonly notification: OrchestrationV2Notification } {
231 const { changes, exhausted } = input.report;
232 const context = {
233 baseBranch: input.baseBranch,
234 commit: input.headSha === null ? "" : ` on ${input.headSha.slice(0, 7)}`,
235 };
236 const text = [
237 `Update on pull request #${input.number} (${input.url}), which T3 Code is watching for you:`,
238 ...changes.flatMap((change) => changeLines(change, context)),
239 "",
240 exhausted
241 ? `T3 Code stopped watching after ${PULL_REQUEST_WATCH_WAKE_LIMIT} comment-only updates in a row. Call watch_pull_request to watch it again.`
242 : "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.",
243 ].join("\n");
244 const failed = changes.some(
245 (change) => change.kind === "checks-failed" || change.kind === "conflicting",
246 );
247 const summary = changes.map((change) => SUMMARY[change.kind]);
248 if (exhausted) summary.push("stopped watching");
249 return {
250 text,
251 notification: {
252 source: { kind: "monitor" },
253 outcome: failed
254 ? "failed"
255 : changes.every((change) => change.kind === "checks-passed")
256 ? "completed"
257 : "updated",
258 summary: `#${input.number}: ${summary.join(", ")}`,
259 },
260 };
261}