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