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