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