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