Open History to see the last commit
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 { 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;
36}
37
38const DAY_MS = 24 * 60 * 60 * 1_000;
39const 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);
43}
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;
52}
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 );
64}
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 );
78}
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;
90}
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 });
106}
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);
134}
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;
157}
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 // Interrupted runs must keep the same snooze protection the sidebar shows.
170 return !isSnoozed(thread, nowMs);
171}
172
173/**
174 * Server twin of the client's `effectiveSnoozed`, so agents and the sidebar agree on what is
175 * snoozed.
176 */
177export function isSnoozed(
178 thread: Pick<
179 ProjectionStore.ProjectionSettlementCandidate,
180 "snoozedUntil" | "snoozedAt" | "latestRunCompletedAt" | "status" | "pendingRuntimeRequest"
181 >,
182 nowMs: number,
183): boolean {
184 const snoozedUntilMs = toMillis(thread.snoozedUntil);
185 if (snoozedUntilMs === null || snoozedUntilMs <= nowMs) return false;
186 if (thread.pendingRuntimeRequest !== null) return false;
187 const snoozedAtMs = toMillis(thread.snoozedAt);
188 const completedAtMs = toMillis(thread.latestRunCompletedAt);
189 const wokeOnError =
190 thread.status === "failed" &&
191 (snoozedAtMs === null || (completedAtMs !== null && completedAtMs > snoozedAtMs));
192 return !wokeOnError;
193}
194
195export function resolveAutoSettlementAt(input: {
196 readonly thread: ProjectionStore.ProjectionSettlementCandidate;
197 readonly pullRequest: SettlementPullRequest | null;
198 readonly nowMs: number;
199 readonly autoSettleAfterDays: number | null;
200 readonly autoSettleOnMerge: boolean;
201 readonly autoSettleKeepPullRequests?: boolean;
202}): DateTime.Utc | null {
203 const { thread } = input;
204 let pullRequest = input.pullRequest;
205 const links = settlementPullRequestLinks(thread.pullRequests ?? []);
206 if (links.some((link) => link.snapshot === null || link.snapshot.state === "open")) return null;
207 if (links.length > 0) {
208 const latest = links.reduce((current, candidate) =>
209 linkTerminalAtMs(candidate) > linkTerminalAtMs(current) ? candidate : current,
210 );
211 pullRequest =
212 latest.snapshot === null
213 ? null
214 : {
215 state: latest.snapshot.state,
216 mergedAt: latest.snapshot.mergedAt ?? null,
217 closedAt: latest.snapshot.closedAt ?? null,
218 };
219 }
220 if (!isAutoSettlementCandidate(thread, input.nowMs)) return null;
221 const activityAtMs =
222 latestMillis([
223 toMillis(thread.latestUserMessageAt),
224 toMillis(thread.latestRunRequestedAt),
225 toMillis(thread.latestRunStartedAt),
226 toMillis(thread.latestRunCompletedAt),
227 ]) ?? DateTime.toEpochMillis(thread.createdAt);
228 if (pullRequest !== null && pullRequestSettles(thread, pullRequest, input.autoSettleOnMerge)) {
229 return DateTime.makeUnsafe(activityAtMs);
230 }
231 const hasPullRequest =
232 pullRequest !== null || thread.linkedPullRequest != null || thread.branchPullRequest != null;
233 if (input.autoSettleKeepPullRequests === true && hasPullRequest) return null;
234 if (input.autoSettleAfterDays === null) return null;
235 const snoozedUntilMs = toMillis(thread.snoozedUntil);
236 const timerWakeAtMs =
237 snoozedUntilMs !== null && snoozedUntilMs <= input.nowMs ? snoozedUntilMs : null;
238 const inactivityAtMs =
239 latestMillis([activityAtMs, toMillis(thread.lastSnoozeWakeAt), timerWakeAtMs]) ?? activityAtMs;
240 return inactivityAtMs < input.nowMs - input.autoSettleAfterDays * DAY_MS
241 ? DateTime.makeUnsafe(inactivityAtMs)
242 : null;
243}
244
245export class ThreadSettlementServiceV2 extends Context.Service<
246 ThreadSettlementServiceV2,
247 {
248 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
249 readonly drain: Effect.Effect<void>;
250 }
251>()("t3/orchestration-v2/ThreadSettlementService/ThreadSettlementServiceV2") {}
252
253function autoSettlementConfigured(settings: import("@t3tools/contracts").ServerSettings): boolean {
254 if (settings.sidebarAutoSettleOnMerge || settings.sidebarAutoSettleAfterDays !== null) {
255 return true;
256 }
257 return Object.values(settings.projectSettingsOverrides).some(
258 (entry) =>
259 entry.sidebarAutoSettleOnMerge === true ||
260 (entry.sidebarAutoSettleAfterDays !== undefined && entry.sidebarAutoSettleAfterDays !== null),
261 );
262}
263
264/** @internal Exported for tests. */
265export function autoSettlementSettingsKey(
266 settings: import("@t3tools/contracts").ServerSettings,
267): string {
268 return JSON.stringify([
269 settings.sidebarAutoSettleOnMerge,
270 settings.sidebarAutoSettleAfterDays,
271 settings.sidebarAutoSettleKeepPullRequests,
272 Object.entries(settings.projectSettingsOverrides)
273 .filter(
274 ([, entry]) =>
275 entry.sidebarAutoSettleOnMerge !== undefined ||
276 entry.sidebarAutoSettleAfterDays !== undefined ||
277 entry.sidebarAutoSettleKeepPullRequests !== undefined,
278 )
279 .sort(([left], [right]) => left.localeCompare(right))
280 .map(([projectId, entry]) => [
281 projectId,
282 entry.sidebarAutoSettleOnMerge ?? "inherit",
283 entry.sidebarAutoSettleAfterDays === undefined
284 ? "inherit"
285 : entry.sidebarAutoSettleAfterDays,
286 entry.sidebarAutoSettleKeepPullRequests ?? "inherit",
287 ]),
288 ]);
289}
290
291export const make = Effect.gen(function* () {
292 const orchestrator = yield* Orchestrator.OrchestratorV2;
293 const projections = yield* ProjectionStore.ProjectionStoreV2;
294 const projectStore = yield* ProjectStore.ProjectStoreV2;
295 const settingsService = yield* ServerSettings.ServerSettingsService;
296 const git = yield* GitManager.GitManager;
297 const pullRequests = yield* PullRequestService.PullRequestService;
298 const crypto = yield* Crypto.Crypto;
299 const fileSystem = yield* FileSystem.FileSystem;
300 const terminals = yield* TerminalManager.TerminalManager;
301 const projectScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
302 // Settling a settled thread re-emits thread.settled with the same settledAt,
303 // so this keeps the settle action to one run per settlement.
304 const settleActionRunAt = new Map<ThreadId, number>();
305
306 const sweep = Effect.fn("ThreadSettlementServiceV2.sweep")(function* (
307 mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
308 threadId?: ThreadId,
309 ) {
310 const settings = yield* settingsService.getSettings;
311 if (!autoSettlementConfigured(settings)) {
312 return;
313 }
314 const threads = yield* projections.getSettlementCandidates(threadId);
315 if (threads.length === 0) return;
316 const projectShells = yield* projectStore.listShells();
317 const nowMs = DateTime.toEpochMillis(yield* DateTime.now);
318 const projects = new Map(projectShells.map((project) => [project.id, project]));
319 // A merge event re-sweeps every candidate, not just the threads linked to
320 // the merged pull request: most threads carry no link and settle from
321 // their branch lookup, which would otherwise wait for the next minute's
322 // sweep on a possibly stale cached answer.
323 const candidates = threads.filter((thread) => isAutoSettlementCandidate(thread, nowMs));
324
325 const settleThread = Effect.fn("ThreadSettlementServiceV2.settleThread")(
326 function* (thread: (typeof candidates)[number], pullRequest: SettlementPullRequest | null) {
327 const currentSettings = resolveProjectSettings(
328 yield* settingsService.getSettings,
329 thread.projectId,
330 ).settings;
331 const decisionNow = yield* DateTime.now;
332 const settledAt = resolveAutoSettlementAt({
333 thread,
334 pullRequest,
335 nowMs: DateTime.toEpochMillis(decisionNow),
336 autoSettleAfterDays: currentSettings.sidebarAutoSettleAfterDays,
337 autoSettleOnMerge: currentSettings.sidebarAutoSettleOnMerge,
338 autoSettleKeepPullRequests: currentSettings.sidebarAutoSettleKeepPullRequests,
339 });
340 if (settledAt === null) return thread;
341 const uuid = yield* crypto.randomUUIDv4();
342 yield* orchestrator.dispatch({
343 type: "thread.auto-settle",
344 commandId: CommandId.make(`server:auto-settle:${thread.id}:${uuid}`),
345 threadId: thread.id,
346 snapshotAt: thread.updatedAt,
347 settledAt,
348 });
349 return null;
350 },
351 (effect, thread) =>
352 effect.pipe(
353 Effect.catchCause((cause) =>
354 Cause.hasInterruptsOnly(cause)
355 ? Effect.failCause(cause)
356 : Effect.logWarning("automatic thread settlement skipped", {
357 threadId: thread.id,
358 cause: Cause.pretty(cause),
359 }).pipe(Effect.as(null)),
360 ),
361 ),
362 );
363
364 const lookupCandidates = (yield* Effect.forEach(
365 candidates,
366 (thread) => settleThread(thread, null),
367 { concurrency: 8 },
368 ))
369 .filter((thread) => thread !== null)
370 .filter((thread) => visibleThreadPullRequests(thread.pullRequests ?? []).length === 0);
371 const lookupCwdByThreadId = new Map<string, string>();
372 yield* Effect.forEach(
373 lookupCandidates,
374 (thread) =>
375 Effect.gen(function* () {
376 const project = projects.get(thread.projectId);
377 if (project === undefined || thread.branch === null) return;
378 const worktreeExists =
379 thread.worktreePath !== null &&
380 (yield* fileSystem.exists(thread.worktreePath).pipe(Effect.orElseSucceed(() => false)));
381 lookupCwdByThreadId.set(
382 thread.id,
383 worktreeExists && thread.worktreePath !== null
384 ? thread.worktreePath
385 : project.workspaceRoot,
386 );
387 }),
388 { concurrency: 8, discard: true },
389 );
390 if (mergedPullRequest !== null) {
391 // The merge just confirmed a terminal state the lookup caches can still
392 // call open (branch answers live two minutes, the sweep runs every
393 // minute). Drop the swept checkouts' cached answers so the merge settles
394 // its branch threads now instead of on a later sweep.
395 const cwds = [...new Set(lookupCwdByThreadId.values())];
396 yield* Effect.forEach(cwds, (cwd) => git.invalidateStatus(cwd), {
397 concurrency: 8,
398 discard: true,
399 });
400 }
401 const lookupKey = (thread: (typeof lookupCandidates)[number]) => {
402 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
403 if (reference != null) {
404 return JSON.stringify([
405 "linked",
406 reference.projectId,
407 reference.repository,
408 reference.number,
409 lookupCwdByThreadId.get(thread.id),
410 thread.branch,
411 ]);
412 }
413 if (thread.branch === null) return JSON.stringify(["none", thread.id]);
414 const cwd = lookupCwdByThreadId.get(thread.id);
415 return JSON.stringify(
416 cwd === undefined ? ["missing-project", thread.id] : ["branch", cwd, thread.branch],
417 );
418 };
419 const groups = Map.groupBy(lookupCandidates, lookupKey);
420
421 const wouldSettle = Effect.fn("ThreadSettlementServiceV2.wouldSettle")(function* (
422 group: ReadonlyArray<(typeof lookupCandidates)[number]>,
423 pullRequest: SettlementPullRequest,
424 ) {
425 const currentSettings = yield* settingsService.getSettings;
426 const decisionNow = yield* DateTime.now;
427 return group.some((thread) => {
428 const { settings } = resolveProjectSettings(currentSettings, thread.projectId);
429 return (
430 resolveAutoSettlementAt({
431 thread,
432 pullRequest,
433 nowMs: DateTime.toEpochMillis(decisionNow),
434 autoSettleAfterDays: settings.sidebarAutoSettleAfterDays,
435 autoSettleOnMerge: settings.sidebarAutoSettleOnMerge,
436 autoSettleKeepPullRequests: settings.sidebarAutoSettleKeepPullRequests,
437 }) !== null
438 );
439 });
440 });
441
442 const pullRequestFor = Effect.fn("ThreadSettlementServiceV2.pullRequestFor")(function* (
443 group: ReadonlyArray<(typeof lookupCandidates)[number]>,
444 ) {
445 const thread = group[0]!;
446 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
447 if (reference != null) {
448 // The event carries the merged state, so only the threads linked to
449 // that exact pull request settle from it. Every other linked thread
450 // falls through to a fresh summary lookup below: the merge sweep
451 // covers all candidates, and an unrelated merge must never settle
452 // them.
453 const matchesMerge =
454 mergedPullRequest !== null &&
455 reference.projectId === mergedPullRequest.projectId &&
456 reference.repository.toLowerCase() === mergedPullRequest.repository.toLowerCase() &&
457 reference.number === mergedPullRequest.number;
458 if (!matchesMerge && !projects.has(reference.projectId)) {
459 return yield* Effect.die(new Error("linked pull request project not found"));
460 }
461 const summary = matchesMerge
462 ? ({
463 state: "merged",
464 closedAt: null,
465 mergedAt: mergedPullRequest.mergedAt,
466 } satisfies SettlementPullRequest)
467 : yield* pullRequests.summary(
468 {
469 projectId: reference.projectId,
470 repository: reference.repository,
471 number: reference.number,
472 },
473 { recoverTransientFailure: false },
474 );
475 const terminal = {
476 state: summary.state,
477 closedAt: summary.closedAt ?? null,
478 mergedAt: summary.mergedAt ?? null,
479 } satisfies SettlementPullRequest;
480 const cwd = lookupCwdByThreadId.get(thread.id);
481 if (summary.state !== "open" && thread.branch !== null && cwd !== undefined) {
482 if (!(yield* wouldSettle(group, terminal))) return undefined;
483 const current = yield* git.branchPullRequest(
484 { cwd, branch: thread.branch },
485 { refresh: true },
486 );
487 const project = projects.get(thread.projectId);
488 if (
489 current?.state === "open" &&
490 project !== undefined &&
491 pullRequestMatchesProject(current, project)
492 ) {
493 return current;
494 }
495 }
496 return terminal;
497 }
498 if (thread.branch === null) return null;
499 const cwd = lookupCwdByThreadId.get(thread.id);
500 if (cwd === undefined) {
501 return yield* Effect.die(new Error("thread project not found"));
502 }
503 return yield* git.branchPullRequest({ cwd, branch: thread.branch });
504 });
505
506 yield* Effect.forEach(
507 groups.values(),
508 (group) =>
509 Effect.gen(function* () {
510 const pullRequest = yield* pullRequestFor(group);
511 if (pullRequest === undefined) return;
512 yield* Effect.forEach(group, (thread) => settleThread(thread, pullRequest), {
513 discard: true,
514 });
515 }).pipe(
516 Effect.catchCause((cause) =>
517 Cause.hasInterruptsOnly(cause)
518 ? Effect.failCause(cause)
519 : Effect.logWarning("automatic thread settlement skipped", {
520 threadIds: group.map((thread) => thread.id),
521 cause: Cause.pretty(cause),
522 }),
523 ),
524 ),
525 { concurrency: 8, discard: true },
526 );
527 });
528
529 const runSweep = (
530 mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
531 threadId?: ThreadId,
532 ) =>
533 sweep(mergedPullRequest, threadId).pipe(
534 Effect.catchCause((cause) =>
535 Cause.hasInterruptsOnly(cause)
536 ? Effect.failCause(cause)
537 : Effect.logWarning("automatic thread settlement sweep failed", {
538 cause: Cause.pretty(cause),
539 }),
540 ),
541 );
542 const worker = yield* makeDrainableWorker((threadId: ThreadId | undefined) =>
543 runSweep(null, threadId),
544 );
545
546 // Then the project's settle script runs in the thread's own worktree; a
547 // thread in the shared checkout skips it, because other threads may still be
548 // working there.
549 const cleanUpSettledThread = Effect.fn("ThreadSettlementServiceV2.cleanUpSettledThread")(
550 function* (threadId: ThreadId) {
551 const settled = yield* projections.getThread(threadId);
552 if (settled.settledOverride !== "settled") return;
553 yield* terminals.closeIdle({ threadId });
554 const worktreePath = settled.worktreePath;
555 if (worktreePath === null || !(yield* fileSystem.exists(worktreePath))) return;
556 // Closing and the worktree check wait on I/O. A thread re-engaged
557 // meanwhile is working again, so its worktree is no place for cleanup.
558 const thread = yield* projections.getThread(threadId);
559 if (thread.settledOverride !== "settled") return;
560 const settledAtMs = toMillis(thread.settledAt);
561 if (settledAtMs === null || settleActionRunAt.get(threadId) === settledAtMs) return;
562 const run = yield* projectScripts.runForThread({
563 threadId,
564 projectId: thread.projectId,
565 worktreePath,
566 trigger: "settle",
567 observeCompletion: {},
568 });
569 settleActionRunAt.set(threadId, settledAtMs);
570 if (run.status === "started" && run.completion) {
571 yield* run.completion.pipe(Effect.forkDetach);
572 }
573 },
574 (effect, threadId) =>
575 effect.pipe(
576 Effect.catchCause((cause) =>
577 Cause.hasInterruptsOnly(cause)
578 ? Effect.failCause(cause)
579 : Effect.logWarning("cleaning up a settled thread failed", {
580 threadId,
581 cause: Cause.pretty(cause),
582 }),
583 ),
584 ),
585 );
586
587 const processEvent = (event: OrchestrationV2DomainEvent) => {
588 switch (event.type) {
589 case "thread.settled":
590 return cleanUpSettledThread(event.threadId);
591 case "thread.pull-request-link-updated":
592 case "thread.pull-request-synced":
593 case "provider-session.detached":
594 return worker.enqueue(event.threadId);
595 case "provider-session.updated":
596 return event.payload.status !== "starting" && event.payload.status !== "running"
597 ? worker.enqueue(event.threadId)
598 : Effect.void;
599 case "run.updated":
600 return ["completed", "interrupted", "failed", "cancelled", "rolled_back"].includes(
601 event.payload.status,
602 )
603 ? worker.enqueue(event.threadId)
604 : Effect.void;
605 default:
606 return Effect.void;
607 }
608 };
609
610 const start: ThreadSettlementServiceV2["Service"]["start"] = Effect.fn(
611 "ThreadSettlementServiceV2.start",
612 )(function* () {
613 const settingsChanges = yield* settingsService.subscribeChanges;
614 const mergedPullRequests = yield* pullRequests.subscribeMerges;
615 const events = orchestrator.streamDomainEvents;
616 const initialSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
617 let lastSettlementSettings = autoSettlementSettingsKey(initialSettings);
618 yield* forkParked(
619 Effect.gen(function* () {
620 yield* worker.enqueue(undefined);
621 yield* worker.drain;
622 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
623 );
624 yield* forkParked(
625 Stream.runForEach(settingsChanges, (settings) => {
626 const key = autoSettlementSettingsKey(settings);
627 if (key === lastSettlementSettings) {
628 return Effect.void;
629 }
630 lastSettlementSettings = key;
631 return worker.enqueue(undefined);
632 }),
633 );
634 yield* forkParked(Stream.runForEach(mergedPullRequests, (event) => runSweep(event)));
635 yield* forkParked(
636 Stream.runForEach(events, processEvent).pipe(
637 Effect.catchCause((cause) =>
638 Effect.logWarning("Thread settlement event stream failed", { cause }),
639 ),
640 ),
641 );
642 });
643
644 return { start, drain: worker.drain } satisfies ThreadSettlementServiceV2["Service"];
645});
646
647export const layer = Layer.effect(ThreadSettlementServiceV2, make);