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