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

ThreadSettlementService.ts

674 lines27.7 KB

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