Open History to see the last commit
1import { siblingPullRequestUrl } from "@t3tools/shared/changeRequestUrl";
2import {
3 CommandId,
4 type PullRequestSummary,
5 type ThreadId,
6 type ThreadPullRequestKey,
7 type ThreadPullRequestLink,
8 type ThreadPullRequestSnapshot,
9 type ThreadPullRequestStack,
10} from "@t3tools/contracts";
11import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
12import {
13 threadPullRequestKeyOf,
14 normalizeThreadPullRequestKey,
15 threadPullRequestKeysEqual,
16 visibleThreadPullRequests,
17} from "@t3tools/shared/threadPullRequests";
18import * as Cause from "effect/Cause";
19import * as Clock from "effect/Clock";
20import * as Context from "effect/Context";
21import * as Crypto from "effect/Crypto";
22import * as DateTime from "effect/DateTime";
23import * as Effect from "effect/Effect";
24import * as Layer from "effect/Layer";
25import * as Schema from "effect/Schema";
26import * as Schedule from "effect/Schedule";
27import type * as Scope from "effect/Scope";
28import * as Semaphore from "effect/Semaphore";
29import * as Stream from "effect/Stream";
30
31import { PullRequestProviderError } from "../pullRequest/PullRequestProvider.ts";
32import * as PullRequestService from "../pullRequest/PullRequestService.ts";
33import { forkParked } from "../serverActivation.ts";
34import * as Orchestrator from "./Orchestrator.ts";
35import * as ProjectionStore from "./ProjectionStore.ts";
36import { isTerminalRunStatus } from "./ThreadManagementService.ts";
37
38const SLOW_SYNC_INTERVAL_MS = 15 * 60 * 1_000;
39/** Shell commands that can merge or close a pull request without a merge notification. */
40const PULL_REQUEST_CLOSE_COMMAND = /\b(?:gh\s+pr|glab\s+mr)\s+(?:merge|close)\b/u;
41
42const isPullRequestProviderError = Schema.is(PullRequestProviderError);
43
44type SnapshotFields = Omit<ThreadPullRequestSnapshot, "syncedAt">;
45
46interface LinkEntry {
47 readonly thread: ProjectionStore.ProjectionThreadPullRequests;
48 readonly link: ThreadPullRequestLink;
49}
50
51function snapshotFieldsOf(summary: PullRequestSummary): SnapshotFields {
52 return {
53 state: summary.state,
54 title: summary.title,
55 headBranch: summary.headBranch,
56 baseBranch: summary.baseBranch,
57 isDraft: summary.isDraft ?? false,
58 updatedAt: summary.updatedAt,
59 closedAt: summary.closedAt ?? null,
60 mergedAt: summary.mergedAt ?? null,
61 ...(summary.author === undefined ? {} : { author: summary.author }),
62 ...(summary.additions === undefined ? {} : { additions: summary.additions }),
63 ...(summary.deletions === undefined ? {} : { deletions: summary.deletions }),
64 ...(summary.changedFiles === undefined ? {} : { changedFiles: summary.changedFiles }),
65 ...(summary.reviewDecision === undefined ? {} : { reviewDecision: summary.reviewDecision }),
66 ...(summary.checksState === undefined ? {} : { checksState: summary.checksState }),
67 ...(summary.mergeability === undefined ? {} : { mergeability: summary.mergeability }),
68 };
69}
70
71function snapshotFieldsEqual(left: SnapshotFields, right: SnapshotFields): boolean {
72 return (
73 left.state === right.state &&
74 left.title === right.title &&
75 left.headBranch === right.headBranch &&
76 left.baseBranch === right.baseBranch &&
77 left.isDraft === right.isDraft &&
78 left.updatedAt === right.updatedAt &&
79 (left.closedAt ?? null) === (right.closedAt ?? null) &&
80 (left.mergedAt ?? null) === (right.mergedAt ?? null) &&
81 (left.author?.login ?? null) === (right.author?.login ?? null) &&
82 (left.author?.avatarUrl ?? null) === (right.author?.avatarUrl ?? null) &&
83 left.additions === right.additions &&
84 left.deletions === right.deletions &&
85 left.changedFiles === right.changedFiles &&
86 (left.reviewDecision ?? null) === (right.reviewDecision ?? null) &&
87 (left.checksState ?? null) === (right.checksState ?? null) &&
88 left.mergeability === right.mergeability
89 );
90}
91
92function stacksEqual(
93 left: ThreadPullRequestStack | null,
94 right: ThreadPullRequestStack | null,
95): boolean {
96 if (left === null || right === null) return left === right;
97 return (
98 left.kind === right.kind &&
99 left.id === right.id &&
100 left.number === right.number &&
101 left.url === right.url &&
102 left.base === right.base &&
103 left.layers.length === right.layers.length &&
104 left.layers.every((layer, index) => {
105 const other = right.layers[index]!;
106 return (
107 layer.number === other.number &&
108 layer.headBranch === other.headBranch &&
109 layer.state === other.state
110 );
111 })
112 );
113}
114
115function skipReason(cause: Cause.Cause<unknown>): string {
116 const error = Cause.squash(cause);
117 return error instanceof Error ? error.message : String(error);
118}
119
120/** When a host read failed because the host is rate limited, the time that pause ends. */
121function rateLimitRetryAt(cause: Cause.Cause<unknown>): number | undefined {
122 let error: unknown = Cause.squash(cause);
123 while (error instanceof Error) {
124 if (isPullRequestProviderError(error) && error.reason === "rate-limited") return error.retryAt;
125 error = error.cause;
126 }
127 return undefined;
128}
129
130function isUnsettled(thread: ProjectionStore.ProjectionThreadPullRequests): boolean {
131 return thread.settledOverride !== "settled" && thread.settledAt === null;
132}
133
134/**
135 * Keeps every thread ↔ pull request link's host snapshot current. One sweep a minute reads
136 * only the active threads that have links, groups visible links by pull request so the host
137 * is asked once per PR no matter how many threads share it, and writes back only what
138 * changed. Native stacks the host reports are auto-linked to the thread as `source: "stack"`.
139 */
140export class PullRequestSyncReactor extends Context.Service<
141 PullRequestSyncReactor,
142 {
143 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
144 readonly drain: Effect.Effect<void>;
145 /**
146 * Force the next sweep to re-read this pull request, even when its snapshot is terminal.
147 * While its host is rate limited, the read waits for the first sweep after the pause.
148 */
149 readonly requestSync: (key: ThreadPullRequestKey) => Effect.Effect<void>;
150 }
151>()("t3/orchestration-v2/PullRequestSyncReactor") {}
152
153/** @public Service construction is part of the canonical Effect module API. */
154export const make = Effect.gen(function* () {
155 const engine = yield* Orchestrator.OrchestratorV2;
156 const projections = yield* ProjectionStore.ProjectionStoreV2;
157 const pullRequests = yield* PullRequestService.PullRequestService;
158 const crypto = yield* Crypto.Crypto;
159
160 const lastSyncedAt = new Map<string, number>();
161 const requested = new Map<string, number>();
162 let requestGeneration = 0;
163 // Requested keys wait in `requested` for one queued sweep, so a burst of links (an agent
164 // linking dozens of pull requests) is read together and shares the summary batches.
165 let requestedSweepQueued = false;
166 const retryStacks = new Set<string>();
167 // Rate limit pauses by project and host, since each project reads with its own credential.
168 // A paused host refuses every read without asking it, so the sweep leaves its pull requests
169 // due until the pause ends rather than failing each of them every minute.
170 const pausedUntil = new Map<string, number>();
171
172 const isDue = (key: string, entries: ReadonlyArray<LinkEntry>, nowMs: number): boolean => {
173 if (requested.has(key) || retryStacks.has(key)) return true;
174 if (entries.some((entry) => entry.link.snapshot === null)) return true;
175 // Settled threads stop watching their pull requests. Unsettling one makes its links due on
176 // the next sweep, since the cadence clock below kept running while it was settled.
177 const active = entries.filter((entry) => isUnsettled(entry.thread));
178 if (active.every((entry) => entry.link.snapshot?.state === "merged")) return false;
179 if (active.some((entry) => entry.link.snapshot?.state === "open")) return true;
180 // Closed requests can reopen on the host.
181 const last = lastSyncedAt.get(key);
182 return last === undefined || nowMs - last >= SLOW_SYNC_INTERVAL_MS;
183 };
184
185 const logSkipped =
186 (message: string, fields: Record<string, unknown>) =>
187 <E>(cause: Cause.Cause<E>): Effect.Effect<void, E> =>
188 Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.logWarning(message, fields);
189
190 /** `requested` reads only keys asked for through `requestSync`; `all` is the periodic pass. */
191 const sweep = Effect.fn("PullRequestSyncReactor.sweep")(function* (scope: "all" | "requested") {
192 const threads = yield* projections.getThreadsWithPullRequests();
193 const now = yield* DateTime.now;
194 const nowMs = DateTime.toEpochMillis(now);
195 const nowIso = DateTime.formatIso(now);
196
197 const groups = new Map<string, Array<LinkEntry>>();
198 for (const thread of threads) {
199 for (const link of visibleThreadPullRequests(thread.pullRequests ?? [])) {
200 const key = threadPullRequestKeyOf(link);
201 const entries = groups.get(key) ?? [];
202 entries.push({ thread, link });
203 groups.set(key, entries);
204 }
205 }
206
207 for (const key of lastSyncedAt.keys()) if (!groups.has(key)) lastSyncedAt.delete(key);
208 for (const key of retryStacks) if (!groups.has(key)) retryStacks.delete(key);
209 for (const key of requested.keys()) if (!groups.has(key)) requested.delete(key);
210
211 // Layers auto-linked this sweep, so two links of one thread that share a
212 // stack do not both try to add the same sibling.
213 const linkedThisSweep = new Set<string>();
214 const persistence = yield* Semaphore.make(1);
215
216 const syncEntry = Effect.fn("PullRequestSyncReactor.syncEntry")(function* (
217 entry: LinkEntry,
218 fields: SnapshotFields,
219 fetchedStack: { readonly stack: ThreadPullRequestStack | null } | null,
220 ) {
221 const { thread, link } = entry;
222 const nextStack = fetchedStack === null ? link.stack : fetchedStack.stack;
223 const changed =
224 link.snapshot === null ||
225 !snapshotFieldsEqual(link.snapshot, fields) ||
226 !stacksEqual(link.stack, nextStack);
227 // Persist discovered siblings before a terminal snapshot can trigger settlement. A settled
228 // thread that shares this pull request with an active one takes the fresh snapshot, but
229 // gains no links.
230 for (const layer of isUnsettled(thread) ? (fetchedStack?.stack?.layers ?? []) : []) {
231 const layerKey = {
232 host: normalizeThreadPullRequestKey(link).host,
233 repository: link.repository,
234 number: layer.number,
235 };
236 const dedupeKey = `${thread.id}:${threadPullRequestKeyOf(layerKey)}`;
237 if (linkedThisSweep.has(dedupeKey)) continue;
238 // Tombstones count as present: a dismissed layer is never re-added.
239 if (
240 (thread.pullRequests ?? []).some((existing) =>
241 threadPullRequestKeysEqual(existing, layerKey),
242 )
243 ) {
244 continue;
245 }
246 const url = siblingPullRequestUrl(link.url, layer.number);
247 if (url === null) continue;
248 const uuid = yield* crypto.randomUUIDv4;
249 yield* engine.dispatch({
250 type: "thread.pull-request.link",
251 commandId: CommandId.make(`server:pr-stack-link:${thread.id}:${uuid}`),
252 threadId: thread.id,
253 ...layerKey,
254 url,
255 source: "stack",
256 });
257 linkedThisSweep.add(dedupeKey);
258 }
259 if (changed) {
260 const uuid = yield* crypto.randomUUIDv4;
261 yield* engine.dispatch({
262 type: "thread.pull-request-link.sync",
263 commandId: CommandId.make(`server:pr-sync:${thread.id}:${uuid}`),
264 threadId: thread.id,
265 host: normalizeThreadPullRequestKey(link).host,
266 repository: link.repository,
267 number: link.number,
268 snapshot: { ...fields, syncedAt: nowIso },
269 stack: nextStack,
270 });
271 }
272 });
273
274 const syncGroup = Effect.fn("PullRequestSyncReactor.syncGroup")(function* (
275 key: string,
276 entries: ReadonlyArray<LinkEntry>,
277 ) {
278 const first = entries[0]!;
279 const ref = {
280 projectId: first.thread.projectId,
281 host: normalizeThreadPullRequestKey(first.link).host,
282 repository: first.link.repository,
283 number: first.link.number,
284 };
285 const generation = requested.get(key);
286 if (generation !== undefined) yield* pullRequests.invalidate({ reference: ref });
287 const summary = yield* pullRequests.summary(ref, { recoverTransientFailure: false });
288 const fields = snapshotFieldsOf(summary);
289 const needsStack =
290 generation !== undefined ||
291 retryStacks.has(key) ||
292 entries.some(
293 (entry) =>
294 entry.link.snapshot === null ||
295 !snapshotFieldsEqual(entry.link.snapshot, fields) ||
296 (summary.stack !== undefined &&
297 (entry.link.stack?.number ?? null) !== (summary.stack?.number ?? null)),
298 );
299 // A summary that says the pull request is in no stack, for links that hold none, already
300 // answers what the stack read would.
301 const knownUnstacked =
302 summary.stack === null && entries.every((entry) => entry.link.stack === null);
303 const fetchedStack = !needsStack
304 ? null
305 : knownUnstacked
306 ? { stack: null }
307 : yield* pullRequests.stack(ref, { includeDetails: false }).pipe(
308 Effect.map((stack) => ({
309 stack: stack === null ? null : ({ kind: "native", ...stack } as const),
310 })),
311 Effect.catchCauseIf(
312 (cause) => !Cause.hasInterruptsOnly(cause),
313 (cause) =>
314 rateLimitRetryAt(cause) !== undefined
315 ? // The sweep records the pause and holds the host's other reads until it ends.
316 Effect.sync(() => retryStacks.add(key)).pipe(
317 Effect.andThen(Effect.failCause(cause)),
318 )
319 : Effect.logWarning("pull request stack lookup failed", {
320 key,
321 }).pipe(Effect.as(null)),
322 ),
323 );
324 if (needsStack) {
325 if (fetchedStack === null) {
326 retryStacks.add(key);
327 return;
328 }
329 retryStacks.delete(key);
330 }
331 // The host answered, so the cadence clock ticks even if a dispatch below is rejected.
332 lastSyncedAt.set(key, nowMs);
333 // A refresh requested while the host read was in flight belongs to the next sweep.
334 if (requested.get(key) === generation) requested.delete(key);
335 yield* Effect.forEach(
336 entries,
337 (entry) =>
338 syncEntry(entry, fields, fetchedStack).pipe(
339 persistence.withPermits(1),
340 Effect.catchCause((cause) => {
341 if (!Cause.hasInterruptsOnly(cause)) retryStacks.add(key);
342 return logSkipped("pull request sync skipped", { threadId: entry.thread.id, key })(
343 cause,
344 );
345 }),
346 ),
347 { discard: true },
348 );
349 });
350
351 // Failed host reads by reason: how many, and the first key that failed that way.
352 const skips = new Map<string, { count: number; readonly key: string }>();
353 const readGroup = (key: string, entries: ReadonlyArray<LinkEntry>, pauseKey: string) =>
354 syncGroup(key, entries).pipe(
355 Effect.catchCause((cause) => {
356 if (Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause);
357 const retryAt = rateLimitRetryAt(cause);
358 if (retryAt !== undefined) {
359 pausedUntil.set(pauseKey, Math.max(retryAt, pausedUntil.get(pauseKey) ?? 0));
360 }
361 const reason = skipReason(cause);
362 const skip = skips.get(reason);
363 if (skip === undefined) skips.set(reason, { count: 1, key });
364 else skip.count += 1;
365 return Effect.void;
366 }),
367 );
368 yield* Effect.forEach(
369 groups,
370 ([key, entries]) => {
371 if (!((scope === "all" || requested.has(key)) && isDue(key, entries, nowMs))) {
372 return Effect.void;
373 }
374 const first = entries[0]!;
375 const pauseKey = `${first.thread.projectId}\0${normalizeThreadPullRequestKey(first.link).host}`;
376 // Checked against the clock as each read starts, so a pause found earlier in this sweep
377 // holds the rest, and one that ends during the sweep lets the rest through.
378 return Clock.currentTimeMillis.pipe(
379 Effect.flatMap((startedAtMs) =>
380 (pausedUntil.get(pauseKey) ?? 0) > startedAtMs
381 ? Effect.void
382 : readGroup(key, entries, pauseKey),
383 ),
384 );
385 },
386 // As wide as one batched summary read, so the sweep's reads on a host arrive together and
387 // GitHub answers them in one request rather than one `gh pr view` apiece.
388 { concurrency: 25, discard: true },
389 );
390 // A host failure such as a signed-out CLI fails every due pull request the same way, so a
391 // sweep reports one line per reason rather than one per pull request.
392 for (const [reason, { count, key }] of skips) {
393 yield* Effect.logWarning("pull request sync skipped", { count, key, reason });
394 }
395 });
396
397 const worker = yield* makeDrainableWorker((scope: "all" | "requested") =>
398 Effect.suspend(() => {
399 // Requests from here on queue another sweep; the ones already recorded are read by this.
400 if (scope === "requested") requestedSweepQueued = false;
401 return sweep(scope);
402 }).pipe(Effect.catchCause(logSkipped("pull request sync sweep failed", {}))),
403 );
404
405 // Threads whose current run ran a merge or close command, until that run ends.
406 const closeCommandThreads = new Set<ThreadId>();
407 const refreshOpenLinks = (threadId: ThreadId) =>
408 projections.getThreadsWithPullRequests(threadId).pipe(
409 Effect.flatMap((threads) =>
410 Effect.forEach(
411 threads.flatMap((thread) =>
412 visibleThreadPullRequests(thread.pullRequests ?? []).filter(
413 (link) => link.snapshot?.state === "open",
414 ),
415 ),
416 requestSync,
417 { discard: true },
418 ),
419 ),
420 Effect.catchCause(logSkipped("pull request refresh after run skipped", { threadId })),
421 );
422
423 const start: PullRequestSyncReactor["Service"]["start"] = Effect.fn(
424 "PullRequestSyncReactor.start",
425 )(function* () {
426 const events = engine.streamDomainEvents;
427 // A client reading a pull request can see it merge or close before the next sweep does.
428 const stateChanges = yield* pullRequests.subscribeStateChanges;
429 yield* forkParked(
430 Stream.runForEach(stateChanges, requestSync).pipe(
431 Effect.catchCause(logSkipped("pull request state change stream failed", {})),
432 ),
433 );
434 yield* forkParked(
435 Stream.runForEach(events, (event) => {
436 switch (event.type) {
437 case "thread.pull-request-synced":
438 return Effect.forEach(
439 visibleThreadPullRequests(event.payload.pullRequests ?? []).filter(
440 (link) => link.snapshot === null,
441 ),
442 requestSync,
443 { discard: true },
444 );
445 // An agent can merge or close its pull request from a shell (`gh pr merge`), which
446 // sends no merge notification. When a run that ran such a command ends, read the
447 // thread's open links fresh, so settlement does not wait for the next sweep and the
448 // cached summary. Other runs add no host reads.
449 case "turn-item.updated":
450 if (
451 event.payload.type === "command_execution" &&
452 PULL_REQUEST_CLOSE_COMMAND.test(event.payload.input)
453 ) {
454 closeCommandThreads.add(event.threadId);
455 }
456 return Effect.void;
457 case "run.updated":
458 return isTerminalRunStatus(event.payload.status) &&
459 closeCommandThreads.delete(event.threadId)
460 ? refreshOpenLinks(event.threadId)
461 : Effect.void;
462 default:
463 return Effect.void;
464 }
465 }).pipe(Effect.catchCause(logSkipped("pull request sync event stream failed", {}))),
466 );
467 yield* forkParked(
468 Effect.gen(function* () {
469 yield* worker.enqueue("all");
470 yield* worker.drain;
471 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
472 );
473 });
474
475 const requestSync: PullRequestSyncReactor["Service"]["requestSync"] = (key) =>
476 Effect.suspend(() => {
477 requested.set(threadPullRequestKeyOf(key), ++requestGeneration);
478 if (requestedSweepQueued) return Effect.void;
479 requestedSweepQueued = true;
480 return worker.enqueue("requested");
481 });
482
483 return { start, drain: worker.drain, requestSync } satisfies PullRequestSyncReactor["Service"];
484});
485
486export const layer = Layer.effect(PullRequestSyncReactor, make);