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 NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
11import * as Cause from "effect/Cause";
12import * as Context from "effect/Context";
13import * as SecureRandom from "effect/crypto/SecureRandom";
14import * as Effect from "effect/Effect";
15import * as FileSystem from "effect/FileSystem";
16import * as Option from "effect/Option";
17import * as Path from "effect/Path";
18import * as Schedule from "effect/Schedule";
19import type * as Scope from "effect/Scope";
20import * as Stream from "effect/Stream";
21
22import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
23import * as GitManager from "../git/GitManager.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 );
50}
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 );
62}
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 );
88}
89
90const BACKFILL_ATTEMPTS = 5;
91
92interface RefreshRequest {
93 readonly threadId: ThreadId | null;
94 readonly refresh: boolean;
95 readonly backfill?: boolean;
96}
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 threadId === null
124 ? orchestrator
125 .getShellSnapshot({
126 location: "active",
127 unsettledOnly: !(backfill || pendingBackfill.size > 0),
128 })
129 .pipe(NodeSqliteClient.readOnly)
130 : Effect.gen(function* () {
131 // Read sequence first so guarded sync rejects intervening changes.
132 const snapshotSequence = yield* orchestrator.getThreadEventSequence(threadId);
133 const thread = yield* orchestrator.getThreadShell(threadId);
134 return { snapshotSequence, threads: thread === null ? [] : [thread] };
135 });
136
137 const synchronize = Effect.fn("ThreadPullRequestServiceV2.synchronize")(function* (
138 request: RefreshRequest,
139 ) {
140 const [threadSnapshot, projectShells] = yield* Effect.all([
141 readThreadSnapshot(request),
142 projectStore.listShells(),
143 ]);
144 // Subagent children refresh after their own runs; sweeping them costs a lookup each per minute.
145 const snapshotThreads =
146 request.threadId === null
147 ? threadSnapshot.threads.filter(
148 (thread) => thread.lineage.relationshipToParent !== "subagent",
149 )
150 : threadSnapshot.threads;
151 const projects = new Map(projectShells.map((project) => [project.id, project]));
152 if (request.backfill) {
153 for (const thread of snapshotThreads) {
154 if (
155 (thread.settledOverride === "settled" || thread.settledAt !== null) &&
156 thread.branchPullRequest == null
157 ) {
158 pendingBackfill.set(thread.id, BACKFILL_ATTEMPTS);
159 }
160 }
161 }
162 const visibleThreadIds = new Set(
163 snapshotThreads.filter((thread) => thread.branch !== null).map((thread) => thread.id),
164 );
165 const checkedIds = request.threadId === null ? [...pendingBackfill.keys()] : [request.threadId];
166 for (const threadId of checkedIds) {
167 if (!visibleThreadIds.has(threadId)) pendingBackfill.delete(threadId);
168 }
169 const threads = snapshotThreads.filter(
170 (thread) =>
171 thread.archivedAt === null &&
172 ((thread.settledOverride !== "settled" && thread.settledAt === null) ||
173 request.threadId !== null ||
174 pendingBackfill.has(thread.id)) &&
175 (thread.branch !== null || thread.branchPullRequest != null),
176 );
177 const groups = Map.groupBy(threads, (thread) =>
178 JSON.stringify([thread.projectId, thread.worktreePath, thread.branch]),
179 );
180
181 yield* Effect.forEach(
182 groups.values(),
183 (group) =>
184 Effect.gen(function* () {
185 const first = group[0]!;
186 const project = projects.get(first.projectId);
187 if (project === undefined) return finishBackfill(group);
188 const { project: resolvedProject, repository } =
189 yield* resolveProjectForPullRequestDiscovery(project, repositoryIdentities, {
190 refresh: request.refresh,
191 });
192 if (first.branch !== null && repository === null) return finishBackfill(group);
193 // A worktree folder can outlive its .git, and git there fails with not_a_repository.
194 // An unreadable .git keeps the worktree rather than failing the whole group.
195 const cwd =
196 first.worktreePath !== null &&
197 (yield* fileSystem
198 .exists(path.join(first.worktreePath, ".git"))
199 .pipe(Effect.orElseSucceed(() => true)))
200 ? first.worktreePath
201 : project.workspaceRoot;
202 const detected =
203 first.branch === null
204 ? null
205 : yield* git.branchPullRequest(
206 { cwd, branch: first.branch },
207 { refresh: request.refresh },
208 );
209 if (detected !== null && !pullRequestMatchesProject(detected, resolvedProject)) {
210 return finishBackfill(group);
211 }
212 const detectedReference =
213 detected !== null && repository !== null
214 ? {
215 projectId: project.id,
216 repository,
217 number: detected.number,
218 url: detected.url,
219 }
220 : null;
221
222 const plans = yield* Effect.forEach(group, (thread) =>
223 Effect.gen(function* () {
224 let branchPullRequest = detectedReference;
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 (
235 previous.headBranch === thread.branch &&
236 (previous.state === "merged" || previous.state === "closed")
237 ) {
238 branchPullRequest = thread.branchPullRequest;
239 }
240 }
241
242 let replacement: ThreadLinkedPullRequest | undefined;
243 if (
244 (thread.pullRequests ?? []).length === 0 &&
245 thread.linkedPullRequest != null &&
246 detected?.state === "open" &&
247 detectedReference !== null &&
248 !samePullRequest(thread.linkedPullRequest, detectedReference)
249 ) {
250 const linked = yield* pullRequests.summary(thread.linkedPullRequest, {
251 recoverTransientFailure: false,
252 });
253 if (linked.state === "merged" || linked.state === "closed") {
254 replacement = detectedReference;
255 }
256 }
257 if (
258 samePullRequest(thread.branchPullRequest, branchPullRequest) &&
259 replacement === undefined
260 ) {
261 pendingBackfill.delete(thread.id);
262 return null;
263 }
264 return { thread, branchPullRequest, replacement };
265 }).pipe(
266 Effect.catchCauseIf(
267 (cause) => !Cause.hasInterruptsOnly(cause),
268 (cause) =>
269 Effect.logWarning("thread pull request discovery failed", {
270 threadId: thread.id,
271 cause: Cause.pretty(cause),
272 }).pipe(
273 Effect.tap(() => Effect.sync(() => failBackfill([thread]))),
274 Effect.as(null),
275 ),
276 ),
277 ),
278 );
279 const updates = plans.filter((plan) => plan !== null);
280 if (updates.length === 0) return;
281
282 if (detected !== null && first.branch !== null) {
283 const current = yield* git.branchPullRequest(
284 { cwd, branch: first.branch },
285 { freshGitState: true },
286 );
287 const currentIdentity = yield* repositoryIdentities.resolve(project.workspaceRoot, {
288 refresh: true,
289 });
290 if (
291 current === null ||
292 current.number !== detected.number ||
293 current.url !== detected.url ||
294 current.state !== detected.state ||
295 current.repositoryKey !== detected.repositoryKey ||
296 !pullRequestMatchesProject(current, {
297 ...project,
298 repositoryIdentity: currentIdentity,
299 })
300 ) {
301 return failBackfill(updates.map((update) => update.thread));
302 }
303 }
304
305 yield* Effect.forEach(
306 updates,
307 ({ thread, branchPullRequest, replacement }) =>
308 Effect.gen(function* () {
309 // Discovery yields to network I/O; recheck the project at commit to reject deleted projects or changed checkouts.
310 const currentProject = yield* projectStore.getShell(project.id);
311 if (!projectWorkspaceMatchesSnapshot(currentProject, project.workspaceRoot)) {
312 return failBackfill([thread]);
313 }
314 const uuid = yield* random.uuidV4();
315 yield* orchestrator.dispatch({
316 type: "thread.pull-request.sync",
317 commandId: CommandId.make(`server:thread-pull-request:${thread.id}:${uuid}`),
318 threadId: thread.id,
319 projectId: project.id,
320 snapshotSequence: threadSnapshot.snapshotSequence,
321 expected: {
322 workspaceRoot: project.workspaceRoot,
323 branch: thread.branch,
324 worktreePath: thread.worktreePath,
325 linkedPullRequest: thread.linkedPullRequest ?? null,
326 branchPullRequest: thread.branchPullRequest ?? null,
327 },
328 branchPullRequest,
329 ...(replacement === undefined ? {} : { linkedPullRequest: replacement }),
330 });
331 pendingBackfill.delete(thread.id);
332 }).pipe(
333 Effect.catchCauseIf(
334 (cause) => !Cause.hasInterruptsOnly(cause),
335 (cause) =>
336 Effect.logWarning("thread pull request update failed", {
337 threadId: thread.id,
338 cause: Cause.pretty(cause),
339 }).pipe(Effect.tap(() => Effect.sync(() => failBackfill([thread])))),
340 ),
341 ),
342 { discard: true },
343 );
344 }).pipe(
345 Effect.catchCauseIf(
346 (cause) => !Cause.hasInterruptsOnly(cause),
347 (cause) =>
348 Effect.logWarning("thread branch pull request lookup failed", {
349 threadIds: group.map((thread) => thread.id),
350 cause: Cause.pretty(cause),
351 }).pipe(Effect.tap(() => Effect.sync(() => failBackfill(group)))),
352 ),
353 ),
354 // Batch concurrent branch lookups into one GitHub GraphQL document.
355 { concurrency: 32, discard: true },
356 );
357 });
358
359 const worker = yield* makeDrainableWorker((request: RefreshRequest) =>
360 synchronize(request).pipe(
361 Effect.catchCauseIf(
362 (cause) => !Cause.hasInterruptsOnly(cause),
363 (cause) =>
364 Effect.logWarning("thread pull request refresh failed", {
365 cause: Cause.pretty(cause),
366 }),
367 ),
368 ),
369 );
370
371 const processEvent = (event: OrchestrationV2DomainEvent) => {
372 switch (event.type) {
373 case "thread.created":
374 case "thread.unarchived":
375 case "thread.metadata-updated":
376 return worker.enqueue({ threadId: event.threadId, refresh: false });
377 case "thread.unsettled":
378 case "checkpoint.captured":
379 return worker.enqueue({ threadId: event.threadId, refresh: true });
380 case "run.updated":
381 if (
382 event.payload.status === "completed" ||
383 event.payload.status === "failed" ||
384 event.payload.status === "cancelled" ||
385 event.payload.status === "interrupted"
386 ) {
387 return worker.enqueue({ threadId: event.threadId, refresh: true });
388 }
389 break;
390 }
391 return Effect.void;
392 };
393
394 const start: ThreadPullRequestServiceV2["Service"]["start"] = Effect.fn(
395 "ThreadPullRequestServiceV2.start",
396 )(function* () {
397 yield* forkParked(Stream.runForEach(orchestrator.streamDomainEvents, processEvent));
398 yield* forkParked(
399 Effect.gen(function* () {
400 yield* worker.enqueue({ threadId: null, refresh: false, backfill: true });
401 yield* worker.drain;
402 yield* Effect.gen(function* () {
403 // The sweep only catches pull requests opened outside a turn, which
404 // nobody sees without a client. Thread events still refresh headless work.
405 if (!(yield* backgroundPolicy.shouldRunOpportunisticWork)) return;
406 yield* worker.enqueue({ threadId: null, refresh: false });
407 yield* worker.drain;
408 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.delay("1 minute"));
409 }).pipe(Effect.asVoid),
410 );
411 });
412
413 return { start, drain: worker.drain } satisfies ThreadPullRequestServiceV2["Service"];
414});