Open History to see the last commit
1import {
2 CommandId,
3 isOrchestrationV2WorkActive,
4 MessageId,
5 type OrchestrationV2Notification,
6 type PullRequestActivity,
7 type PullRequestComment,
8 type PullRequestDetail,
9 type PullRequestRef,
10 type PullRequestThreadCommentsResult,
11 type ThreadPullRequestLink,
12 type ThreadId,
13 type ThreadPullRequestWatch,
14} from "@t3tools/contracts";
15import { commandIndicatesFailure } from "@t3tools/shared/toolOutput";
16import {
17 changeRequestsClosedBy,
18 isChangeRequestCloseCommand,
19} from "../sourceControl/sourceControlDefinitions.ts";
20import {
21 normalizeThreadPullRequestKey,
22 threadPullRequestKeyOf,
23 visibleThreadPullRequests,
24} from "../sourceControl/threadPullRequests.ts";
25import * as Cause from "effect/Cause";
26import * as Clock from "effect/Clock";
27import * as Context from "effect/Context";
28import * as SecureRandom from "effect/crypto/SecureRandom";
29import * as Effect from "effect/Effect";
30import * as Exit from "effect/Exit";
31import * as FiberMap from "effect/FiberMap";
32import * as Layer from "effect/Layer";
33import * as Option from "effect/Option";
34import * as Schedule from "effect/Schedule";
35import * as Schema from "effect/Schema";
36import * as Semaphore from "effect/Semaphore";
37import type * as Scope from "effect/Scope";
38import * as Stream from "effect/Stream";
39
40import {
41 type ProviderChangeRequestWatchFingerprint,
42 PullRequestProviderError,
43} from "@t3tools/source-control-core/server/PullRequestProvider";
44import * as PullRequestService from "../pullRequest/PullRequestService.ts";
45import { forkParked } from "../serverActivation.ts";
46import * as Orchestrator from "./Orchestrator.ts";
47import * as ProjectionStore from "./ProjectionStore.ts";
48import { isTerminalRunStatus } from "./ThreadManagementService.ts";
49import {
50 combinePullRequestWatchWakes,
51 evaluatePullRequestWatch,
52 PULL_REQUEST_WATCH_NO_CHECKS_MS,
53 pullRequestWatchEndMessage,
54 pullRequestWatchMessage,
55} from "./pullRequestWatch.ts";
56
57/** Checks take minutes; faster sweeps waste the account's shared host quota. */
58const SWEEP_MINUTES = 2;
59const READ_FAILURE_LIMIT = 8;
60/** Group reads in flight at once, inside the host's own request limit. */
61const GROUP_READS = 4;
62/** Without fingerprints, reread quiet PRs on snapshot changes or this interval to catch edits. */
63const QUIET_REREAD_MS = 10 * 60_000;
64/** Reread despite unchanged fingerprints; they miss review-thread comment edits. */
65const FINGERPRINT_REREAD_MS = 30 * 60_000;
66
67const isProviderError = Schema.is(PullRequestProviderError);
68
69const providerFailureReason = (cause: Cause.Cause<PullRequestService.PullRequestError>) =>
70 Option.match(Cause.findErrorOption(cause), {
71 onNone: () => null,
72 onSome: (error) =>
73 error._tag === "PullRequestOperationError" && isProviderError(error.cause)
74 ? error.cause.reason
75 : null,
76 });
77
78const logFailure =
79 (message: string, fields: Record<string, unknown>) =>
80 <E>(cause: Cause.Cause<E>): Effect.Effect<void> =>
81 Cause.hasInterruptsOnly(cause)
82 ? Effect.interrupt
83 : Effect.logWarning(message, { ...fields, cause });
84
85interface WatchTarget {
86 readonly thread: ProjectionStore.ProjectionThreadPullRequests;
87 readonly link: ThreadPullRequestLink;
88 readonly watch: ThreadPullRequestWatch;
89}
90
91interface WatchGroup {
92 readonly key: string;
93 readonly targets: ReadonlyArray<WatchTarget>;
94 readonly fingerprint: string;
95}
96
97interface LastRead {
98 readonly at: number;
99 readonly fingerprint: string;
100 readonly inFlight: boolean;
101 readonly remarksComplete: boolean;
102 readonly watches: ReadonlySet<string>;
103 readonly status: string | null;
104 readonly remarks: string | null;
105}
106
107interface ReadPlan {
108 readonly detail: boolean;
109 readonly activity: boolean;
110}
111
112interface Wake {
113 readonly text: string;
114 readonly notification: OrchestrationV2Notification;
115 readonly includesRemarks?: boolean;
116}
117
118/** A wake a pass holds back so each thread gets one for everything the pass found. */
119interface HeldWake {
120 readonly groupKey: string;
121 readonly target: WatchTarget;
122 readonly next: ThreadPullRequestWatch | null;
123 readonly endedWatch?: ThreadPullRequestWatch;
124 readonly wake: Wake;
125 readonly reason?: WatchEndReason;
126}
127
128const watchKey = ({ thread, watch }: WatchTarget) => `${thread.id} ${watch.startedAt}`;
129
130type WatchEndReason =
131 | "merged"
132 | "closed"
133 | "unreadable"
134 | "comment-limit"
135 | "settled"
136 | "moved"
137 | "subagent"
138 | "stopped";
139
140interface WatchLife {
141 readonly threadId: string;
142 readonly pullRequest: string;
143 readonly startedAt: number;
144 readonly headSha: string | null;
145 readonly pushedAt: number;
146 readonly longestQuietMs: number;
147 readonly wakes: number;
148 readonly reads: number;
149}
150
151const lifeKeyOf = (threadId: string, link: ThreadPullRequestLink, watch: ThreadPullRequestWatch) =>
152 `${threadId} ${threadPullRequestKeyOf(link)} ${watch.startedAt}`;
153const lifeKey = ({ thread, link, watch }: WatchTarget) => lifeKeyOf(thread.id, link, watch);
154
155const minutes = (ms: number) => Math.max(0, Math.round(ms / 60_000));
156
157const snapshotFingerprint = ({ link }: WatchTarget) => {
158 const snapshot = link.snapshot;
159 return snapshot === null
160 ? ""
161 : [
162 snapshot.state,
163 snapshot.updatedAt,
164 snapshot.checksState,
165 snapshot.mergeability,
166 snapshot.rebaseRequired,
167 snapshot.reviewDecision,
168 snapshot.isDraft,
169 ].join(" ");
170};
171
172function planRead(
173 group: WatchGroup,
174 last: LastRead | undefined,
175 fingerprint: ProviderChangeRequestWatchFingerprint | null,
176 now: number,
177): ReadPlan {
178 if (last === undefined || group.targets.some((target) => !last.watches.has(watchKey(target)))) {
179 return { detail: true, activity: true };
180 }
181 // Nothing on the host changes when the no-checks deadline passes, or when a push to another
182 // branch clears a watch's answer, so either alone prompts a read.
183 const checksDue = group.targets.some(
184 ({ watch }) =>
185 watch.checksPending === undefined ||
186 (watch.checksAwaitedSince != null &&
187 now - Date.parse(watch.checksAwaitedSince) >= PULL_REQUEST_WATCH_NO_CHECKS_MS),
188 );
189 if (fingerprint === null) {
190 const read =
191 last.inFlight ||
192 !last.remarksComplete ||
193 last.fingerprint !== group.fingerprint ||
194 now - last.at >= QUIET_REREAD_MS;
195 return { detail: read || checksDue, activity: read };
196 }
197 const activity =
198 last.remarks !== fingerprint.remarks ||
199 !last.remarksComplete ||
200 now - last.at >= FINGERPRINT_REREAD_MS;
201 return {
202 detail:
203 activity ||
204 checksDue ||
205 last.status !== fingerprint.status ||
206 (last.inFlight && fingerprint.coversDetail !== true),
207 activity,
208 };
209}
210
211// Lets the orchestrator tell that a push cleared the answer while this read was in flight.
212const checksPendingBeforeOf = ({ watch }: WatchTarget) =>
213 watch.checksPending === undefined ? {} : { checksPendingBefore: watch.checksPending };
214
215function watchesEqual(left: ThreadPullRequestWatch, right: ThreadPullRequestWatch): boolean {
216 return (
217 left.startedAt === right.startedAt &&
218 left.headSha === right.headSha &&
219 left.failedChecks.join("\n") === right.failedChecks.join("\n") &&
220 left.passed === right.passed &&
221 left.passedChecks.join("\n") === right.passedChecks.join("\n") &&
222 (left.owedChecks ?? []).join("\n") === (right.owedChecks ?? []).join("\n") &&
223 (left.awaitingApproval ?? []).join("\n") === (right.awaitingApproval ?? []).join("\n") &&
224 (left.approvalAnnounced ?? false) === (right.approvalAnnounced ?? false) &&
225 left.remarksThrough === right.remarksThrough &&
226 left.remarkIds.join("\n") === right.remarkIds.join("\n") &&
227 left.conflicting === right.conflicting &&
228 left.rebaseRequired === right.rebaseRequired &&
229 left.mergeQueueRemovalId === right.mergeQueueRemovalId &&
230 left.wakes === right.wakes &&
231 left.awaitingBaseline === right.awaitingBaseline &&
232 left.checksAwaitedSince === right.checksAwaitedSince &&
233 left.checksPending === right.checksPending &&
234 left.until === right.until
235 );
236}
237
238export class PullRequestWatchReactor extends Context.Service<
239 PullRequestWatchReactor,
240 {
241 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
242 readonly sweep: Effect.Effect<void>;
243 }
244>()("t3/orchestration-v2/PullRequestWatchReactor") {}
245
246/** @public */
247export const make = Effect.gen(function* () {
248 const engine = yield* Orchestrator.OrchestratorV2;
249 const projections = yield* ProjectionStore.ProjectionStoreV2;
250 const pullRequests = yield* PullRequestService.PullRequestService;
251 const random = yield* SecureRandom.SecureRandom;
252 const bootedAt = yield* Clock.currentTimeMillis;
253 const lives = new Map<string, WatchLife>();
254
255 const lifeOf = (target: WatchTarget): WatchLife => {
256 const existing = lives.get(lifeKey(target));
257 if (existing !== undefined) return existing;
258 const startedAt = Date.parse(target.watch.startedAt);
259 const life: WatchLife = {
260 threadId: target.thread.id,
261 pullRequest: threadPullRequestKeyOf(target.link),
262 startedAt,
263 headSha: target.watch.headSha,
264 pushedAt: startedAt,
265 longestQuietMs: 0,
266 wakes: 0,
267 reads: 0,
268 };
269 lives.set(lifeKey(target), life);
270 return life;
271 };
272 const woke = (target: WatchTarget) =>
273 Effect.sync(() => {
274 const life = lifeOf(target);
275 lives.set(lifeKey(target), { ...life, wakes: life.wakes + 1 });
276 });
277
278 const reportEnd = Effect.fn("PullRequestWatchReactor.reportEnd")(function* (
279 key: string,
280 life: WatchLife,
281 reason: WatchEndReason,
282 ) {
283 lives.delete(key);
284 const now = yield* Clock.currentTimeMillis;
285 const quietMs = now - life.pushedAt;
286 yield* Effect.logInfo("pull request watch ended", {
287 threadId: life.threadId,
288 pullRequest: life.pullRequest,
289 reason,
290 minutes: minutes(now - life.startedAt),
291 quietMinutes: minutes(quietMs),
292 longestQuietMinutes: minutes(Math.max(life.longestQuietMs, quietMs)),
293 wakes: life.wakes,
294 reads: life.reads,
295 partial: life.startedAt < bootedAt,
296 });
297 });
298 const ended = (target: WatchTarget, reason: WatchEndReason) =>
299 Effect.suspend(() => reportEnd(lifeKey(target), lifeOf(target), reason));
300
301 const readFailures = new Map<string, number>();
302 /** The last sweep's groups, whose pull requests get host change feeds. */
303 let currentGroups: ReadonlyArray<WatchGroup> = [];
304 // A pass reads watches and records new ones, so passes must not overlap.
305 const passes = Semaphore.makeUnsafe(1);
306 const lastReads = new Map<string, LastRead>();
307 /**
308 * Each thread's merge and close commands, by item, with the pull requests each names. One counts
309 * while it runs and, if it succeeded, until the read at its end is done.
310 */
311 const agentEnds = new Map<ThreadId, Map<string, ReadonlySet<number> | "any">>();
312 // The agent needs no wake for a merge or close it made itself. Anything ending later, as a
313 // `--auto` merge does, is news.
314 const endedByAgent = (target: WatchTarget) =>
315 [...(agentEnds.get(target.thread.id)?.values() ?? [])].some(
316 (named) => named === "any" || named.has(target.link.number),
317 );
318 const threadTails = new Map<
319 string,
320 {
321 readonly fetchedAt: number;
322 readonly visibleThrough: number;
323 readonly tails: ReadonlyMap<
324 string,
325 { readonly count: number; readonly comments: ReadonlyArray<PullRequestComment> }
326 >;
327 }
328 >();
329
330 const identityOf = (link: ThreadPullRequestLink) => ({
331 host: normalizeThreadPullRequestKey(link).host,
332 repository: link.repository,
333 number: link.number,
334 });
335
336 /**
337 * The orchestrator applies this only while the same watch is on, so a stop or restart
338 * that lands during the host read wins.
339 */
340 const record = Effect.fn("PullRequestWatchReactor.record")(function* (
341 target: WatchTarget,
342 next: ThreadPullRequestWatch | null,
343 wake?: Wake,
344 endedWatch?: ThreadPullRequestWatch,
345 ) {
346 const uuid = yield* random.uuidV4();
347 yield* engine.dispatch({
348 type: "thread.pull-request-watch.sync",
349 commandId: CommandId.make(`server:pr-watch:${target.thread.id}:${uuid}`),
350 threadId: target.thread.id,
351 ...identityOf(target.link),
352 startedAt: target.watch.startedAt,
353 watch: next,
354 ...checksPendingBeforeOf(target),
355 ...(endedWatch === undefined ? {} : { endedWatch }),
356 ...(wake === undefined
357 ? {}
358 : { wake: { ...wake, messageId: MessageId.make(`message:pr-watch:${uuid}`) } }),
359 });
360 });
361
362 const giveUp = (target: WatchTarget, cause: Cause.Cause<PullRequestService.PullRequestError>) => {
363 const error = Option.getOrUndefined(Cause.findErrorOption(cause));
364 // The message is the host's own setup instruction, never the subprocess output in `cause`.
365 const unusable =
366 error?._tag === "PullRequestUnavailableError" && error.reason !== "provider-unsupported"
367 ? error.message
368 : null;
369 return record(target, null, {
370 text:
371 unusable === null
372 ? `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 only if it is still open.`
373 : `T3 Code stopped watching pull request #${target.link.number} (${target.link.url}) because the T3 Code server cannot use the host: ${unusable} Fix that on the server, then call watch_pull_request only if it is still open.`,
374 notification: {
375 source: { kind: "monitor" },
376 outcome: "failed",
377 summary: `#${target.link.number}: stopped watching, ${unusable === null ? "could not read it" : "host not set up on the server"}`,
378 },
379 }).pipe(
380 Effect.tap(() => woke(target)),
381 Effect.catch(() => record(target, null)),
382 Effect.tap(() => ended(target, "unreadable")),
383 );
384 };
385
386 const readRemarks = Effect.fn("PullRequestWatchReactor.readRemarks")(
387 function* (
388 key: string,
389 reference: PullRequestRef,
390 activity: PullRequestActivity,
391 now: number,
392 rereadMs: number,
393 ) {
394 // Comment cursors cannot account for missing threads. Only finish a truncated read
395 // when the host confirms that every thread was listed.
396 if (activity.commentsTruncated && activity.reviewThreadsTruncated !== false) return null;
397
398 const visibleThrough = activity.comments.reduce(
399 (latest, comment) => Math.max(latest, Date.parse(comment.editedAt ?? comment.createdAt)),
400 0,
401 );
402 const paginated = activity.reviewThreads.filter(
403 (thread) => thread.nextCommentsCursor != null,
404 );
405 const cached = threadTails.get(key);
406 // All tails share one watermark, so newer visible remarks or a changed thread must
407 // refresh the entire group before any remarks can advance it.
408 const reuse =
409 cached !== undefined &&
410 now - cached.fetchedAt < rereadMs &&
411 cached.visibleThrough === visibleThrough &&
412 cached.tails.size === paginated.length &&
413 paginated.every(
414 (thread) => cached.tails.get(thread.id)?.count === (thread.commentCount ?? 0),
415 );
416 const tails = new Map<
417 string,
418 { count: number; comments: ReadonlyArray<PullRequestComment> }
419 >();
420 const remarks = [...activity.comments];
421 for (const thread of paginated) {
422 let cursor = thread.nextCommentsCursor ?? null;
423 const count = thread.commentCount ?? 0;
424 let tail = reuse ? cached.tails.get(thread.id) : undefined;
425 if (tail === undefined) {
426 const comments = new Map<string, PullRequestComment>();
427 const cursors = new Set<string>();
428 let hidden = 0;
429 while (cursor !== null) {
430 if (cursors.has(cursor)) return null;
431 cursors.add(cursor);
432 const page: PullRequestThreadCommentsResult = yield* pullRequests.threadComments({
433 ...reference,
434 threadId: thread.id,
435 cursor,
436 });
437 for (const comment of page.comments) {
438 comments.set(comment.id, {
439 ...comment,
440 kind: "review-comment",
441 path: thread.path,
442 reviewState: null,
443 });
444 }
445 hidden += page.hiddenCount ?? 0;
446 cursor = page.nextCursor;
447 }
448 if (thread.comments.length + comments.size + hidden < count) return null;
449 tail = { count, comments: [...comments.values()] };
450 }
451 tails.set(thread.id, tail);
452 remarks.push(...tail.comments);
453 }
454 threadTails.set(key, {
455 fetchedAt: reuse ? cached.fetchedAt : now,
456 visibleThrough,
457 tails,
458 });
459 return remarks.sort((left, right) => left.createdAt.localeCompare(right.createdAt));
460 },
461 Effect.catch((error) =>
462 Effect.logWarning("pull request watch comment pagination failed", { error }).pipe(
463 Effect.as(null),
464 ),
465 ),
466 (effect, key) =>
467 effect.pipe(
468 Effect.onExit((exit) =>
469 Effect.sync(() => {
470 // A retry must refresh every tail before advancing the shared remark watermark.
471 if (Exit.isFailure(exit) || exit.value === null) threadTails.delete(key);
472 }),
473 ),
474 ),
475 );
476
477 /** Wakes the current pass found, sent by `sendHeld` once every read of the pass is done. */
478 let held: Array<HeldWake> = [];
479 const hold = (wake: HeldWake) => Effect.sync(() => void held.push(wake));
480
481 const sendOne = (item: HeldWake) =>
482 record(item.target, item.next, item.wake, item.endedWatch).pipe(
483 Effect.tap(() => woke(item.target)),
484 Effect.tap(() => (item.reason === undefined ? Effect.void : ended(item.target, item.reason))),
485 Effect.catchCause((cause) => {
486 lastReads.delete(item.groupKey);
487 return logFailure("pull request watch update failed", {
488 threadId: item.target.thread.id,
489 pullRequest: item.groupKey,
490 })(cause);
491 }),
492 );
493
494 const sendTogether = Effect.fn("PullRequestWatchReactor.sendTogether")(function* (
495 items: readonly [HeldWake, ...ReadonlyArray<HeldWake>],
496 ) {
497 const [first, ...rest] = items;
498 const uuid = yield* random.uuidV4();
499 yield* engine.dispatch({
500 type: "thread.pull-request-watch.sync",
501 commandId: CommandId.make(`server:pr-watch:${first.target.thread.id}:${uuid}`),
502 threadId: first.target.thread.id,
503 ...identityOf(first.target.link),
504 startedAt: first.target.watch.startedAt,
505 watch: first.next,
506 ...checksPendingBeforeOf(first.target),
507 ...(first.endedWatch === undefined ? {} : { endedWatch: first.endedWatch }),
508 others: rest.map((item) => ({
509 ...identityOf(item.target.link),
510 startedAt: item.target.watch.startedAt,
511 watch: item.next,
512 ...checksPendingBeforeOf(item.target),
513 ...(item.endedWatch === undefined ? {} : { endedWatch: item.endedWatch }),
514 ...(item.wake.includesRemarks === true ? { includesRemarks: true } : {}),
515 })),
516 wake: {
517 ...combinePullRequestWatchWakes([first.wake, ...rest.map((item) => item.wake)]),
518 ...(first.wake.includesRemarks === true ? { includesRemarks: true } : {}),
519 sections: items.map(({ wake }) => ({
520 text: wake.text,
521 outcome: wake.notification.outcome,
522 summary: wake.notification.summary,
523 })),
524 messageId: MessageId.make(`message:pr-watch:${uuid}`),
525 },
526 });
527 yield* Effect.forEach(
528 items,
529 (item) =>
530 woke(item.target).pipe(
531 Effect.andThen(item.reason === undefined ? Effect.void : ended(item.target, item.reason)),
532 ),
533 { discard: true },
534 );
535 });
536
537 const sendHeld = Effect.suspend(() => {
538 const byThread = new Map<string, Array<HeldWake>>();
539 for (const item of held) {
540 byThread.set(item.target.thread.id, [...(byThread.get(item.target.thread.id) ?? []), item]);
541 }
542 held = [];
543 return Effect.forEach(
544 byThread.values(),
545 ([first, ...rest]) =>
546 rest.length === 0
547 ? sendOne(first!)
548 : // A watch that ended or moved during the pass fails the whole command; each then
549 // goes on its own, as the orchestrator decides for it alone.
550 sendTogether([first!, ...rest]).pipe(
551 Effect.catchCauseIf(
552 (cause) => !Cause.hasInterruptsOnly(cause),
553 () => Effect.forEach([first!, ...rest], sendOne, { discard: true }),
554 ),
555 ),
556 { discard: true },
557 );
558 });
559
560 const finished = (
561 groupKey: string,
562 target: WatchTarget,
563 detail: Pick<PullRequestDetail, "state" | "baseBranch" | "mergeCommitSha" | "mergedBy">,
564 ) => {
565 const reason = detail.state === "merged" ? "merged" : "closed";
566 return endedByAgent(target)
567 ? record(target, null).pipe(Effect.tap(() => ended(target, reason)))
568 : hold({
569 groupKey,
570 target,
571 next: null,
572 wake: pullRequestWatchEndMessage({
573 number: target.link.number,
574 url: target.link.url,
575 detail,
576 }),
577 reason,
578 });
579 };
580
581 // A merged snapshot still gets one read, so the wake can name the merge commit.
582 const endsWithoutRead = ({ thread }: WatchTarget): WatchEndReason | undefined =>
583 thread.handoff?.state === "departed"
584 ? "moved"
585 : thread.settledOverride === "settled" || thread.settledAt !== null
586 ? "settled"
587 : thread.lineage.relationshipToParent === "subagent"
588 ? "subagent"
589 : undefined;
590
591 const eachTarget = <E>(
592 group: WatchGroup,
593 step: (target: WatchTarget) => Effect.Effect<void, E>,
594 ) =>
595 Effect.forEach(group.targets, (target) =>
596 step(target).pipe(
597 Effect.as(true),
598 Effect.catchCause((cause) => {
599 lastReads.delete(group.key);
600 return logFailure("pull request watch update failed", {
601 threadId: target.thread.id,
602 pullRequest: group.key,
603 })(cause).pipe(Effect.as(false));
604 }),
605 ),
606 ).pipe(Effect.map((landed) => landed.every(Boolean)));
607
608 // A merged PR's watch holds its thread from settling, so it must not wait out the host.
609 const endMergedSnapshots = (group: WatchGroup) => {
610 const merged = group.targets.filter((target) => target.link.snapshot?.state === "merged");
611 return eachTarget({ ...group, targets: merged }, (target) =>
612 target.link.snapshot ? finished(group.key, target, target.link.snapshot) : Effect.void,
613 ).pipe(
614 Effect.as({ ...group, targets: group.targets.filter((target) => !merged.includes(target)) }),
615 );
616 };
617
618 const referenceOf = (group: WatchGroup) => {
619 const first = group.targets[0]!;
620 return { projectId: first.thread.projectId, ...identityOf(first.link) };
621 };
622
623 const fingerprintOf = (group: WatchGroup) =>
624 pullRequests.watchFingerprint(referenceOf(group)).pipe(
625 Effect.catchCause(
626 (cause): Effect.Effect<ProviderChangeRequestWatchFingerprint | null | "paused"> =>
627 Cause.hasInterruptsOnly(cause)
628 ? Effect.interrupt
629 : providerFailureReason(cause) === "rate-limited"
630 ? Effect.succeed("paused")
631 : Effect.logDebug("pull request watch fingerprint failed", {
632 pullRequest: group.key,
633 cause,
634 }).pipe(Effect.as(null)),
635 ),
636 );
637
638 const readGroup = Effect.fn("PullRequestWatchReactor.readGroup")(function* (
639 group: WatchGroup,
640 fingerprint: ProviderChangeRequestWatchFingerprint | null,
641 ) {
642 const now = yield* Clock.currentTimeMillis;
643 const last = lastReads.get(group.key);
644 const plan = planRead(group, last, fingerprint, now);
645 if (!plan.detail) return;
646 if (
647 last === undefined ||
648 group.targets.some((target) => !last.watches.has(watchKey(target))) ||
649 (fingerprint !== null && last.remarks !== fingerprint.remarks)
650 ) {
651 // A new watch or changed host remarks needs a fresh view of every tail.
652 threadTails.delete(group.key);
653 }
654 const reference = referenceOf(group);
655 // Invalidate cached reads before using the newer fingerprint; clients receive no notification.
656 if (fingerprint !== null) yield* pullRequests.invalidate({ reference });
657 const [detailRead, activityRead] = yield* Effect.all(
658 [
659 Effect.exit(pullRequests.detail({ ...reference, allowStale: false })),
660 Effect.exit(
661 plan.activity
662 ? pullRequests.activity(reference).pipe(Effect.asSome)
663 : Effect.succeed(Option.none<PullRequestActivity>()),
664 ),
665 ],
666 { concurrency: 2 },
667 );
668 if (Exit.isFailure(detailRead)) {
669 if (Cause.hasInterruptsOnly(detailRead.cause))
670 return yield* Effect.failCause(detailRead.cause);
671 lastReads.delete(group.key);
672 const unended = yield* endMergedSnapshots(group);
673 if (unended.targets.length === 0) {
674 readFailures.delete(group.key);
675 return;
676 }
677 const reason = providerFailureReason(detailRead.cause);
678 if (reason === "rate-limited") return;
679 // Transport and host failures can outlast the failure limit; keep the watch for recovery.
680 if (reason === "failed") {
681 readFailures.delete(group.key);
682 return yield* Effect.failCause(detailRead.cause);
683 }
684 const failures = (readFailures.get(group.key) ?? 0) + 1;
685 readFailures.set(group.key, failures);
686 if (
687 failures >= READ_FAILURE_LIMIT &&
688 (yield* eachTarget(unended, (target) => giveUp(target, detailRead.cause)))
689 ) {
690 readFailures.delete(group.key);
691 }
692 return yield* Effect.failCause(detailRead.cause);
693 }
694 readFailures.delete(group.key);
695 const detail = detailRead.value;
696 for (const target of group.targets) {
697 const life = lifeOf(target);
698 const headSha = detail.headSha ?? life.headSha;
699 const pushed = life.headSha !== null && headSha !== life.headSha;
700 lives.set(lifeKey(target), {
701 ...life,
702 headSha,
703 reads: life.reads + 1,
704 ...(pushed
705 ? { pushedAt: now, longestQuietMs: Math.max(life.longestQuietMs, now - life.pushedAt) }
706 : {}),
707 });
708 }
709 if (detail.state !== "open") {
710 lastReads.delete(group.key);
711 return yield* eachTarget(group, (target) => finished(group.key, target, detail));
712 }
713
714 // A failed comments read leaves remarks incomplete, so the next pass reads them again;
715 // checks, head and conflicts from the detail still reach the evaluator.
716 if (Exit.isFailure(activityRead)) {
717 threadTails.delete(group.key);
718 if (providerFailureReason(activityRead.cause) !== "rate-limited") {
719 yield* logFailure("pull request watch activity read failed", { pullRequest: group.key })(
720 activityRead.cause,
721 );
722 }
723 }
724 const activity = Exit.isSuccess(activityRead)
725 ? activityRead.value
726 : Option.none<PullRequestActivity>();
727
728 // Never advance the remark watermark past comments an incomplete read could have missed.
729 const remarks = Option.isSome(activity)
730 ? yield* readRemarks(
731 group.key,
732 reference,
733 activity.value,
734 now,
735 fingerprint === null ? QUIET_REREAD_MS : FINGERPRINT_REREAD_MS,
736 )
737 : null;
738 lastReads.set(group.key, {
739 at:
740 plan.activity || last === undefined
741 ? (threadTails.get(group.key)?.fetchedAt ?? now)
742 : last.at,
743 fingerprint: group.fingerprint,
744 inFlight:
745 detail.mergeability === "unknown" ||
746 detail.checks.some((check) => check.status === "pending"),
747 remarksComplete: plan.activity ? remarks !== null : (last?.remarksComplete ?? false),
748 watches: new Set(group.targets.map(watchKey)),
749 status: fingerprint?.status ?? null,
750 remarks: fingerprint?.remarks ?? null,
751 });
752 yield* eachTarget(group, (target) => {
753 const report = evaluatePullRequestWatch(target.watch, detail, remarks, now);
754 if (report.changes.length > 0) {
755 const wake = {
756 ...pullRequestWatchMessage({
757 number: target.link.number,
758 url: target.link.url,
759 baseBranch: detail.baseBranch,
760 headSha: report.next.headSha,
761 report,
762 }),
763 includesRemarks: report.changes.some((change) => change.kind === "remarks"),
764 };
765 // An ending watch keeps what this pass saw, so watching again starts from it.
766 return hold(
767 report.exhausted
768 ? {
769 groupKey: group.key,
770 target,
771 next: null,
772 endedWatch: report.next,
773 wake,
774 reason: "comment-limit",
775 }
776 : { groupKey: group.key, target, next: report.next, wake },
777 );
778 }
779 return watchesEqual(report.next, target.watch) ? Effect.void : record(target, report.next);
780 });
781 });
782
783 /** Every watch, or with `changed`, only that pull request's after its host reported a change. */
784 // The sweep and change reads each name their own span.
785 const pass = Effect.fnUntraced(function* (changed: string | undefined) {
786 held = [];
787 const threads = yield* projections.getThreadsWithPullRequests();
788 const targets = threads.flatMap((thread) =>
789 visibleThreadPullRequests(thread.pullRequests ?? []).flatMap((link) =>
790 link.watch === undefined ||
791 (changed !== undefined && threadPullRequestKeyOf(link) !== changed)
792 ? []
793 : [{ thread, link, watch: link.watch }],
794 ),
795 );
796 if (changed === undefined) {
797 const present = new Set(targets.map(lifeKey));
798 yield* Effect.forEach(
799 [...lives].filter(([key]) => !present.has(key)),
800 ([key, life]) => reportEnd(key, life, "stopped"),
801 { discard: true },
802 );
803 }
804 for (const target of targets) lifeOf(target);
805 const byPullRequest = new Map<string, Array<WatchTarget>>();
806 const ending: Array<readonly [WatchTarget, WatchEndReason]> = [];
807 for (const target of targets) {
808 const reason = endsWithoutRead(target);
809 if (reason !== undefined) {
810 ending.push([target, reason]);
811 continue;
812 }
813 // The watch must survive a failed handoff, but it cannot wake the source during the move.
814 if (target.thread.handoff?.state === "departing") continue;
815 // Group by project because checkout access differs; one failure must not end another project's watches.
816 const key = `${target.thread.projectId} ${threadPullRequestKeyOf(target.link)}`;
817 byPullRequest.set(key, [...(byPullRequest.get(key) ?? []), target]);
818 }
819 const groups = [...byPullRequest].map(([key, members]): WatchGroup => ({
820 key,
821 targets: members,
822 fingerprint: [...new Set(members.map(snapshotFingerprint))].toSorted().join("\n"),
823 }));
824 if (changed === undefined) {
825 currentGroups = groups;
826 for (const cache of [readFailures, lastReads, threadTails]) {
827 for (const key of cache.keys()) if (!byPullRequest.has(key)) cache.delete(key);
828 }
829 }
830 yield* Effect.forEach(
831 ending,
832 ([target, reason]) =>
833 record(target, null).pipe(
834 Effect.tap(() => ended(target, reason)),
835 Effect.catchCause(
836 logFailure("pull request watch stop failed", {
837 threadId: target.thread.id,
838 pullRequest: threadPullRequestKeyOf(target.link),
839 }),
840 ),
841 ),
842 { discard: true },
843 );
844 // Every fingerprint is asked for at once so the host can batch them, and each group reads
845 // as soon as its own answer lands rather than waiting on the slowest host.
846 const reads = yield* Semaphore.make(GROUP_READS);
847 yield* Effect.forEach(
848 groups,
849 (group) =>
850 // The host just reported a change, so a cached fingerprint may predate it.
851 (changed === undefined
852 ? Effect.void
853 : pullRequests.invalidate({ reference: referenceOf(group) })
854 ).pipe(
855 Effect.andThen(fingerprintOf(group)),
856 Effect.tap((fingerprint) => {
857 const last = lastReads.get(group.key);
858 // Open pull request views refresh only when the host state moved.
859 return changed !== undefined &&
860 fingerprint !== null &&
861 fingerprint !== "paused" &&
862 (last === undefined ||
863 last.status !== fingerprint.status ||
864 last.remarks !== fingerprint.remarks)
865 ? pullRequests.invalidate({ reference: referenceOf(group) }, { notifyReaders: true })
866 : Effect.void;
867 }),
868 Effect.flatMap((fingerprint) =>
869 fingerprint === "paused"
870 ? endMergedSnapshots(group).pipe(Effect.asVoid)
871 : reads.withPermit(
872 readGroup(group, fingerprint).pipe(
873 Effect.catchCause(
874 logFailure("pull request watch check failed", { pullRequest: group.key }),
875 ),
876 ),
877 ),
878 ),
879 ),
880 { concurrency: "unbounded", discard: true },
881 );
882 yield* sendHeld;
883 }, passes.withPermit);
884
885 const sweep = pass(undefined).pipe(
886 Effect.catchCause(logFailure("pull request watch sweep failed", {})),
887 Effect.withSpan("PullRequestWatchReactor.sweep"),
888 );
889
890 const pullRequestOf = (group: WatchGroup) => threadPullRequestKeyOf(group.targets[0]!.link);
891
892 const readOnChange = (pullRequest: string) =>
893 pass(pullRequest).pipe(
894 Effect.catchCause(logFailure("pull request watch change read failed", { pullRequest })),
895 Effect.withSpan("PullRequestWatchReactor.readOnChange"),
896 );
897
898 // A full read, since an unchanged fingerprint or snapshot would otherwise skip the detail.
899 const readThreadWatches = (threadId: ThreadId) =>
900 projections.getThreadsWithPullRequests(threadId).pipe(
901 Effect.flatMap((threads) =>
902 Effect.forEach(
903 threads.flatMap((thread) =>
904 visibleThreadPullRequests(thread.pullRequests ?? [])
905 .filter((link) => link.watch !== undefined)
906 .map((link) => [thread.projectId, threadPullRequestKeyOf(link)] as const),
907 ),
908 ([projectId, pullRequest]) =>
909 // After any pass in flight, which could record a read from before the merge.
910 passes
911 .withPermit(Effect.sync(() => lastReads.delete(`${projectId} ${pullRequest}`)))
912 .pipe(Effect.andThen(readOnChange(pullRequest))),
913 { discard: true },
914 ),
915 ),
916 Effect.catchCause(logFailure("pull request watch read after a merge failed", { threadId })),
917 );
918
919 const start: PullRequestWatchReactor["Service"]["start"] = Effect.fn(
920 "PullRequestWatchReactor.start",
921 )(function* () {
922 // Reading a thread's watches as its agent's merge or close ends lets them end at once.
923 const agentReads = yield* FiberMap.make<string>();
924 const finished = new Set<string>();
925 yield* forkParked(
926 Stream.runForEach(engine.streamDomainEvents, (event) => {
927 if (event.type === "run.updated") {
928 // A run can stop before its command reports that it ended.
929 const commands = agentEnds.get(event.threadId);
930 if (commands === undefined || !isTerminalRunStatus(event.payload.status)) {
931 return Effect.void;
932 }
933 for (const id of commands.keys()) if (!finished.has(id)) commands.delete(id);
934 if (commands.size === 0) agentEnds.delete(event.threadId);
935 return Effect.void;
936 }
937 if (event.type !== "turn-item.updated") return Effect.void;
938 const item = event.payload;
939 if (
940 item.type !== "command_execution" ||
941 finished.has(item.id) ||
942 !isChangeRequestCloseCommand(item.input)
943 ) {
944 return Effect.void;
945 }
946 const commands = agentEnds.get(event.threadId) ?? new Map();
947 agentEnds.set(event.threadId, commands);
948 commands.set(item.id, changeRequestsClosedBy(item.input));
949 if (isOrchestrationV2WorkActive(item.status)) return Effect.void;
950 finished.add(item.id);
951 const done = Effect.sync(() => {
952 commands.delete(item.id);
953 if (commands.size === 0 && agentEnds.get(event.threadId) === commands) {
954 agentEnds.delete(event.threadId);
955 }
956 });
957 // Some providers report a command that failed as completed.
958 return Effect.andThen(
959 item.status === "completed" && !commandIndicatesFailure(item) ? Effect.void : done,
960 FiberMap.run(
961 agentReads,
962 item.id,
963 )(readThreadWatches(event.threadId).pipe(Effect.ensuring(done))),
964 );
965 }).pipe(Effect.catchCause(logFailure("pull request watch command stream failed", {}))),
966 );
967 // One feed per pull request: the host keeps one subscription per pull request and account.
968 const feeds = yield* FiberMap.make<string>();
969 const follow = Effect.gen(function* () {
970 const wanted = new Map(currentGroups.map((group) => [pullRequestOf(group), group]));
971 const stale = Array.from(feeds, ([pullRequest]) => pullRequest).filter(
972 (pullRequest) => !wanted.has(pullRequest),
973 );
974 yield* Effect.forEach(stale, (pullRequest) => FiberMap.remove(feeds, pullRequest), {
975 discard: true,
976 });
977 for (const [pullRequest, group] of wanted) {
978 // An ended feed restarts here, so a host that refused it is asked again each sweep.
979 yield* FiberMap.run(feeds, pullRequest, { onlyIfMissing: true })(
980 pullRequests.changes(referenceOf(group)).pipe(
981 // A review sends an event per comment; those landing during a read make one more.
982 Stream.buffer({ capacity: 1, strategy: "sliding" }),
983 Stream.runForEach(() => readOnChange(pullRequest)),
984 ),
985 );
986 }
987 });
988 // A watch's first read is its baseline, so it reads now: CI that finishes before the next
989 // sweep would otherwise be taken as old news and never wake the thread.
990 yield* forkParked(
991 Stream.runForEach(engine.streamDomainEvents, (event) => {
992 if (event.type !== "thread.pull-request-synced") return Effect.void;
993 const unread = visibleThreadPullRequests(event.payload.pullRequests ?? []).flatMap((link) =>
994 link.watch === undefined || lives.has(lifeKeyOf(event.threadId, link, link.watch))
995 ? []
996 : [threadPullRequestKeyOf(link)],
997 );
998 return Effect.forEach(new Set(unread), readOnChange, { discard: true });
999 }).pipe(Effect.catchCause(logFailure("pull request watch event stream failed", {}))),
1000 );
1001 yield* forkParked(
1002 sweep.pipe(
1003 Effect.andThen(follow),
1004 Effect.repeat(Schedule.spaced(`${SWEEP_MINUTES} minutes`)),
1005 Effect.asVoid,
1006 ),
1007 );
1008 });
1009
1010 return { start, sweep } satisfies PullRequestWatchReactor["Service"];
1011});
1012
1013export const layer = Layer.effect(PullRequestWatchReactor, make);