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

ThreadSettlementService.ts

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