Open History to see the last commit
1import {
2 CommandId,
3 MessageId,
4 type OrchestrationV2Notification,
5 type PullRequestActivity,
6 type PullRequestComment,
7 type PullRequestRef,
8 type PullRequestThreadCommentsResult,
9 type ThreadPullRequestLink,
10 type ThreadPullRequestWatch,
11} from "@t3tools/contracts";
12import {
13 normalizeThreadPullRequestKey,
14 threadPullRequestKeyOf,
15 visibleThreadPullRequests,
16} from "@t3tools/shared/threadPullRequests";
17import * as Cause from "effect/Cause";
18import * as Clock from "effect/Clock";
19import * as Context from "effect/Context";
20import * as Crypto from "effect/Crypto";
21import * as Effect from "effect/Effect";
22import * as Exit from "effect/Exit";
23import * as Layer from "effect/Layer";
24import * as Option from "effect/Option";
25import * as Schedule from "effect/Schedule";
26import * as Schema from "effect/Schema";
27import type * as Scope from "effect/Scope";
28
29import {
30 type ProviderChangeRequestWatchFingerprint,
31 PullRequestProviderError,
32} from "@t3tools/source-control-core/server/PullRequestProvider";
33import * as PullRequestService from "../pullRequest/PullRequestService.ts";
34import { forkParked } from "../serverActivation.ts";
35import * as Orchestrator from "./Orchestrator.ts";
36import * as ProjectionStore from "./ProjectionStore.ts";
37import { evaluatePullRequestWatch, pullRequestWatchMessage } from "./pullRequestWatch.ts";
38
39/**
40 * Checks take minutes, so a faster pass mostly spends the host's rate limit,
41 * which every machine on the same account shares.
42 */
43const SWEEP_MINUTES = 2;
44const READ_FAILURE_LIMIT = 8;
45/**
46 * Without a host fingerprint, a pull request with nothing in flight is read again only when its
47 * sync snapshot moves, or after this long, for news the snapshot cannot show, such as a bot
48 * editing its review.
49 */
50const QUIET_REREAD_MS = 10 * 60_000;
51/**
52 * With a host fingerprint, how long until the activity is read again anyway: the fingerprint
53 * does not see edits to comments inside review threads.
54 */
55const FINGERPRINT_REREAD_MS = 30 * 60_000;
56
57const isProviderError = Schema.is(PullRequestProviderError);
58
59const isRateLimited = (cause: Cause.Cause<PullRequestService.PullRequestError>) =>
60 Option.match(Cause.findErrorOption(cause), {
61 onNone: () => false,
62 onSome: (error) =>
63 error._tag === "PullRequestOperationError" &&
64 isProviderError(error.cause) &&
65 error.cause.reason === "rate-limited",
66 });
67
68const logFailure =
69 (message: string, fields: Record<string, unknown>) =>
70 <E>(cause: Cause.Cause<E>): Effect.Effect<void> =>
71 Cause.hasInterruptsOnly(cause)
72 ? Effect.interrupt
73 : Effect.logWarning(message, { ...fields, cause });
74
75interface WatchTarget {
76 readonly thread: ProjectionStore.ProjectionThreadPullRequests;
77 readonly link: ThreadPullRequestLink;
78 readonly watch: ThreadPullRequestWatch;
79}
80
81interface WatchGroup {
82 readonly key: string;
83 readonly targets: ReadonlyArray<WatchTarget>;
84 readonly fingerprint: string;
85}
86
87interface LastRead {
88 readonly at: number;
89 readonly fingerprint: string;
90 readonly inFlight: boolean;
91 readonly remarksComplete: boolean;
92 readonly watches: ReadonlySet<string>;
93 readonly status: string | null;
94 readonly remarks: string | null;
95}
96
97interface ReadPlan {
98 readonly detail: boolean;
99 readonly activity: boolean;
100}
101
102const watchKey = ({ thread, watch }: WatchTarget) => `${thread.id} ${watch.startedAt}`;
103
104type WatchEndReason =
105 | "merged"
106 | "closed"
107 | "unreadable"
108 | "comment-limit"
109 | "settled"
110 | "subagent"
111 | "stopped";
112
113interface WatchLife {
114 readonly threadId: string;
115 readonly pullRequest: string;
116 readonly startedAt: number;
117 readonly headSha: string | null;
118 readonly pushedAt: number;
119 readonly longestQuietMs: number;
120 readonly wakes: number;
121 readonly reads: number;
122}
123
124const lifeKey = ({ thread, link, watch }: WatchTarget) =>
125 `${thread.id} ${threadPullRequestKeyOf(link)} ${watch.startedAt}`;
126
127const minutes = (ms: number) => Math.max(0, Math.round(ms / 60_000));
128
129const snapshotFingerprint = ({ link }: WatchTarget) => {
130 const snapshot = link.snapshot;
131 return snapshot === null
132 ? ""
133 : [
134 snapshot.state,
135 snapshot.updatedAt,
136 snapshot.checksState,
137 snapshot.mergeability,
138 snapshot.reviewDecision,
139 snapshot.isDraft,
140 ].join(" ");
141};
142
143function planRead(
144 group: WatchGroup,
145 last: LastRead | undefined,
146 fingerprint: ProviderChangeRequestWatchFingerprint | null,
147 now: number,
148): ReadPlan {
149 if (last === undefined || group.targets.some((target) => !last.watches.has(watchKey(target)))) {
150 return { detail: true, activity: true };
151 }
152 if (fingerprint === null) {
153 const read =
154 last.inFlight ||
155 !last.remarksComplete ||
156 last.fingerprint !== group.fingerprint ||
157 now - last.at >= QUIET_REREAD_MS;
158 return { detail: read, activity: read };
159 }
160 const activity =
161 last.remarks !== fingerprint.remarks ||
162 !last.remarksComplete ||
163 now - last.at >= FINGERPRINT_REREAD_MS;
164 return { detail: activity || last.status !== fingerprint.status || last.inFlight, activity };
165}
166
167function watchesEqual(left: ThreadPullRequestWatch, right: ThreadPullRequestWatch): boolean {
168 return (
169 left.startedAt === right.startedAt &&
170 left.headSha === right.headSha &&
171 left.failedChecks.join("\n") === right.failedChecks.join("\n") &&
172 left.passed === right.passed &&
173 left.passedChecks.join("\n") === right.passedChecks.join("\n") &&
174 left.remarksThrough === right.remarksThrough &&
175 left.remarkIds.join("\n") === right.remarkIds.join("\n") &&
176 left.conflicting === right.conflicting &&
177 left.wakes === right.wakes
178 );
179}
180
181export class PullRequestWatchReactor extends Context.Service<
182 PullRequestWatchReactor,
183 {
184 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
185 readonly sweep: Effect.Effect<void>;
186 }
187>()("t3/orchestration-v2/PullRequestWatchReactor") {}
188
189/** @public Service construction is part of the canonical Effect module API. */
190export const make = Effect.gen(function* () {
191 const engine = yield* Orchestrator.OrchestratorV2;
192 const projections = yield* ProjectionStore.ProjectionStoreV2;
193 const pullRequests = yield* PullRequestService.PullRequestService;
194 const crypto = yield* Crypto.Crypto;
195 const bootedAt = yield* Clock.currentTimeMillis;
196 const lives = new Map<string, WatchLife>();
197
198 const lifeOf = (target: WatchTarget): WatchLife => {
199 const existing = lives.get(lifeKey(target));
200 if (existing !== undefined) return existing;
201 const startedAt = Date.parse(target.watch.startedAt);
202 const life: WatchLife = {
203 threadId: target.thread.id,
204 pullRequest: threadPullRequestKeyOf(target.link),
205 startedAt,
206 headSha: target.watch.headSha,
207 pushedAt: startedAt,
208 longestQuietMs: 0,
209 wakes: 0,
210 reads: 0,
211 };
212 lives.set(lifeKey(target), life);
213 return life;
214 };
215 const woke = (target: WatchTarget) =>
216 Effect.sync(() => {
217 const life = lifeOf(target);
218 lives.set(lifeKey(target), { ...life, wakes: life.wakes + 1 });
219 });
220
221 const reportEnd = Effect.fn("PullRequestWatchReactor.reportEnd")(function* (
222 key: string,
223 life: WatchLife,
224 reason: WatchEndReason,
225 ) {
226 lives.delete(key);
227 const now = yield* Clock.currentTimeMillis;
228 const quietMs = now - life.pushedAt;
229 yield* Effect.logInfo("pull request watch ended", {
230 threadId: life.threadId,
231 pullRequest: life.pullRequest,
232 reason,
233 minutes: minutes(now - life.startedAt),
234 quietMinutes: minutes(quietMs),
235 longestQuietMinutes: minutes(Math.max(life.longestQuietMs, quietMs)),
236 wakes: life.wakes,
237 reads: life.reads,
238 partial: life.startedAt < bootedAt,
239 });
240 });
241 const ended = (target: WatchTarget, reason: WatchEndReason) =>
242 Effect.suspend(() => reportEnd(lifeKey(target), lifeOf(target), reason));
243
244 const readFailures = new Map<string, number>();
245 const lastReads = new Map<string, LastRead>();
246 const threadTails = new Map<
247 string,
248 Map<string, { readonly count: number; readonly comments: ReadonlyArray<PullRequestComment> }>
249 >();
250
251 const identityOf = (link: ThreadPullRequestLink) => ({
252 host: normalizeThreadPullRequestKey(link).host,
253 repository: link.repository,
254 number: link.number,
255 });
256
257 /**
258 * The orchestrator applies this only while the same watch is on, so a stop or restart
259 * that lands during the host read wins.
260 */
261 const record = Effect.fn("PullRequestWatchReactor.record")(function* (
262 target: WatchTarget,
263 next: ThreadPullRequestWatch | null,
264 wake?: { readonly text: string; readonly notification: OrchestrationV2Notification },
265 endedWatch?: ThreadPullRequestWatch,
266 ) {
267 const uuid = yield* crypto.randomUUIDv4();
268 yield* engine.dispatch({
269 type: "thread.pull-request-watch.sync",
270 commandId: CommandId.make(`server:pr-watch:${target.thread.id}:${uuid}`),
271 threadId: target.thread.id,
272 ...identityOf(target.link),
273 startedAt: target.watch.startedAt,
274 watch: next,
275 ...(endedWatch === undefined ? {} : { endedWatch }),
276 ...(wake === undefined
277 ? {}
278 : { wake: { ...wake, messageId: MessageId.make(`message:pr-watch:${uuid}`) } }),
279 });
280 });
281
282 const giveUp = (target: WatchTarget) =>
283 record(target, null, {
284 text: `T3 Code stopped watching pull request #${target.link.number} (${target.link.url}) because it failed to read it from the host ${READ_FAILURE_LIMIT} times in a row. Check it yourself, and call watch_pull_request to watch it again.`,
285 notification: {
286 source: { kind: "monitor" },
287 outcome: "failed",
288 summary: `#${target.link.number}: stopped watching, could not read it`,
289 },
290 }).pipe(
291 Effect.tap(() => woke(target)),
292 Effect.catch(() => record(target, null)),
293 Effect.tap(() => ended(target, "unreadable")),
294 );
295
296 const readRemarks = Effect.fn("PullRequestWatchReactor.readRemarks")(
297 function* (key: string, reference: PullRequestRef, activity: PullRequestActivity) {
298 // Comment cursors cannot account for missing threads. Only finish a truncated read
299 // when the host confirms that every thread was listed.
300 if (activity.commentsTruncated && activity.reviewThreadsTruncated !== false) return null;
301
302 let tails = threadTails.get(key);
303 if (tails === undefined) {
304 tails = new Map();
305 threadTails.set(key, tails);
306 }
307 const remarks = [...activity.comments];
308 for (const thread of activity.reviewThreads) {
309 let cursor = thread.nextCommentsCursor ?? null;
310 if (cursor === null) continue;
311 const count = thread.commentCount ?? 0;
312 let tail = tails.get(thread.id);
313 if (tail?.count !== count) {
314 const comments = new Map<string, PullRequestComment>();
315 const cursors = new Set<string>();
316 while (cursor !== null) {
317 if (cursors.has(cursor)) return null;
318 cursors.add(cursor);
319 const page: PullRequestThreadCommentsResult = yield* pullRequests.threadComments({
320 ...reference,
321 threadId: thread.id,
322 cursor,
323 });
324 for (const comment of page.comments) {
325 comments.set(comment.id, {
326 ...comment,
327 kind: "review-comment",
328 path: thread.path,
329 reviewState: null,
330 });
331 }
332 cursor = page.nextCursor;
333 }
334 if (thread.comments.length + comments.size < count) return null;
335 tail = { count, comments: [...comments.values()] };
336 tails.set(thread.id, tail);
337 }
338 remarks.push(...tail.comments);
339 }
340 return remarks.sort((left, right) => left.createdAt.localeCompare(right.createdAt));
341 },
342 Effect.catch((error) =>
343 Effect.logWarning("pull request watch comment pagination failed", { error }).pipe(
344 Effect.as(null),
345 ),
346 ),
347 );
348
349 const closed = (target: WatchTarget) =>
350 record(target, null, {
351 text: `Pull request #${target.link.number} (${target.link.url}) was closed, so T3 Code stopped watching it. Call watch_pull_request if it reopens.`,
352 notification: {
353 source: { kind: "monitor" },
354 outcome: "updated",
355 summary: `#${target.link.number}: closed, stopped watching`,
356 },
357 }).pipe(
358 Effect.tap(() => woke(target)),
359 Effect.tap(() => ended(target, "closed")),
360 );
361
362 const endsWithoutRead = ({ thread, link }: WatchTarget): WatchEndReason | undefined =>
363 link.snapshot?.state === "merged"
364 ? "merged"
365 : thread.settledOverride === "settled" || thread.settledAt !== null
366 ? "settled"
367 : thread.lineage.relationshipToParent === "subagent"
368 ? "subagent"
369 : undefined;
370
371 const eachTarget = <E>(
372 group: WatchGroup,
373 step: (target: WatchTarget) => Effect.Effect<void, E>,
374 ) =>
375 Effect.forEach(group.targets, (target) =>
376 step(target).pipe(
377 Effect.as(true),
378 Effect.catchCause((cause) => {
379 lastReads.delete(group.key);
380 return logFailure("pull request watch update failed", {
381 threadId: target.thread.id,
382 pullRequest: group.key,
383 })(cause).pipe(Effect.as(false));
384 }),
385 ),
386 ).pipe(Effect.map((landed) => landed.every(Boolean)));
387
388 const referenceOf = (group: WatchGroup) => {
389 const first = group.targets[0]!;
390 return { projectId: first.thread.projectId, ...identityOf(first.link) };
391 };
392
393 const fingerprintOf = (group: WatchGroup) =>
394 pullRequests.watchFingerprint(referenceOf(group)).pipe(
395 Effect.catchCause(
396 (cause): Effect.Effect<ProviderChangeRequestWatchFingerprint | null | "paused"> =>
397 Cause.hasInterruptsOnly(cause)
398 ? Effect.interrupt
399 : isRateLimited(cause)
400 ? Effect.succeed("paused")
401 : Effect.logDebug("pull request watch fingerprint failed", {
402 pullRequest: group.key,
403 cause,
404 }).pipe(Effect.as(null)),
405 ),
406 );
407
408 const readGroup = Effect.fn("PullRequestWatchReactor.readGroup")(function* (
409 group: WatchGroup,
410 fingerprint: ProviderChangeRequestWatchFingerprint | null,
411 ) {
412 const now = yield* Clock.currentTimeMillis;
413 const last = lastReads.get(group.key);
414 const plan = planRead(group, last, fingerprint, now);
415 if (!plan.detail) return;
416 const reference = referenceOf(group);
417 // The reads are recorded against this fingerprint, so a cached answer older than it must not
418 // stand in for them. Clients are not told: this only drops this pull request's cached reads.
419 if (fingerprint !== null) yield* pullRequests.invalidate({ reference });
420 const read = yield* Effect.exit(
421 Effect.all(
422 [
423 pullRequests.detail({ ...reference, allowStale: false }),
424 plan.activity
425 ? pullRequests.activity(reference).pipe(Effect.map(Option.some))
426 : Effect.succeed(Option.none<PullRequestActivity>()),
427 ],
428 { concurrency: 2 },
429 ),
430 );
431 if (Exit.isFailure(read)) {
432 if (Cause.hasInterruptsOnly(read.cause)) return yield* Effect.failCause(read.cause);
433 lastReads.delete(group.key);
434 if (isRateLimited(read.cause)) return;
435 const failures = (readFailures.get(group.key) ?? 0) + 1;
436 readFailures.set(group.key, failures);
437 if (failures >= READ_FAILURE_LIMIT && (yield* eachTarget(group, giveUp))) {
438 readFailures.delete(group.key);
439 }
440 return yield* Effect.failCause(read.cause);
441 }
442 readFailures.delete(group.key);
443 const [detail, activity] = read.value;
444 const headSha = detail.headSha ?? null;
445 for (const target of group.targets) {
446 const life = lifeOf(target);
447 const pushed = life.headSha !== null && headSha !== life.headSha;
448 lives.set(lifeKey(target), {
449 ...life,
450 headSha,
451 reads: life.reads + 1,
452 ...(pushed
453 ? { pushedAt: now, longestQuietMs: Math.max(life.longestQuietMs, now - life.pushedAt) }
454 : {}),
455 });
456 }
457 if (detail.state !== "open") {
458 lastReads.delete(group.key);
459 return yield* eachTarget(group, (target) =>
460 detail.state === "closed"
461 ? closed(target)
462 : record(target, null).pipe(Effect.tap(() => ended(target, "merged"))),
463 );
464 }
465
466 // Never advance the remark watermark past comments an incomplete read could have missed.
467 const remarks = Option.isSome(activity)
468 ? yield* readRemarks(group.key, reference, activity.value)
469 : null;
470 lastReads.set(group.key, {
471 at: plan.activity || last === undefined ? now : last.at,
472 fingerprint: group.fingerprint,
473 inFlight:
474 detail.mergeability === "unknown" ||
475 detail.checks.some((check) => check.status === "pending"),
476 remarksComplete: plan.activity ? remarks !== null : (last?.remarksComplete ?? false),
477 watches: new Set(group.targets.map(watchKey)),
478 status: fingerprint?.status ?? null,
479 remarks: fingerprint?.remarks ?? null,
480 });
481 yield* eachTarget(group, (target) => {
482 const report = evaluatePullRequestWatch(target.watch, detail, remarks);
483 if (report.changes.length > 0) {
484 const wake = pullRequestWatchMessage({
485 number: target.link.number,
486 url: target.link.url,
487 baseBranch: detail.baseBranch,
488 headSha: report.next.headSha,
489 report,
490 });
491 // An ending watch keeps what this pass saw, so watching again starts from it.
492 return (
493 report.exhausted
494 ? record(target, null, wake, report.next)
495 : record(target, report.next, wake)
496 ).pipe(
497 Effect.tap(() => woke(target)),
498 Effect.tap(() => (report.exhausted ? ended(target, "comment-limit") : Effect.void)),
499 );
500 }
501 return watchesEqual(report.next, target.watch) ? Effect.void : record(target, report.next);
502 });
503 });
504
505 const sweep = Effect.gen(function* () {
506 const threads = yield* projections.getThreadsWithPullRequests();
507 const targets = threads.flatMap((thread) =>
508 visibleThreadPullRequests(thread.pullRequests ?? []).flatMap((link) =>
509 link.watch === undefined ? [] : [{ thread, link, watch: link.watch }],
510 ),
511 );
512 const present = new Set(targets.map(lifeKey));
513 yield* Effect.forEach(
514 [...lives].filter(([key]) => !present.has(key)),
515 ([key, life]) => reportEnd(key, life, "stopped"),
516 { discard: true },
517 );
518 for (const target of targets) lifeOf(target);
519 const byPullRequest = new Map<string, Array<WatchTarget>>();
520 const ending: Array<readonly [WatchTarget, WatchEndReason]> = [];
521 for (const target of targets) {
522 const reason = endsWithoutRead(target);
523 if (reason !== undefined) {
524 ending.push([target, reason]);
525 continue;
526 }
527 // Grouped per project too: each project reads through its own checkout, so one that cannot
528 // read the pull request must not end another project's watches.
529 const key = `${target.thread.projectId} ${threadPullRequestKeyOf(target.link)}`;
530 byPullRequest.set(key, [...(byPullRequest.get(key) ?? []), target]);
531 }
532 const groups = [...byPullRequest].map(([key, members]): WatchGroup => ({
533 key,
534 targets: members,
535 fingerprint: [...new Set(members.map(snapshotFingerprint))].toSorted().join("\n"),
536 }));
537 for (const cache of [readFailures, lastReads, threadTails]) {
538 for (const key of cache.keys()) if (!byPullRequest.has(key)) cache.delete(key);
539 }
540 yield* Effect.forEach(
541 ending,
542 ([target, reason]) =>
543 record(target, null).pipe(
544 Effect.tap(() => ended(target, reason)),
545 Effect.catchCause(
546 logFailure("pull request watch stop failed", {
547 threadId: target.thread.id,
548 pullRequest: threadPullRequestKeyOf(target.link),
549 }),
550 ),
551 ),
552 { discard: true },
553 );
554 const fingerprints = yield* Effect.forEach(groups, fingerprintOf, {
555 concurrency: "unbounded",
556 });
557 yield* Effect.forEach(
558 groups,
559 (group, index) => {
560 const fingerprint = fingerprints[index]!;
561 return fingerprint === "paused"
562 ? Effect.void
563 : readGroup(group, fingerprint).pipe(
564 Effect.catchCause(
565 logFailure("pull request watch check failed", { pullRequest: group.key }),
566 ),
567 );
568 },
569 { concurrency: 4, discard: true },
570 );
571 }).pipe(
572 Effect.catchCause(logFailure("pull request watch sweep failed", {})),
573 Effect.withSpan("PullRequestWatchReactor.sweep"),
574 );
575
576 const start: PullRequestWatchReactor["Service"]["start"] = () =>
577 forkParked(
578 sweep.pipe(Effect.repeat(Schedule.spaced(`${SWEEP_MINUTES} minutes`)), Effect.asVoid),
579 );
580
581 return { start, sweep } satisfies PullRequestWatchReactor["Service"];
582});
583
584export const layer = Layer.effect(PullRequestWatchReactor, make);