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

ThreadPullRequestService.ts

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