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

pullRequestWatch.ts

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