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

ThreadPullRequestService.ts

405 lines16.2 KB

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