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