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

ThreadSettlementService.ts

660 lines25.9 KB

1import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
2import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
3import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
4import {
5 CommandId,
6 type ThreadId,
7 type OrchestrationV2DomainEvent,
8 type OrchestrationV2ThreadShell,
9} from "@t3tools/contracts";
10import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
11import * as Cause from "effect/Cause";
12import * as Context from "effect/Context";
13import * as Crypto from "effect/Crypto";
14import * as DateTime from "effect/DateTime";
15import * as Effect from "effect/Effect";
16import * as FileSystem from "effect/FileSystem";
17import * as Layer from "effect/Layer";
18import * as Schedule from "effect/Schedule";
19import type * as Scope from "effect/Scope";
20import * as Stream from "effect/Stream";
21​
22import * as GitManager from "../git/GitManager.ts";
23import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
24import * as PullRequestService from "../pullRequest/PullRequestService.ts";
25import * as ServerSettings from "../serverSettings.ts";
26import { forkBackground, forkParked } from "../serverActivation.ts";
27import * as TerminalManager from "../terminal/Manager.ts";
28import * as ProjectStore from "./ProjectStore.ts";
29import * as Orchestrator from "./Orchestrator.ts";
30import * as ProjectionStore from "./ProjectionStore.ts";
31​
32export interface SettlementPullRequest {
33 readonly state: "open" | "closed" | "merged";
34 readonly closedAt?: string | null;
35 readonly mergedAt?: string | null;
37​
38const DAY_MS = 24 * 60 * 60 * 1_000;
39export const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
40​
41function toMillis(value: DateTime.Utc | null | undefined): number | null {
42 return value == null ? null : DateTime.toEpochMillis(value);
44​
45function latestMillis(values: ReadonlyArray<number | null>): number | null {
46 let latest: number | null = null;
47 for (const value of values) {
48 if (value === null) continue;
49 if (latest === null || value > latest) latest = value;
50 }
51 return latest;
53​
54function canonicalRepositoryKey(key: string): string {
55 return key
56 .replace(
57 /^(?:ssh\.dev\.azure\.com|vs-ssh\.visualstudio\.com)\/v3\/([^/]+)\/([^/]+)\/([^/]+)$/u,
58 "dev.azure.com/$1/$2/_git/$3",
59 )
60 .replace(
61 /^([^.]+)\.visualstudio\.com\/(?:defaultcollection\/)?([^/]+)\/_git\/([^/]+)$/u,
62 "dev.azure.com/$1/$2/_git/$3",
63 );
65​
66function pullRequestMatchesProject(
67 pullRequest: GitManager.GitBranchPullRequest,
68 project: {
69 readonly repositoryIdentity?: { readonly canonicalKey: string } | null | undefined;
70 },
71): boolean {
72 return (
73 pullRequest.repositoryKey !== null &&
74 project.repositoryIdentity != null &&
75 canonicalRepositoryKey(pullRequest.repositoryKey) ===
76 canonicalRepositoryKey(project.repositoryIdentity.canonicalKey)
77 );
79​
80type SettlementPullRequestLink = NonNullable<
81 ProjectionStore.ProjectionSettlementCandidate["pullRequests"]
82>[number];
83​
84/** When the linked pull request merged or closed, or -Infinity if it has not. */
85function linkTerminalAtMs(link: SettlementPullRequestLink): number {
86 const snapshot = link.snapshot;
87 const value = snapshot?.state === "merged" ? snapshot.mergedAt : snapshot?.closedAt;
88 const timestamp = Date.parse(value ?? "");
89 return Number.isNaN(timestamp) ? Number.NEGATIVE_INFINITY : timestamp;
91​
92/**
93 * The links whose outcome the thread waits on. A link made after its pull
94 * request had already merged or closed records work the thread did, such as an
95 * agent merging pull requests it was asked to merge, so it cannot settle the
96 * thread.
97 */
98function settlementPullRequestLinks(
99 links: ReadonlyArray<SettlementPullRequestLink>,
100): ReadonlyArray<SettlementPullRequestLink> {
101 return visibleThreadPullRequests(links).filter((link) => {
102 if (link.snapshot === null || link.snapshot.state === "open") return true;
103 const linkedAtMs = Date.parse(link.linkedAt);
104 return Number.isNaN(linkedAtMs) || linkTerminalAtMs(link) >= linkedAtMs;
105 });
107​
108/**
109 * Absolute age bounds client clock skew in both directions and stops stale
110 * pre-adoption data from blocking the thread forever.
111 */
112export function threadHasQueuedTurnStart(
113 thread: Pick<
114 OrchestrationV2ThreadShell,
115 | "latestUserMessageAt"
116 | "latestRunRequestedAt"
117 | "latestRunStartedAt"
118 | "latestRunCompletedAt"
119 | "latestRunId"
120 | "status"
121 >,
122 nowMs: number,
123): boolean {
124 const messageAtMs = toMillis(thread.latestUserMessageAt);
125 if (messageAtMs === null || thread.status === "failed") return false;
126 const age = nowMs - messageAtMs;
127 if (Number.isNaN(age) || Math.abs(age) > QUEUED_TURN_START_GRACE_MS) return false;
128 if (thread.latestRunId === null) return true;
129 return [
130 toMillis(thread.latestRunRequestedAt),
131 toMillis(thread.latestRunStartedAt),
132 toMillis(thread.latestRunCompletedAt),
133 ].every((value) => value === null || value < messageAtMs);
135​
136function pullRequestSettles(
137 thread: Pick<
138 ProjectionStore.ProjectionSettlementCandidate,
139 "createdAt" | "latestUserAuthoredMessageAt"
140 >,
141 pullRequest: SettlementPullRequest,
142 autoSettleOnMerge: boolean,
143): boolean {
144 if (pullRequest.state !== "closed" && (pullRequest.state !== "merged" || !autoSettleOnMerge)) {
145 return false;
146 }
147 const terminalAt = pullRequest.state === "merged" ? pullRequest.mergedAt : pullRequest.closedAt;
148 if (terminalAt == null) return false;
149 const userAnchorMs = latestMillis([
150 toMillis(thread.createdAt),
151 toMillis(thread.latestUserAuthoredMessageAt),
152 ]);
153 if (userAnchorMs === null) return false;
154 const pullRequestAtMs = Date.parse(terminalAt);
155 if (Number.isNaN(pullRequestAtMs)) return false;
156 return pullRequestAtMs >= userAnchorMs;
158​
159export function isAutoSettlementCandidate(
160 thread: Omit<ProjectionStore.ProjectionSettlementCandidate, "latestUserAuthoredMessageAt">,
161 nowMs: number,
162): boolean {
163 if (thread.archivedAt !== null || thread.settledOverride !== null) return false;
164 if (thread.pinnedAt != null || thread.autoSettleDisabledAt != null) return false;
165 if (thread.pendingRuntimeRequest !== null) return false;
166 if (thread.activityRunStatus != null) return false;
167 if (backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])) return false;
168 if (threadHasQueuedTurnStart(thread, nowMs)) return false;
169 const snoozedUntilMs = toMillis(thread.snoozedUntil);
170 if (snoozedUntilMs === null || snoozedUntilMs <= nowMs) return true;
171 const snoozedAtMs = toMillis(thread.snoozedAt);
172 const completedAtMs = toMillis(thread.latestRunCompletedAt);
173 const wokeOnError =
174 thread.status === "failed" &&
175 (snoozedAtMs === null || (completedAtMs !== null && completedAtMs > snoozedAtMs));
176 const wokeOnCompletion =
177 snoozedAtMs !== null && completedAtMs !== null && completedAtMs > snoozedAtMs;
178 return wokeOnError || wokeOnCompletion;
180​
181/**
182 * Server twin of the client's `effectiveSnoozed`, so agents and the sidebar agree on what is
183 * snoozed.
184 */
185export function isSnoozed(
186 thread: Pick<
187 ProjectionStore.ProjectionSettlementCandidate,
188 "snoozedUntil" | "snoozedAt" | "latestRunCompletedAt" | "status" | "pendingRuntimeRequest"
189 >,
190 nowMs: number,
191): boolean {
192 const snoozedUntilMs = toMillis(thread.snoozedUntil);
193 if (snoozedUntilMs === null || snoozedUntilMs <= nowMs) return false;
194 if (thread.pendingRuntimeRequest !== null) return false;
195 const snoozedAtMs = toMillis(thread.snoozedAt);
196 const completedAtMs = toMillis(thread.latestRunCompletedAt);
197 const wokeOnError =
198 thread.status === "failed" &&
199 (snoozedAtMs === null || (completedAtMs !== null && completedAtMs > snoozedAtMs));
200 const wokeOnCompletion =
201 thread.status === "completed" &&
202 snoozedAtMs !== null &&
203 completedAtMs !== null &&
204 completedAtMs > snoozedAtMs;
205 return !wokeOnError && !wokeOnCompletion;
207​
208export function resolveAutoSettlementAt(input: {
209 readonly thread: ProjectionStore.ProjectionSettlementCandidate;
210 readonly pullRequest: SettlementPullRequest | null;
211 readonly nowMs: number;
212 readonly autoSettleAfterDays: number | null;
213 readonly autoSettleOnMerge: boolean;
214 readonly autoSettleKeepPullRequests?: boolean;
215}): DateTime.Utc | null {
216 const { thread } = input;
217 let pullRequest = input.pullRequest;
218 const links = settlementPullRequestLinks(thread.pullRequests ?? []);
219 if (links.some((link) => link.snapshot === null || link.snapshot.state === "open")) return null;
220 if (links.length > 0) {
221 const latest = links.reduce((current, candidate) =>
222 linkTerminalAtMs(candidate) > linkTerminalAtMs(current) ? candidate : current,
223 );
224 pullRequest =
225 latest.snapshot === null
226 ? null
227 : {
228 state: latest.snapshot.state,
229 mergedAt: latest.snapshot.mergedAt ?? null,
230 closedAt: latest.snapshot.closedAt ?? null,
231 };
232 }
233 if (!isAutoSettlementCandidate(thread, input.nowMs)) return null;
234 const activityAtMs = latestMillis([
235 toMillis(thread.latestUserMessageAt),
236 toMillis(thread.latestRunRequestedAt),
237 toMillis(thread.latestRunStartedAt),
238 toMillis(thread.latestRunCompletedAt),
239 ]);
240 if (pullRequest !== null && pullRequestSettles(thread, pullRequest, input.autoSettleOnMerge)) {
241 return activityAtMs === null ? thread.createdAt : DateTime.makeUnsafe(activityAtMs);
242 }
243 const hasPullRequest =
244 pullRequest !== null || thread.linkedPullRequest != null || thread.branchPullRequest != null;
245 if (input.autoSettleKeepPullRequests === true && hasPullRequest) return null;
246 if (input.autoSettleAfterDays === null || activityAtMs === null) return null;
247 const snoozedUntilMs = toMillis(thread.snoozedUntil);
248 const timerWakeAtMs =
249 snoozedUntilMs !== null && snoozedUntilMs <= input.nowMs ? snoozedUntilMs : null;
250 const inactivityAtMs =
251 latestMillis([activityAtMs, toMillis(thread.lastSnoozeWakeAt), timerWakeAtMs]) ?? activityAtMs;
252 return inactivityAtMs < input.nowMs - input.autoSettleAfterDays * DAY_MS
253 ? DateTime.makeUnsafe(inactivityAtMs)
254 : null;
256​
257export class ThreadSettlementServiceV2 extends Context.Service<
258 ThreadSettlementServiceV2,
259 {
260 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
261 readonly drain: Effect.Effect<void>;
262 }
263>()("t3/orchestration-v2/ThreadSettlementService/ThreadSettlementServiceV2") {}
264​
265function autoSettlementConfigured(settings: import("@t3tools/contracts").ServerSettings): boolean {
266 if (settings.sidebarAutoSettleOnMerge || settings.sidebarAutoSettleAfterDays !== null) {
267 return true;
268 }
269 return Object.values(settings.projectSettingsOverrides).some(
270 (entry) =>
271 entry.sidebarAutoSettleOnMerge === true ||
272 (entry.sidebarAutoSettleAfterDays !== undefined && entry.sidebarAutoSettleAfterDays !== null),
273 );
275​
276/** @internal Exported for tests. */
277export function autoSettlementSettingsKey(
278 settings: import("@t3tools/contracts").ServerSettings,
279): string {
280 return JSON.stringify([
281 settings.sidebarAutoSettleOnMerge,
282 settings.sidebarAutoSettleAfterDays,
283 settings.sidebarAutoSettleKeepPullRequests,
284 Object.entries(settings.projectSettingsOverrides)
285 .filter(
286 ([, entry]) =>
287 entry.sidebarAutoSettleOnMerge !== undefined ||
288 entry.sidebarAutoSettleAfterDays !== undefined ||
289 entry.sidebarAutoSettleKeepPullRequests !== undefined,
290 )
291 .sort(([left], [right]) => left.localeCompare(right))
292 .map(([projectId, entry]) => [
293 projectId,
294 entry.sidebarAutoSettleOnMerge ?? "inherit",
295 entry.sidebarAutoSettleAfterDays === undefined
296 ? "inherit"
297 : entry.sidebarAutoSettleAfterDays,
298 entry.sidebarAutoSettleKeepPullRequests ?? "inherit",
299 ]),
300 ]);
302​
303export const make = Effect.gen(function* () {
304 const orchestrator = yield* Orchestrator.OrchestratorV2;
305 const projections = yield* ProjectionStore.ProjectionStoreV2;
306 const projectStore = yield* ProjectStore.ProjectStoreV2;
307 const settingsService = yield* ServerSettings.ServerSettingsService;
308 const git = yield* GitManager.GitManager;
309 const pullRequests = yield* PullRequestService.PullRequestService;
310 const crypto = yield* Crypto.Crypto;
311 const fileSystem = yield* FileSystem.FileSystem;
312 const terminals = yield* TerminalManager.TerminalManager;
313 const projectScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
314 // Settling a settled thread re-emits thread.settled with the same settledAt,
315 // so this keeps the settle action to one run per settlement.
316 const settleActionRunAt = new Map<ThreadId, number>();
317​
318 const sweep = Effect.fn("ThreadSettlementServiceV2.sweep")(function* (
319 mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
320 threadId?: ThreadId,
321 ) {
322 const settings = yield* settingsService.getSettings;
323 if (!autoSettlementConfigured(settings)) {
324 return;
325 }
326 const threads = yield* projections.getSettlementCandidates(threadId);
327 if (threads.length === 0) return;
328 const projectShells = yield* projectStore.listShells();
329 const nowMs = DateTime.toEpochMillis(yield* DateTime.now);
330 const projects = new Map(projectShells.map((project) => [project.id, project]));
331 // A merge event re-sweeps every candidate, not just the threads linked to
332 // the merged pull request: most threads carry no link and settle from
333 // their branch lookup, which would otherwise wait for the next minute's
334 // sweep on a possibly stale cached answer.
335 const candidates = threads.filter((thread) => isAutoSettlementCandidate(thread, nowMs));
336​
337 const settleThread = Effect.fn("ThreadSettlementServiceV2.settleThread")(
338 function* (thread: (typeof candidates)[number], pullRequest: SettlementPullRequest | null) {
339 const currentSettings = resolveProjectSettings(
340 yield* settingsService.getSettings,
341 thread.projectId,
342 ).settings;
343 const decisionNow = yield* DateTime.now;
344 const settledAt = resolveAutoSettlementAt({
345 thread,
346 pullRequest,
347 nowMs: DateTime.toEpochMillis(decisionNow),
348 autoSettleAfterDays: currentSettings.sidebarAutoSettleAfterDays,
349 autoSettleOnMerge: currentSettings.sidebarAutoSettleOnMerge,
350 autoSettleKeepPullRequests: currentSettings.sidebarAutoSettleKeepPullRequests,
351 });
352 if (settledAt === null) return thread;
353 const uuid = yield* crypto.randomUUIDv4();
354 yield* orchestrator.dispatch({
355 type: "thread.auto-settle",
356 commandId: CommandId.make(`server:auto-settle:${thread.id}:${uuid}`),
357 threadId: thread.id,
358 snapshotAt: Orchestrator.autoSettleSnapshotAt(thread),
359 settledAt,
360 });
361 return null;
362 },
363 (effect, thread) =>
364 effect.pipe(
365 Effect.catchCause((cause) =>
366 Cause.hasInterruptsOnly(cause)
367 ? Effect.failCause(cause)
368 : Effect.logWarning("automatic thread settlement skipped", {
369 threadId: thread.id,
370 cause: Cause.pretty(cause),
371 }).pipe(Effect.as(null)),
372 ),
373 ),
374 );
375​
376 const lookupCandidates = (yield* Effect.forEach(
377 candidates,
378 (thread) => settleThread(thread, null),
379 { concurrency: 8 },
380 ))
381 .filter((thread) => thread !== null)
382 .filter((thread) => visibleThreadPullRequests(thread.pullRequests ?? []).length === 0);
383 const lookupCwdByThreadId = new Map<string, string>();
384 yield* Effect.forEach(
385 lookupCandidates,
386 (thread) =>
387 Effect.gen(function* () {
388 const project = projects.get(thread.projectId);
389 if (project === undefined || thread.branch === null) return;
390 const worktreeExists =
391 thread.worktreePath !== null &&
392 (yield* fileSystem.exists(thread.worktreePath).pipe(Effect.orElseSucceed(() => false)));
393 lookupCwdByThreadId.set(
394 thread.id,
395 worktreeExists && thread.worktreePath !== null
396 ? thread.worktreePath
397 : project.workspaceRoot,
398 );
399 }),
400 { concurrency: 8, discard: true },
401 );
402 if (mergedPullRequest !== null) {
403 // The merge just confirmed a terminal state the lookup caches can still
404 // call open (branch answers live two minutes, the sweep runs every
405 // minute). Drop the swept checkouts' cached answers so the merge settles
406 // its branch threads now instead of on a later sweep.
407 const cwds = [...new Set(lookupCwdByThreadId.values())];
408 yield* Effect.forEach(cwds, (cwd) => git.invalidateStatus(cwd), {
409 concurrency: 8,
410 discard: true,
411 });
412 }
413 const lookupKey = (thread: (typeof lookupCandidates)[number]) => {
414 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
415 if (reference != null) {
416 return JSON.stringify([
417 "linked",
418 reference.projectId,
419 reference.repository,
420 reference.number,
421 lookupCwdByThreadId.get(thread.id),
422 thread.branch,
423 ]);
424 }
425 if (thread.branch === null) return JSON.stringify(["none", thread.id]);
426 const cwd = lookupCwdByThreadId.get(thread.id);
427 return JSON.stringify(
428 cwd === undefined ? ["missing-project", thread.id] : ["branch", cwd, thread.branch],
429 );
430 };
431 const groups = Map.groupBy(lookupCandidates, lookupKey);
432​
433 const wouldSettle = Effect.fn("ThreadSettlementServiceV2.wouldSettle")(function* (
434 group: ReadonlyArray<(typeof lookupCandidates)[number]>,
435 pullRequest: SettlementPullRequest,
436 ) {
437 const currentSettings = yield* settingsService.getSettings;
438 const decisionNow = yield* DateTime.now;
439 return group.some((thread) => {
440 const { settings } = resolveProjectSettings(currentSettings, thread.projectId);
441 return (
442 resolveAutoSettlementAt({
443 thread,
444 pullRequest,
445 nowMs: DateTime.toEpochMillis(decisionNow),
446 autoSettleAfterDays: settings.sidebarAutoSettleAfterDays,
447 autoSettleOnMerge: settings.sidebarAutoSettleOnMerge,
448 autoSettleKeepPullRequests: settings.sidebarAutoSettleKeepPullRequests,
449 }) !== null
450 );
451 });
452 });
453​
454 const pullRequestFor = Effect.fn("ThreadSettlementServiceV2.pullRequestFor")(function* (
455 group: ReadonlyArray<(typeof lookupCandidates)[number]>,
456 ) {
457 const thread = group[0]!;
458 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
459 if (reference != null) {
460 // The event carries the merged state, so only the threads linked to
461 // that exact pull request settle from it. Every other linked thread
462 // falls through to a fresh summary lookup below: the merge sweep
463 // covers all candidates, and an unrelated merge must never settle
464 // them.
465 const matchesMerge =
466 mergedPullRequest !== null &&
467 reference.projectId === mergedPullRequest.projectId &&
468 reference.repository.toLowerCase() === mergedPullRequest.repository.toLowerCase() &&
469 reference.number === mergedPullRequest.number;
470 if (!matchesMerge && !projects.has(reference.projectId)) {
471 return yield* Effect.die(new Error("linked pull request project not found"));
472 }
473 const summary = matchesMerge
474 ? ({
475 state: "merged",
476 closedAt: null,
477 mergedAt: mergedPullRequest.mergedAt,
478 } satisfies SettlementPullRequest)
479 : yield* pullRequests.summary(
480 {
481 projectId: reference.projectId,
482 repository: reference.repository,
483 number: reference.number,
484 },
485 { recoverTransientFailure: false },
486 );
487 const terminal = {
488 state: summary.state,
489 closedAt: summary.closedAt ?? null,
490 mergedAt: summary.mergedAt ?? null,
491 } satisfies SettlementPullRequest;
492 const cwd = lookupCwdByThreadId.get(thread.id);
493 if (summary.state !== "open" && thread.branch !== null && cwd !== undefined) {
494 if (!(yield* wouldSettle(group, terminal))) return undefined;
495 const current = yield* git.branchPullRequest(
496 { cwd, branch: thread.branch },
497 { refresh: true },
498 );
499 const project = projects.get(thread.projectId);
500 if (
501 current?.state === "open" &&
502 project !== undefined &&
503 pullRequestMatchesProject(current, project)
504 ) {
505 return current;
506 }
507 }
508 return terminal;
509 }
510 if (thread.branch === null) return null;
511 const cwd = lookupCwdByThreadId.get(thread.id);
512 if (cwd === undefined) {
513 return yield* Effect.die(new Error("thread project not found"));
514 }
515 return yield* git.branchPullRequest({ cwd, branch: thread.branch });
516 });
517​
518 yield* Effect.forEach(
519 groups.values(),
520 (group) =>
521 Effect.gen(function* () {
522 const pullRequest = yield* pullRequestFor(group);
523 if (pullRequest === undefined) return;
524 yield* Effect.forEach(group, (thread) => settleThread(thread, pullRequest), {
525 discard: true,
526 });
527 }).pipe(
528 Effect.catchCause((cause) =>
529 Cause.hasInterruptsOnly(cause)
530 ? Effect.failCause(cause)
531 : Effect.logWarning("automatic thread settlement skipped", {
532 threadIds: group.map((thread) => thread.id),
533 cause: Cause.pretty(cause),
534 }),
535 ),
536 ),
537 { concurrency: 8, discard: true },
538 );
539 });
540​
541 const runSweep = (
542 mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
543 threadId?: ThreadId,
544 ) =>
545 sweep(mergedPullRequest, threadId).pipe(
546 Effect.catchCause((cause) =>
547 Cause.hasInterruptsOnly(cause)
548 ? Effect.failCause(cause)
549 : Effect.logWarning("automatic thread settlement sweep failed", {
550 cause: Cause.pretty(cause),
551 }),
552 ),
553 );
554 const worker = yield* makeDrainableWorker((threadId: ThreadId | undefined) =>
555 runSweep(null, threadId),
556 );
557​
558 // Then the project's settle script runs in the thread's own worktree; a
559 // thread in the shared checkout skips it, because other threads may still be
560 // working there.
561 const cleanUpSettledThread = Effect.fn("ThreadSettlementServiceV2.cleanUpSettledThread")(
562 function* (threadId: ThreadId) {
563 const settled = yield* projections.getThread(threadId);
564 if (settled.settledOverride !== "settled") return;
565 yield* terminals.closeIdle({ threadId });
566 const worktreePath = settled.worktreePath;
567 if (worktreePath === null || !(yield* fileSystem.exists(worktreePath))) return;
568 // Closing and the worktree check wait on I/O. A thread re-engaged
569 // meanwhile is working again, so its worktree is no place for cleanup.
570 const thread = yield* projections.getThread(threadId);
571 if (thread.settledOverride !== "settled") return;
572 const settledAtMs = toMillis(thread.settledAt);
573 if (settledAtMs === null || settleActionRunAt.get(threadId) === settledAtMs) return;
574 const run = yield* projectScripts.runForThread({
575 threadId,
576 projectId: thread.projectId,
577 worktreePath,
578 trigger: "settle",
579 observeCompletion: {},
580 });
581 settleActionRunAt.set(threadId, settledAtMs);
582 if (run.status === "started" && run.completion) {
583 yield* run.completion.pipe(Effect.forkDetach);
584 }
585 },
586 (effect, threadId) =>
587 effect.pipe(
588 Effect.catchCause((cause) =>
589 Cause.hasInterruptsOnly(cause)
590 ? Effect.failCause(cause)
591 : Effect.logWarning("cleaning up a settled thread failed", {
592 threadId,
593 cause: Cause.pretty(cause),
594 }),
595 ),
596 ),
597 );
598​
599 const processEvent = (event: OrchestrationV2DomainEvent) => {
600 switch (event.type) {
601 case "thread.settled":
602 return cleanUpSettledThread(event.threadId);
603 case "thread.pull-request-link-updated":
604 case "thread.pull-request-synced":
605 case "thread.pull-request-link-synced":
606 case "provider-session.detached":
607 return worker.enqueue(event.threadId);
608 case "provider-session.updated":
609 return event.payload.status !== "starting" && event.payload.status !== "running"
610 ? worker.enqueue(event.threadId)
611 : Effect.void;
612 case "run.updated":
613 return ["completed", "interrupted", "failed", "cancelled", "rolled_back"].includes(
614 event.payload.status,
615 )
616 ? worker.enqueue(event.threadId)
617 : Effect.void;
618 default:
619 return Effect.void;
620 }
621 };
622​
623 const start: ThreadSettlementServiceV2["Service"]["start"] = Effect.fn(
624 "ThreadSettlementServiceV2.start",
625 )(function* () {
626 const settingsChanges = yield* settingsService.subscribeChanges;
627 const mergedPullRequests = yield* pullRequests.subscribeMerges;
628 const events = orchestrator.streamDomainEvents;
629 const initialSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
630 let lastSettlementSettings = autoSettlementSettingsKey(initialSettings);
631 yield* forkBackground(
632 Effect.gen(function* () {
633 yield* worker.enqueue(undefined);
634 yield* worker.drain;
635 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
636 );
637 yield* forkParked(
638 Stream.runForEach(settingsChanges, (settings) => {
639 const key = autoSettlementSettingsKey(settings);
640 if (key === lastSettlementSettings) {
641 return Effect.void;
642 }
643 lastSettlementSettings = key;
644 return worker.enqueue(undefined);
645 }),
646 );
647 yield* forkParked(Stream.runForEach(mergedPullRequests, (event) => runSweep(event)));
648 yield* forkParked(
649 Stream.runForEach(events, processEvent).pipe(
650 Effect.catchCause((cause) =>
651 Effect.logWarning("Thread settlement event stream failed", { cause }),
652 ),
653 ),
654 );
655 });
656​
657 return { start, drain: worker.drain } satisfies ThreadSettlementServiceV2["Service"];
658});
659​
660export const layer = Layer.effect(ThreadSettlementServiceV2, make);