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

pullRequestWatch.ts

219 lines9.3 KB

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 /** What the agent has not been told yet. Empty means no wake. */
25 readonly changes: ReadonlyArray<PullRequestWatchChange>;
26 /** The watch to record, whether or not anything is reported. */
27 readonly next: ThreadPullRequestWatch;
28 /** This report spends the last wake before the limit, so watching stops after it. */
29 readonly exhausted: boolean;
31​
32// "action-required" is a finished check that needs someone, so the agent hears about it.
33const isFailedCheck = (check: PullRequestCheck) =>
34 check.status === "failure" || check.status === "cancelled" || check.status === "action-required";
35​
36/**
37 * Compares a watched pull request with what its agent was last told. Each check is reported as
38 * soon as it fails, so a check that never finishes (an advisory review bot) cannot hold the
39 * news back. "Passed" is reported once the checks the base branch requires all passed, or all
40 * checks where the host marks none required. Remarks count when someone other than the agent's
41 * own account wrote them, so its own replies never wake it. `remarks` is null when the
42 * conversation could not be read; remarks then wait for a later pass.
43 */
44export function evaluatePullRequestWatch(
45 watch: ThreadPullRequestWatch,
46 detail: Pick<PullRequestDetail, "headSha" | "checks" | "mergeability" | "viewer" | "author">,
47 remarks: ReadonlyArray<PullRequestComment> | null,
48): PullRequestWatchReport {
49 const changes: Array<PullRequestWatchChange> = [];
50 const headSha = detail.headSha ?? null;
51 const headMoved = headSha !== watch.headSha;
52​
53 // An empty list keeps the last state: a host can answer with one when its check read fails.
54 let failedChecks = headMoved ? [] : watch.failedChecks;
55 let passed = headMoved ? false : watch.passed;
56 let passedChecks = headMoved ? [] : watch.passedChecks;
57 if (detail.checks.length > 0) {
58 const failed = detail.checks.filter(isFailedCheck);
59 const newlyFailed = failed.filter((check) => !failedChecks.includes(check.name));
60 if (newlyFailed.length > 0) changes.push({ kind: "checks-failed", failed: newlyFailed });
61 // A check that runs again leaves the list, so a rerun that fails again is reported.
62 failedChecks = failed.map((check) => check.name);
63​
64 const required = detail.checks.filter((check) => check.required === true);
65 const gate = required.length > 0 ? required : detail.checks;
66 const passedNow = gate.every((check) => check.status !== "pending" && !isFailedCheck(check));
67 const gateNames = gate.map((check) => check.name);
68 // A watch saved before passedChecks existed takes the current names, so it does not wake.
69 const told = passed && passedChecks.length === 0 ? gateNames : passedChecks;
70 // A required job created and finished between two passes is never seen pending.
71 const gateGrew = gateNames.some((name) => !told.includes(name));
72 if (passedNow && (!passed || gateGrew)) {
73 changes.push({ kind: "checks-passed", count: gate.length, required: required.length > 0 });
74 }
75 passed = passedNow;
76 passedChecks = passedNow ? gateNames : [];
77 }
78​
79 const own = (detail.viewer ?? detail.author?.login)?.toLowerCase();
80 const through = Date.parse(watch.remarksThrough);
81 // An edit counts as new activity, so bots that rewrite one summary comment still wake the agent.
82 const activeAt = (remark: PullRequestComment) => remark.editedAt ?? remark.createdAt;
83 // GitHub times are per second, so remarks at the boundary time are told apart by ID.
84 const fresh = (remarks ?? []).filter((remark) => {
85 const at = Date.parse(activeAt(remark));
86 return (
87 (at > through || (at === through && !watch.remarkIds.includes(remark.id))) &&
88 remark.author?.login.toLowerCase() !== own
89 );
90 });
91 if (fresh.length > 0) changes.push({ kind: "remarks", remarks: fresh });
92 const latest = Math.max(through, ...fresh.map((remark) => Date.parse(activeAt(remark))));
93 const atLatest = fresh.filter((remark) => Date.parse(activeAt(remark)) === latest);
94 const remarksThrough = latest === through ? watch.remarksThrough : activeAt(atLatest[0]!);
95 const remarkIds = [
96 ...(latest === through ? watch.remarkIds : []),
97 ...atLatest.map((remark) => remark.id),
98 ];
99​
100 if (detail.mergeability === "conflicting" && !watch.conflicting) {
101 changes.push({ kind: "conflicting" });
102 }
103 // "unknown" is GitHub still computing after a push; only a clean answer clears a conflict.
104 const conflicting =
105 detail.mergeability === "unknown" ? watch.conflicting : detail.mergeability === "conflicting";
106​
107 const commentsOnly = changes.length > 0 && changes.every((change) => change.kind === "remarks");
108 const progress = headMoved || (changes.length > 0 && !commentsOnly);
109 const wakes = (progress ? 0 : watch.wakes) + (commentsOnly ? 1 : 0);
110 return {
111 changes,
112 next: {
113 startedAt: watch.startedAt,
114 headSha,
115 failedChecks,
116 passed,
117 passedChecks,
118 remarksThrough,
119 remarkIds,
120 conflicting,
121 wakes,
122 },
123 exhausted: commentsOnly && wakes >= PULL_REQUEST_WATCH_WAKE_LIMIT,
124 };
126​
127function snippet(body: string): string {
128 const text = body
129 .replaceAll(/<!--[\s\S]*?-->/g, " ")
130 .replaceAll(/\s+/g, " ")
131 .trim();
132 return text.length <= SNIPPET_LENGTH ? text : `${text.slice(0, SNIPPET_LENGTH - 3)}...`;
134​
135function listed<T>(items: ReadonlyArray<T>, line: (item: T) => string): Array<string> {
136 const lines = items.slice(0, LISTED_ITEMS).map(line);
137 if (items.length > LISTED_ITEMS) lines.push(` - and ${items.length - LISTED_ITEMS} more`);
138 return lines;
140​
141function changeLines(
142 change: PullRequestWatchChange,
143 context: { readonly baseBranch: string; readonly commit: string },
144): Array<string> {
145 switch (change.kind) {
146 case "checks-failed":
147 return [
148 `- Checks failed${context.commit}:`,
149 ...listed(
150 change.failed,
151 (check) =>
152 ` - ${check.name}${check.status === "failure" ? "" : ` (${check.status})`}${check.url ? ` ${check.url}` : ""}`,
153 ),
154 ];
155 case "checks-passed":
156 return [
157 `- All ${change.count} ${change.required ? "required " : ""}${change.count === 1 ? "check" : "checks"} passed${context.commit}.`,
158 ];
159 case "remarks":
160 return [
161 `- ${change.remarks.length} new ${change.remarks.length === 1 ? "comment" : "comments"}:`,
162 ...listed(change.remarks, (remark) => {
163 const where = remark.path === null ? "" : ` on ${remark.path}`;
164 const body = snippet(remark.body);
165 const said = body.length === 0 ? (remark.reviewState ?? "reviewed") : `"${body}"`;
166 return ` - ${remark.author?.login ?? "someone"}${where}: ${said}${remark.url ? ` ${remark.url}` : ""}`;
167 }),
168 ];
169 case "conflicting":
170 return [`- The branch now conflicts with ${context.baseBranch}.`];
171 }
173​
174const SUMMARY: Record<PullRequestWatchChange["kind"], string> = {
175 "checks-failed": "checks failed",
176 "checks-passed": "checks passed",
177 remarks: "new comments",
178 conflicting: "merge conflict",
179};
180​
181/** The wake the agent reads and the timeline notification the user sees. */
182export function pullRequestWatchMessage(input: {
183 readonly number: number;
184 readonly url: string;
185 readonly baseBranch: string;
186 readonly headSha: string | null;
187 readonly report: PullRequestWatchReport;
188}): { readonly text: string; readonly notification: OrchestrationV2Notification } {
189 const { changes, exhausted } = input.report;
190 const context = {
191 baseBranch: input.baseBranch,
192 commit: input.headSha === null ? "" : ` on ${input.headSha.slice(0, 7)}`,
193 };
194 const text = [
195 `Update on pull request #${input.number} (${input.url}), which T3 Code is watching for you:`,
196 ...changes.flatMap((change) => changeLines(change, context)),
197 "",
198 exhausted
199 ? `T3 Code stopped watching after ${PULL_REQUEST_WATCH_WAKE_LIMIT} comment-only updates in a row. Call watch_pull_request to watch it again.`
200 : "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. Call unwatch_pull_request when you no longer need updates.",
201 ].join("\n");
202 const failed = changes.some(
203 (change) => change.kind === "checks-failed" || change.kind === "conflicting",
204 );
205 const summary = changes.map((change) => SUMMARY[change.kind]);
206 if (exhausted) summary.push("stopped watching");
207 return {
208 text,
209 notification: {
210 source: { kind: "monitor" },
211 outcome: failed
212 ? "failed"
213 : changes.every((change) => change.kind === "checks-passed")
214 ? "completed"
215 : "updated",
216 summary: `#${input.number}: ${summary.join(", ")}`,
217 },
218 };