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