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