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

pullRequestWatch.ts

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