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 /** 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;
30}
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 if (detail.checks.length > 0) {
57 const failed = detail.checks.filter(isFailedCheck);
58 const newlyFailed = failed.filter((check) => !failedChecks.includes(check.name));
59 if (newlyFailed.length > 0) changes.push({ kind: "checks-failed", failed: newlyFailed });
60 // A check that runs again leaves the list, so a rerun that fails again is reported.
61 failedChecks = failed.map((check) => check.name);
62
63 const required = detail.checks.filter((check) => check.required === true);
64 const gate = required.length > 0 ? required : detail.checks;
65 const passedNow = gate.every((check) => check.status !== "pending" && !isFailedCheck(check));
66 if (passedNow && !passed) {
67 changes.push({ kind: "checks-passed", count: gate.length, required: required.length > 0 });
68 }
69 passed = passedNow;
70 }
71
72 const own = (detail.viewer ?? detail.author?.login)?.toLowerCase();
73 const through = Date.parse(watch.remarksThrough);
74 // GitHub times are per second, so remarks at the boundary time are told apart by ID.
75 const fresh = (remarks ?? []).filter((remark) => {
76 const at = Date.parse(remark.createdAt);
77 return (
78 (at > through || (at === through && !watch.remarkIds.includes(remark.id))) &&
79 remark.author?.login.toLowerCase() !== own
80 );
81 });
82 if (fresh.length > 0) changes.push({ kind: "remarks", remarks: fresh });
83 const latest = Math.max(through, ...fresh.map((remark) => Date.parse(remark.createdAt)));
84 const atLatest = fresh.filter((remark) => Date.parse(remark.createdAt) === latest);
85 const remarksThrough = latest === through ? watch.remarksThrough : atLatest[0]!.createdAt;
86 const remarkIds = [
87 ...(latest === through ? watch.remarkIds : []),
88 ...atLatest.map((remark) => remark.id),
89 ];
90
91 if (detail.mergeability === "conflicting" && !watch.conflicting) {
92 changes.push({ kind: "conflicting" });
93 }
94 // "unknown" is GitHub still computing after a push; only a clean answer clears a conflict.
95 const conflicting =
96 detail.mergeability === "unknown" ? watch.conflicting : detail.mergeability === "conflicting";
97
98 const commentsOnly = changes.length > 0 && changes.every((change) => change.kind === "remarks");
99 const progress = headMoved || (changes.length > 0 && !commentsOnly);
100 const wakes = (progress ? 0 : watch.wakes) + (commentsOnly ? 1 : 0);
101 return {
102 changes,
103 next: {
104 startedAt: watch.startedAt,
105 headSha,
106 failedChecks,
107 passed,
108 remarksThrough,
109 remarkIds,
110 conflicting,
111 wakes,
112 },
113 exhausted: commentsOnly && wakes >= PULL_REQUEST_WATCH_WAKE_LIMIT,
114 };
115}
116
117function snippet(body: string): string {
118 const text = body
119 .replaceAll(/<!--[\s\S]*?-->/g, " ")
120 .replaceAll(/\s+/g, " ")
121 .trim();
122 return text.length <= SNIPPET_LENGTH ? text : `${text.slice(0, SNIPPET_LENGTH - 3)}...`;
123}
124
125function listed<T>(items: ReadonlyArray<T>, line: (item: T) => string): Array<string> {
126 const lines = items.slice(0, LISTED_ITEMS).map(line);
127 if (items.length > LISTED_ITEMS) lines.push(` - and ${items.length - LISTED_ITEMS} more`);
128 return lines;
129}
130
131function changeLines(
132 change: PullRequestWatchChange,
133 context: { readonly baseBranch: string; readonly commit: string },
134): Array<string> {
135 switch (change.kind) {
136 case "checks-failed":
137 return [
138 `- Checks failed${context.commit}:`,
139 ...listed(
140 change.failed,
141 (check) =>
142 ` - ${check.name}${check.status === "failure" ? "" : ` (${check.status})`}${check.url ? ` ${check.url}` : ""}`,
143 ),
144 ];
145 case "checks-passed":
146 return [
147 `- All ${change.count} ${change.required ? "required " : ""}${change.count === 1 ? "check" : "checks"} passed${context.commit}.`,
148 ];
149 case "remarks":
150 return [
151 `- ${change.remarks.length} new ${change.remarks.length === 1 ? "comment" : "comments"}:`,
152 ...listed(change.remarks, (remark) => {
153 const where = remark.path === null ? "" : ` on ${remark.path}`;
154 const body = snippet(remark.body);
155 const said = body.length === 0 ? (remark.reviewState ?? "reviewed") : `"${body}"`;
156 return ` - ${remark.author?.login ?? "someone"}${where}: ${said}${remark.url ? ` ${remark.url}` : ""}`;
157 }),
158 ];
159 case "conflicting":
160 return [`- The branch now conflicts with ${context.baseBranch}.`];
161 }
162}
163
164const SUMMARY: Record<PullRequestWatchChange["kind"], string> = {
165 "checks-failed": "checks failed",
166 "checks-passed": "checks passed",
167 remarks: "new comments",
168 conflicting: "merge conflict",
169};
170
171/** The wake the agent reads and the timeline notification the user sees. */
172export function pullRequestWatchMessage(input: {
173 readonly number: number;
174 readonly url: string;
175 readonly baseBranch: string;
176 readonly headSha: string | null;
177 readonly report: PullRequestWatchReport;
178}): { readonly text: string; readonly notification: OrchestrationV2Notification } {
179 const { changes, exhausted } = input.report;
180 const context = {
181 baseBranch: input.baseBranch,
182 commit: input.headSha === null ? "" : ` on ${input.headSha.slice(0, 7)}`,
183 };
184 const text = [
185 `Update on pull request #${input.number} (${input.url}), which T3 Code is watching for you:`,
186 ...changes.flatMap((change) => changeLines(change, context)),
187 "",
188 exhausted
189 ? `T3 Code stopped watching after ${PULL_REQUEST_WATCH_WAKE_LIMIT} comment-only updates in a row. Call watch_pull_request to watch it again.`
190 : "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.",
191 ].join("\n");
192 const failed = changes.some(
193 (change) => change.kind === "checks-failed" || change.kind === "conflicting",
194 );
195 const summary = changes.map((change) => SUMMARY[change.kind]);
196 if (exhausted) summary.push("stopped watching");
197 return {
198 text,
199 notification: {
200 source: { kind: "monitor" },
201 outcome: failed
202 ? "failed"
203 : changes.every((change) => change.kind === "checks-passed")
204 ? "completed"
205 : "updated",
206 summary: `#${input.number}: ${summary.join(", ")}`,
207 },
208 };
209}