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

ThreadPullRequestService.ts

481 lines19.3 KB

1import {
2 CommandId,
3 type OrchestrationProjectShell,
4 type OrchestrationV2DomainEvent,
5 type OrchestrationV2ThreadShell,
6 type PullRequestSummary,
7 type ThreadId,
8 type ThreadLinkedPullRequest,
9} from "@t3tools/contracts";
10import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
11import * as Cause from "effect/Cause";
12import * as Context from "effect/Context";
13import * as SecureRandom from "effect/crypto/SecureRandom";
14import * as DateTime from "effect/DateTime";
15import * as Effect from "effect/Effect";
16import * as FileSystem from "effect/FileSystem";
17import * as Option from "effect/Option";
18import * as Path from "effect/Path";
19import * as Queue from "effect/Queue";
20import * as Schedule from "effect/Schedule";
21import type * as Scope from "effect/Scope";
22import * as Stream from "effect/Stream";
23​
24import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
25import * as GitManager from "../git/GitManager.ts";
26import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
27import * as ProjectStore from "./ProjectStore.ts";
28import * as PullRequestService from "../pullRequest/PullRequestService.ts";
29import { makeLinkedThreadsChangeDetector } from "../pullRequest/linkedThreads.ts";
30import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
31import { forkParked } from "../serverActivation.ts";
32import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
33import * as Orchestrator from "./Orchestrator.ts";
34​
35class ThreadPullRequestServiceV2 extends Context.Service<
36 ThreadPullRequestServiceV2,
37 {
38 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
39 readonly drain: Effect.Effect<void>;
40 }
41>()("t3/orchestration-v2/ThreadPullRequestService/ThreadPullRequestServiceV2") {}
42​
43function samePullRequest(
44 left: ThreadLinkedPullRequest | null | undefined,
45 right: ThreadLinkedPullRequest | null,
46): boolean {
47 if (left == null || right === null) return left == null && right === null;
48 return (
49 left.projectId === right.projectId &&
50 left.repository.toLowerCase() === right.repository.toLowerCase() &&
51 left.number === right.number &&
52 left.url === right.url
53 );
55​
56function pullRequestPredatesThread(
57 pullRequest: Pick<PullRequestSummary, "state" | "closedAt" | "mergedAt">,
58 createdAt: DateTime.Utc,
59): boolean {
60 const terminalAt =
61 pullRequest.state === "merged"
62 ? pullRequest.mergedAt
63 : pullRequest.state === "closed"
64 ? pullRequest.closedAt
65 : null;
66 return terminalAt != null && Date.parse(terminalAt) < DateTime.toEpochMillis(createdAt);
68​
69function pullRequestMatchesProject(
70 pullRequest: GitManager.GitBranchPullRequest,
71 project: OrchestrationProjectShell,
72): boolean {
73 return (
74 pullRequest.repositoryKey !== null &&
75 project.repositoryIdentity != null &&
76 sourceControlDefinitions.canonicalRepositoryKey(pullRequest.repositoryKey) ===
77 sourceControlDefinitions.canonicalRepositoryKey(project.repositoryIdentity.canonicalKey)
78 );
80​
81const resolveProjectForPullRequestDiscovery = Effect.fn(
82 "ThreadPullRequestServiceV2.resolveProject",
83)(function* (
84 project: OrchestrationProjectShell,
85 repositoryIdentities: RepositoryIdentityResolver.RepositoryIdentityResolver["Service"],
86 options?: { readonly refresh?: boolean },
87) {
88 // Post-turn discovery refreshes 15-minute identity caches because agents may add remotes.
89 const repositoryIdentity = yield* repositoryIdentities.resolve(project.workspaceRoot, {
90 refresh: options?.refresh ?? false,
91 });
92 return {
93 project: { ...project, repositoryIdentity },
94 repository: sourceControlDefinitions.repositorySelector(repositoryIdentity),
95 };
96});
97​
98export function projectWorkspaceMatchesSnapshot(
99 currentProject: Option.Option<Pick<OrchestrationProjectShell, "workspaceRoot">>,
100 expectedWorkspaceRoot: string,
101): boolean {
102 return (
103 Option.isSome(currentProject) && currentProject.value.workspaceRoot === expectedWorkspaceRoot
104 );
106​
107const BACKFILL_ATTEMPTS = 5;
108​
109interface RefreshRequest {
110 readonly threadId: ThreadId | null;
111 readonly refresh: boolean;
112 readonly backfill?: boolean;
114​
115export const make = Effect.gen(function* () {
116 const orchestrator = yield* Orchestrator.OrchestratorV2;
117 const projectStore = yield* ProjectStore.ProjectStoreV2;
118 const git = yield* GitManager.GitManager;
119 const pullRequests = yield* PullRequestService.PullRequestService;
120 const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
121 const random = yield* SecureRandom.SecureRandom;
122 const fileSystem = yield* FileSystem.FileSystem;
123 const path = yield* Path.Path;
124 const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
125 const pendingBackfill = new Map<ThreadId, number>();
126​
127 const finishBackfill = (threads: ReadonlyArray<Pick<OrchestrationV2ThreadShell, "id">>) => {
128 for (const thread of threads) pendingBackfill.delete(thread.id);
129 };
130 const failBackfill = (threads: ReadonlyArray<Pick<OrchestrationV2ThreadShell, "id">>) => {
131 for (const thread of threads) {
132 const remaining = pendingBackfill.get(thread.id);
133 if (remaining === undefined) continue;
134 if (remaining <= 1) pendingBackfill.delete(thread.id);
135 else pendingBackfill.set(thread.id, remaining - 1);
136 }
137 };
138​
139 const readThreadSnapshot = ({ threadId, backfill }: RefreshRequest) =>
140 orchestrator.getPullRequestSnapshot(
141 threadId === null ? { unsettledOnly: !(backfill || pendingBackfill.size > 0) } : { threadId },
142 );
143​
144 const synchronize = Effect.fn("ThreadPullRequestServiceV2.synchronize")(function* (
145 request: RefreshRequest,
146 ) {
147 const [threadSnapshot, projectShells] = yield* Effect.all([
148 readThreadSnapshot(request),
149 projectStore.listShells(),
150 ]);
151 // Subagent children refresh after their own runs; sweeping them costs a lookup each per minute.
152 const snapshotThreads =
153 request.threadId === null
154 ? threadSnapshot.threads.filter(
155 (thread) => thread.lineage.relationshipToParent !== "subagent",
156 )
157 : threadSnapshot.threads;
158 const projects = new Map(projectShells.map((project) => [project.id, project]));
159 if (request.backfill) {
160 for (const thread of snapshotThreads) {
161 if (
162 (thread.settledOverride === "settled" || thread.settledAt !== null) &&
163 thread.branchPullRequest == null
164 ) {
165 pendingBackfill.set(thread.id, BACKFILL_ATTEMPTS);
166 }
167 }
168 }
169 const visibleThreadIds = new Set(
170 snapshotThreads.filter((thread) => thread.branch !== null).map((thread) => thread.id),
171 );
172 const checkedIds = request.threadId === null ? [...pendingBackfill.keys()] : [request.threadId];
173 for (const threadId of checkedIds) {
174 if (!visibleThreadIds.has(threadId)) pendingBackfill.delete(threadId);
175 }
176 const threads = snapshotThreads.filter(
177 (thread) =>
178 thread.archivedAt === null &&
179 ((thread.settledOverride !== "settled" && thread.settledAt === null) ||
180 request.threadId !== null ||
181 pendingBackfill.has(thread.id)) &&
182 (thread.branch !== null || thread.branchPullRequest != null),
183 );
184 const groups = Map.groupBy(threads, (thread) =>
185 JSON.stringify([thread.projectId, thread.worktreePath, thread.branch]),
186 );
187​
188 yield* Effect.forEach(
189 groups.values(),
190 (group) =>
191 Effect.gen(function* () {
192 const first = group[0]!;
193 const project = projects.get(first.projectId);
194 if (project === undefined) return finishBackfill(group);
195 const { project: resolvedProject, repository } =
196 yield* resolveProjectForPullRequestDiscovery(project, repositoryIdentities, {
197 refresh: request.refresh,
198 });
199 if (first.branch !== null && repository === null) return finishBackfill(group);
200 // A worktree folder can outlive its .git, and git there fails with not_a_repository.
201 // An unreadable .git keeps the worktree rather than failing the whole group.
202 const cwd =
203 first.worktreePath !== null &&
204 (yield* fileSystem
205 .exists(path.join(first.worktreePath, ".git"))
206 .pipe(Effect.orElseSucceed(() => true)))
207 ? first.worktreePath
208 : project.workspaceRoot;
209 // A detected PR is confirmed against fresh git state before it is saved.
210 const detected =
211 first.branch === null
212 ? null
213 : yield* git.branchPullRequest(
214 { cwd, branch: first.branch },
215 { refresh: request.refresh, confirmTerminal: false },
216 );
217 if (detected !== null && !pullRequestMatchesProject(detected, resolvedProject)) {
218 return finishBackfill(group);
219 }
220 const detectedReference =
221 detected !== null && repository !== null
222 ? {
223 projectId: project.id,
224 repository,
225 number: detected.number,
226 url: detected.url,
227 }
228 : null;
229​
230 // Only a new association is refused: a thread keeps a PR it already saved, and a PR the
231 // user checked out stays with the threads made for it, however long ago it closed.
232 const isHistoricalFor = (thread: (typeof group)[number]) =>
233 detected !== null &&
234 pullRequestPredatesThread(detected, thread.createdAt) &&
235 !samePullRequest(thread.branchPullRequest, detectedReference);
236 const dropsHistorical =
237 detected !== null &&
238 first.branch !== null &&
239 group.some(isHistoricalFor) &&
240 !(yield* git.checkedOutPullRequest({ cwd, branch: first.branch, url: detected.url }));
241​
242 const plans = yield* Effect.forEach(group, (thread) =>
243 Effect.gen(function* () {
244 let branchPullRequest =
245 dropsHistorical && isHistoricalFor(thread) ? null : detectedReference;
246 if (
247 branchPullRequest === null &&
248 thread.branch !== null &&
249 thread.worktreePath === null &&
250 thread.branchPullRequest != null
251 ) {
252 const previous = yield* pullRequests.summary(thread.branchPullRequest, {
253 recoverTransientFailure: false,
254 });
255 if (
256 previous.headBranch === thread.branch &&
257 (previous.state === "merged" || previous.state === "closed")
258 ) {
259 branchPullRequest = thread.branchPullRequest;
260 }
261 }
262​
263 let replacement: ThreadLinkedPullRequest | undefined;
264 if (
265 (thread.pullRequests ?? []).length === 0 &&
266 thread.linkedPullRequest != null &&
267 detected?.state === "open" &&
268 detectedReference !== null &&
269 !samePullRequest(thread.linkedPullRequest, detectedReference)
270 ) {
271 const linked = yield* pullRequests.summary(thread.linkedPullRequest, {
272 recoverTransientFailure: false,
273 });
274 if (linked.state === "merged" || linked.state === "closed") {
275 replacement = detectedReference;
276 }
277 }
278 if (
279 samePullRequest(thread.branchPullRequest, branchPullRequest) &&
280 replacement === undefined
281 ) {
282 pendingBackfill.delete(thread.id);
283 return null;
284 }
285 return { thread, branchPullRequest, replacement };
286 }).pipe(
287 Effect.catchCauseIf(
288 (cause) => !Cause.hasInterruptsOnly(cause),
289 (cause) =>
290 Effect.logWarning("thread pull request discovery failed", {
291 threadId: thread.id,
292 cause: Cause.pretty(cause),
293 }).pipe(
294 Effect.tap(() => Effect.sync(() => failBackfill([thread]))),
295 Effect.as(null),
296 ),
297 ),
298 ),
299 );
300 const updates = plans.filter((plan) => plan !== null);
301 if (updates.length === 0) return;
302​
303 if (detected !== null && first.branch !== null) {
304 const current = yield* git.branchPullRequest(
305 { cwd, branch: first.branch },
306 { freshGitState: true },
307 );
308 const currentIdentity = yield* repositoryIdentities.resolve(project.workspaceRoot, {
309 refresh: true,
310 });
311 if (
312 current === null ||
313 current.number !== detected.number ||
314 current.url !== detected.url ||
315 current.state !== detected.state ||
316 current.repositoryKey !== detected.repositoryKey ||
317 !pullRequestMatchesProject(current, {
318 ...project,
319 repositoryIdentity: currentIdentity,
320 })
321 ) {
322 return failBackfill(updates.map((update) => update.thread));
323 }
324 }
325​
326 yield* Effect.forEach(
327 updates,
328 ({ thread, branchPullRequest, replacement }) =>
329 Effect.gen(function* () {
330 // Discovery yields to network I/O; recheck the project at commit to reject deleted projects or changed checkouts.
331 const currentProject = yield* projectStore.getShell(project.id);
332 if (!projectWorkspaceMatchesSnapshot(currentProject, project.workspaceRoot)) {
333 return failBackfill([thread]);
334 }
335 const uuid = yield* random.uuidV4();
336 yield* orchestrator.dispatch({
337 type: "thread.pull-request.sync",
338 commandId: CommandId.make(`server:thread-pull-request:${thread.id}:${uuid}`),
339 threadId: thread.id,
340 projectId: project.id,
341 snapshotSequence: threadSnapshot.snapshotSequence,
342 expected: {
343 workspaceRoot: project.workspaceRoot,
344 branch: thread.branch,
345 worktreePath: thread.worktreePath,
346 linkedPullRequest: thread.linkedPullRequest ?? null,
347 branchPullRequest: thread.branchPullRequest ?? null,
348 },
349 branchPullRequest,
350 ...(replacement === undefined ? {} : { linkedPullRequest: replacement }),
351 });
352 pendingBackfill.delete(thread.id);
353 }).pipe(
354 Effect.catchCauseIf(
355 (cause) => !Cause.hasInterruptsOnly(cause),
356 (cause) =>
357 Effect.logWarning("thread pull request update failed", {
358 threadId: thread.id,
359 cause: Cause.pretty(cause),
360 }).pipe(Effect.tap(() => Effect.sync(() => failBackfill([thread])))),
361 ),
362 ),
363 { discard: true },
364 );
365 }).pipe(
366 Effect.catchCauseIf(
367 (cause) => !Cause.hasInterruptsOnly(cause),
368 (cause) =>
369 Effect.logWarning("thread branch pull request lookup failed", {
370 threadIds: group.map((thread) => thread.id),
371 cause: Cause.pretty(cause),
372 }).pipe(Effect.tap(() => Effect.sync(() => failBackfill(group)))),
373 ),
374 ),
375 // Batch concurrent branch lookups into one GitHub GraphQL document.
376 { concurrency: 32, discard: true },
377 );
378 });
379​
380 // At most one queued request per thread, so a turn end's events share one lookup.
381 // A request after that lookup starts queues another, so later host changes are still read.
382 const queuedThreadRequests = new Map<ThreadId, { threadId: ThreadId; refresh: boolean }>();
383​
384 const worker = yield* makeDrainableWorker((request: RefreshRequest) =>
385 Effect.suspend(() => {
386 if (request.threadId !== null) queuedThreadRequests.delete(request.threadId);
387 return synchronize(request);
388 }).pipe(
389 Effect.provideService(GitVcsDriver.BackgroundGitWork, true),
390 Effect.catchCauseIf(
391 (cause) => !Cause.hasInterruptsOnly(cause),
392 (cause) =>
393 Effect.logWarning("thread pull request refresh failed", {
394 cause: Cause.pretty(cause),
395 }),
396 ),
397 ),
398 );
399​
400 const enqueueThread = (threadId: ThreadId, refresh: boolean) =>
401 Effect.suspend(() => {
402 const queued = queuedThreadRequests.get(threadId);
403 if (queued !== undefined) {
404 queued.refresh ||= refresh;
405 return Effect.void;
406 }
407 const request = { threadId, refresh };
408 queuedThreadRequests.set(threadId, request);
409 return worker.enqueue(request);
410 });
411​
412 const linkedThreadsChange = makeLinkedThreadsChangeDetector();
413 // A running linked thread can reorder its answers on every event, so reorders refresh readers at
414 // most once per 10s, the cadence clients used to poll at.
415 const linkedThreadReorders = yield* Queue.dropping<void>(1);
416​
417 const notifyLinkedThreads = (event: OrchestrationV2DomainEvent) => {
418 switch (linkedThreadsChange(event)) {
419 case "changed":
420 return pullRequests.notifyLinkedThreadsChanged;
421 case "reordered":
422 return Queue.offer(linkedThreadReorders, undefined).pipe(Effect.asVoid);
423 case null:
424 return Effect.void;
425 }
426 };
427​
428 const processEvent = (event: OrchestrationV2DomainEvent) =>
429 Effect.andThen(notifyLinkedThreads(event), refreshForEvent(event));
430​
431 const refreshForEvent = (event: OrchestrationV2DomainEvent) => {
432 switch (event.type) {
433 case "thread.created":
434 case "thread.unarchived":
435 case "thread.metadata-updated":
436 return enqueueThread(event.threadId, false);
437 case "thread.unsettled":
438 case "checkpoint.captured":
439 return enqueueThread(event.threadId, true);
440 case "run.updated":
441 if (
442 event.payload.status === "completed" ||
443 event.payload.status === "failed" ||
444 event.payload.status === "cancelled" ||
445 event.payload.status === "interrupted"
446 ) {
447 return enqueueThread(event.threadId, true);
448 }
449 break;
450 }
451 return Effect.void;
452 };
453​
454 const start: ThreadPullRequestServiceV2["Service"]["start"] = Effect.fn(
455 "ThreadPullRequestServiceV2.start",
456 )(function* () {
457 yield* forkParked(Stream.runForEach(orchestrator.streamDomainEvents, processEvent));
458 yield* forkParked(
459 Queue.take(linkedThreadReorders).pipe(
460 Effect.andThen(pullRequests.notifyLinkedThreadsChanged),
461 Effect.andThen(Effect.sleep("10 seconds")),
462 Effect.forever,
463 ),
464 );
465 yield* forkParked(
466 Effect.gen(function* () {
467 yield* worker.enqueue({ threadId: null, refresh: false, backfill: true });
468 yield* worker.drain;
469 yield* Effect.gen(function* () {
470 // The sweep only catches pull requests opened outside a turn, which
471 // nobody sees without a client. Thread events still refresh headless work.
472 if (!(yield* backgroundPolicy.shouldRunOpportunisticWork)) return;
473 yield* worker.enqueue({ threadId: null, refresh: false });
474 yield* worker.drain;
475 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.delay("1 minute"));
476 }).pipe(Effect.asVoid),
477 );
478 });
479​
480 return { start, drain: worker.drain } satisfies ThreadPullRequestServiceV2["Service"];
481});