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

PullRequestWatchReactor.ts

1,009 lines38.1 KB

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