Open History to see the last commit
1import {
2 canonicalRepositoryKey,
3 sourceControlRepositorySelector,
4} from "@t3tools/shared/sourceControl";
5import {
6 CommandId,
7 type OrchestrationEvent,
8 type OrchestrationProjectShell,
9 type OrchestrationShellSnapshot,
10 type ThreadId,
11 type ThreadLinkedPullRequest,
12} from "@t3tools/contracts";
13import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
14import * as Cause from "effect/Cause";
15import * as Context from "effect/Context";
16import * as Crypto from "effect/Crypto";
17import * as Effect from "effect/Effect";
18import * as FileSystem from "effect/FileSystem";
19import * as Layer from "effect/Layer";
20import * as Option from "effect/Option";
21import * as Schedule from "effect/Schedule";
22import type * as Scope from "effect/Scope";
23import * as Stream from "effect/Stream";
24
25import * as GitManager from "../git/GitManager.ts";
26import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
27import * as PullRequestService from "../pullRequest/PullRequestService.ts";
28import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
29import { forkParked } from "../serverActivation.ts";
30import * as OrchestrationEngine from "./Services/OrchestrationEngine.ts";
31import * as ProjectionSnapshotQuery from "./Services/ProjectionSnapshotQuery.ts";
32
33export class ThreadPullRequestReactor extends Context.Service<
34 ThreadPullRequestReactor,
35 {
36 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
37 readonly drain: Effect.Effect<void>;
38 }
39>()("t3/orchestration/ThreadPullRequestReactor") {}
40
41function samePullRequest(
42 left: ThreadLinkedPullRequest | null | undefined,
43 right: ThreadLinkedPullRequest | null,
44): boolean {
45 if (left == null || right === null) return left == null && right === null;
46 return (
47 left.projectId === right.projectId &&
48 left.repository.toLowerCase() === right.repository.toLowerCase() &&
49 left.number === right.number &&
50 left.url === right.url
51 );
52}
53
54/** Startup lookups per settled thread before discovery gives up on it. */
55export const BACKFILL_ATTEMPTS = 5;
56
57interface RefreshRequest {
58 readonly threadId: ThreadId | null;
59 readonly refresh: boolean;
60 readonly backfill?: boolean;
61}
62
63export function pullRequestMatchesProject(
64 pullRequest: GitManager.GitBranchPullRequest,
65 project: OrchestrationProjectShell,
66): boolean {
67 return (
68 pullRequest.repositoryKey !== null &&
69 project.repositoryIdentity != null &&
70 canonicalRepositoryKey(pullRequest.repositoryKey) ===
71 canonicalRepositoryKey(project.repositoryIdentity.canonicalKey)
72 );
73}
74
75/**
76 * Read the shell state for a discovery or settlement sweep. A sweep for one
77 * thread reads that thread and the projects it names, not every thread. A
78 * sweep over all threads reads only unsettled threads, since both sweeps skip
79 * settled ones. Discovery's backfill does its own full read.
80 */
81export const readSweepSnapshot = (
82 snapshots: ProjectionSnapshotQuery.ProjectionSnapshotQueryShape,
83 threadId: ThreadId | null,
84): Effect.Effect<
85 Pick<OrchestrationShellSnapshot, "snapshotSequence" | "projects" | "threads">,
86 ProjectionRepositoryError
87> =>
88 threadId === null
89 ? snapshots.getShellSnapshot({ unsettledOnly: true })
90 : Effect.gen(function* () {
91 // Read the sequence first. The thread is then at least this new, so a
92 // command guarded by the sequence is rejected rather than missing a change.
93 const { snapshotSequence } = yield* snapshots.getSnapshotSequence();
94 const thread = yield* snapshots.getThreadShellById(threadId);
95 if (Option.isNone(thread)) return { snapshotSequence, projects: [], threads: [] };
96 // Settlement also checks the project a saved pull request names.
97 const reference = thread.value.linkedPullRequest ?? thread.value.branchPullRequest;
98 const projects = yield* snapshots.getProjectShells(
99 reference == null
100 ? [thread.value.projectId]
101 : [thread.value.projectId, reference.projectId],
102 );
103 return { snapshotSequence, projects, threads: [thread.value] };
104 });
105
106/** @public Service construction is part of the canonical Effect module API. */
107export const make = Effect.gen(function* () {
108 const engine = yield* OrchestrationEngine.OrchestrationEngineService;
109 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
110 const git = yield* GitManager.GitManager;
111 const pullRequests = yield* PullRequestService.PullRequestService;
112 const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
113 const crypto = yield* Crypto.Crypto;
114 const fileSystem = yield* FileSystem.FileSystem;
115 // Settled threads get one link discovery at startup. Failed lookups retry on
116 // the periodic pass a few times, then stop until the thread changes or the
117 // server restarts, so a missing or logged-out CLI cannot loop forever.
118 const pendingBackfill = new Map<ThreadId, number>();
119 const finishBackfill = (threads: ReadonlyArray<{ readonly id: ThreadId }>) => {
120 for (const thread of threads) pendingBackfill.delete(thread.id);
121 };
122 const failBackfill = (threads: ReadonlyArray<{ readonly id: ThreadId }>) => {
123 for (const thread of threads) {
124 const remaining = pendingBackfill.get(thread.id);
125 if (remaining === undefined) continue;
126 if (remaining <= 1) pendingBackfill.delete(thread.id);
127 else pendingBackfill.set(thread.id, remaining - 1);
128 }
129 };
130
131 const synchronize = Effect.fn("ThreadPullRequestReactor.synchronize")(function* (
132 request: RefreshRequest,
133 ) {
134 // Backfill looks up settled threads, so its passes read every thread.
135 const snapshot =
136 request.threadId === null && (request.backfill || pendingBackfill.size > 0)
137 ? yield* snapshots.getShellSnapshot()
138 : yield* readSweepSnapshot(snapshots, request.threadId);
139 const projects = new Map(snapshot.projects.map((project) => [project.id, project]));
140 if (request.backfill) {
141 for (const thread of snapshot.threads) {
142 if (
143 (thread.settledOverride === "settled" || thread.settledAt !== null) &&
144 thread.branchPullRequest == null
145 ) {
146 pendingBackfill.set(thread.id, BACKFILL_ATTEMPTS);
147 }
148 }
149 }
150 // A single-thread read only shows whether its own thread is gone. A thread
151 // with no branch has nothing to look up, and its entry would keep every
152 // periodic pass on the full read.
153 const branchThreadIds = new Set(
154 snapshot.threads.filter((thread) => thread.branch !== null).map((thread) => thread.id),
155 );
156 const checkedIds = request.threadId === null ? pendingBackfill.keys() : [request.threadId];
157 for (const threadId of checkedIds) {
158 if (!branchThreadIds.has(threadId)) pendingBackfill.delete(threadId);
159 }
160 const threads = snapshot.threads.filter(
161 (thread) =>
162 thread.archivedAt === null &&
163 ((thread.settledOverride !== "settled" && thread.settledAt === null) ||
164 request.threadId !== null ||
165 pendingBackfill.has(thread.id)) &&
166 (thread.branch !== null || thread.branchPullRequest != null),
167 );
168 const groups = Map.groupBy(threads, (thread) =>
169 JSON.stringify([thread.projectId, thread.worktreePath, thread.branch]),
170 );
171
172 yield* Effect.forEach(
173 groups.values(),
174 (group) =>
175 Effect.gen(function* () {
176 const first = group[0]!;
177 const snapshotProject = projects.get(first.projectId);
178 if (snapshotProject === undefined) return finishBackfill(group);
179 // A finished turn may have added the remote this PR lives on. A failed
180 // refresh resolves to null, so keep the snapshot's identity then.
181 const project = request.refresh
182 ? {
183 ...snapshotProject,
184 repositoryIdentity:
185 (yield* repositoryIdentities.resolve(snapshotProject.workspaceRoot, {
186 refresh: true,
187 })) ?? snapshotProject.repositoryIdentity,
188 }
189 : snapshotProject;
190 const repository = sourceControlRepositorySelector(project.repositoryIdentity);
191 if (first.branch !== null && repository === null) return finishBackfill(group);
192 const worktreeExists =
193 first.worktreePath !== null && (yield* fileSystem.exists(first.worktreePath));
194 const cwd =
195 worktreeExists && first.worktreePath !== null
196 ? first.worktreePath
197 : project.workspaceRoot;
198 const detected =
199 first.branch === null
200 ? null
201 : yield* git.branchPullRequest(
202 { cwd, branch: first.branch },
203 { refresh: request.refresh },
204 );
205 // A worktree can have different remotes, and the project identity
206 // can lag a remote edit. Do not attach its PR to the wrong repository.
207 if (detected !== null && !pullRequestMatchesProject(detected, project)) {
208 return finishBackfill(group);
209 }
210 const detectedReference =
211 detected !== null && repository !== null
212 ? {
213 projectId: project.id,
214 repository,
215 number: detected.number,
216 url: detected.url,
217 }
218 : null;
219
220 const plans = yield* Effect.forEach(group, (thread) =>
221 Effect.gen(function* () {
222 let branchPullRequest = detectedReference;
223 // Shared checkouts often return to the default branch after
224 // a merge. Keep that thread's terminal PR across the change.
225 if (
226 branchPullRequest === null &&
227 thread.branch !== null &&
228 thread.worktreePath === null &&
229 thread.branchPullRequest != null
230 ) {
231 const previous = yield* pullRequests.summary(thread.branchPullRequest, {
232 recoverTransientFailure: false,
233 });
234 if (previous.state === "merged" || previous.state === "closed") {
235 branchPullRequest = thread.branchPullRequest;
236 }
237 }
238
239 let replacement: ThreadLinkedPullRequest | undefined;
240 if (
241 thread.pullRequests.length === 0 &&
242 thread.linkedPullRequest != null &&
243 detected?.state === "open" &&
244 detectedReference !== null &&
245 !samePullRequest(thread.linkedPullRequest, detectedReference)
246 ) {
247 const linked = yield* pullRequests.summary(thread.linkedPullRequest, {
248 recoverTransientFailure: false,
249 });
250 if (linked.state === "merged" || linked.state === "closed") {
251 replacement = detectedReference;
252 }
253 }
254
255 if (
256 samePullRequest(thread.branchPullRequest, branchPullRequest) &&
257 replacement === undefined
258 ) {
259 pendingBackfill.delete(thread.id);
260 return null;
261 }
262 return { thread, branchPullRequest, replacement };
263 }).pipe(
264 Effect.catchCauseIf(
265 (cause) => !Cause.hasInterruptsOnly(cause),
266 (cause) =>
267 Effect.logWarning("thread pull request discovery failed", {
268 threadId: thread.id,
269 cause: Cause.pretty(cause),
270 }).pipe(
271 Effect.tap(() => Effect.sync(() => failBackfill([thread]))),
272 Effect.as(null),
273 ),
274 ),
275 ),
276 );
277 const updates = plans.filter((plan) => plan !== null);
278 if (updates.length === 0) return;
279
280 if (detected !== null && first.branch !== null) {
281 // Summary reads can outlast a remote edit. Recheck the branch and
282 // the project's primary remote before saving the group's links.
283 const current = yield* git.branchPullRequest({ cwd, branch: first.branch });
284 const currentIdentity = yield* repositoryIdentities.resolve(project.workspaceRoot, {
285 refresh: true,
286 });
287 if (
288 current === null ||
289 current.number !== detected.number ||
290 current.url !== detected.url ||
291 current.state !== detected.state ||
292 current.repositoryKey !== detected.repositoryKey ||
293 !pullRequestMatchesProject(current, {
294 ...project,
295 repositoryIdentity: currentIdentity,
296 })
297 ) {
298 return failBackfill(updates.map((update) => update.thread));
299 }
300 }
301
302 yield* Effect.forEach(
303 updates,
304 ({ thread, branchPullRequest, replacement }) =>
305 Effect.gen(function* () {
306 const uuid = yield* crypto.randomUUIDv4;
307 yield* engine.dispatch({
308 type: "thread.pull-request.sync",
309 commandId: CommandId.make(`server:thread-pull-request:${thread.id}:${uuid}`),
310 threadId: thread.id,
311 projectId: project.id,
312 snapshotSequence: snapshot.snapshotSequence,
313 expected: {
314 workspaceRoot: project.workspaceRoot,
315 branch: thread.branch,
316 worktreePath: thread.worktreePath,
317 linkedPullRequest: thread.linkedPullRequest ?? null,
318 branchPullRequest: thread.branchPullRequest ?? null,
319 },
320 branchPullRequest,
321 ...(replacement !== undefined ? { linkedPullRequest: replacement } : {}),
322 });
323 pendingBackfill.delete(thread.id);
324 }).pipe(
325 // The thread changed since the lookup. Its own events requeue it.
326 Effect.catchTags({
327 OrchestrationCommandInvariantError: () =>
328 Effect.sync(() => finishBackfill([thread])),
329 }),
330 Effect.catchCauseIf(
331 (cause) => !Cause.hasInterruptsOnly(cause),
332 (cause) =>
333 Effect.logWarning("thread pull request update failed", {
334 threadId: thread.id,
335 cause: Cause.pretty(cause),
336 }).pipe(Effect.tap(() => Effect.sync(() => failBackfill([thread])))),
337 ),
338 ),
339 { discard: true },
340 );
341 }).pipe(
342 Effect.catchCauseIf(
343 (cause) => !Cause.hasInterruptsOnly(cause),
344 (cause) =>
345 Effect.logWarning("thread branch pull request lookup failed", {
346 threadIds: group.map((thread) => thread.id),
347 cause: Cause.pretty(cause),
348 }).pipe(Effect.tap(() => Effect.sync(() => failBackfill(group)))),
349 ),
350 ),
351 // Wide enough that a sweep's GitHub branch lookups reach GitHubCli together and share one
352 // GraphQL document, instead of one `gh pr list` per branch.
353 { concurrency: 32, discard: true },
354 );
355 });
356
357 const worker = yield* makeDrainableWorker((request: RefreshRequest) =>
358 synchronize(request).pipe(
359 Effect.catchCauseIf(
360 (cause) => !Cause.hasInterruptsOnly(cause),
361 (cause) =>
362 Effect.logWarning("thread pull request refresh failed", {
363 cause: Cause.pretty(cause),
364 }),
365 ),
366 ),
367 );
368
369 const processEvent = (event: OrchestrationEvent) => {
370 switch (event.type) {
371 case "thread.created":
372 case "thread.unarchived":
373 return worker.enqueue({ threadId: event.payload.threadId, refresh: false });
374 case "thread.meta-updated":
375 if (
376 event.payload.branchPullRequest === undefined &&
377 (event.payload.branch !== undefined ||
378 event.payload.worktreePath !== undefined ||
379 event.payload.linkedPullRequest !== undefined)
380 ) {
381 return worker.enqueue({ threadId: event.payload.threadId, refresh: false });
382 }
383 break;
384 case "thread.session-set":
385 if (
386 event.payload.session.status !== "running" &&
387 event.payload.session.status !== "starting"
388 ) {
389 // Checkpoint completion forces the post-turn read. Session lifecycle
390 // events reuse it regardless of which event reaches this worker first.
391 return worker.enqueue({ threadId: event.payload.threadId, refresh: false });
392 }
393 break;
394 case "thread.turn-diff-completed":
395 case "thread.unsettled":
396 return worker.enqueue({ threadId: event.payload.threadId, refresh: true });
397 case "project.meta-updated":
398 if (event.payload.workspaceRoot !== undefined) {
399 return worker.enqueue({ threadId: null, refresh: false });
400 }
401 break;
402 }
403 return Effect.void;
404 };
405
406 const start = Effect.fn("ThreadPullRequestReactor.start")(function* () {
407 const events = yield* engine.subscribeDomainEvents;
408 yield* forkParked(Stream.runForEach(events, processEvent));
409 // Run without client demand. Saved branch lookups share GitManager's
410 // provider cache and retry backoff with status and automatic settlement.
411 yield* forkParked(
412 Effect.gen(function* () {
413 yield* worker.enqueue({ threadId: null, refresh: false, backfill: true });
414 yield* worker.drain;
415 yield* Effect.gen(function* () {
416 yield* worker.enqueue({ threadId: null, refresh: false });
417 yield* worker.drain;
418 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.delay("1 minute"));
419 }).pipe(Effect.asVoid),
420 );
421 });
422
423 return { start, drain: worker.drain } satisfies ThreadPullRequestReactor["Service"];
424});
425
426export const layer = Layer.effect(ThreadPullRequestReactor, make);