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