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