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

ThreadSettlementService.ts

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