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

ThreadSettlementService.ts

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