Open History to see the last commit
1import {
2 backgroundWorkHoldsCompletion,
3 turnItemUpdateCanEndBackgroundWork,
4} from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
5import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
6import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
7import {
8 CommandId,
9 isOrchestrationV2WorkActive,
10 type ThreadId,
11 type OrchestrationV2DomainEvent,
12 type OrchestrationV2ThreadShell,
13} from "@t3tools/contracts";
14import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
15import * as Cause from "effect/Cause";
16import * as Context from "effect/Context";
17import * as Crypto from "effect/Crypto";
18import * as DateTime from "effect/DateTime";
19import * as Effect from "effect/Effect";
20import * as FiberSet from "effect/FiberSet";
21import * as FileSystem from "effect/FileSystem";
22import * as Schedule from "effect/Schedule";
23import * as Semaphore from "effect/Semaphore";
24import type * as Scope from "effect/Scope";
25import * as Stream from "effect/Stream";
26
27import * as GitManager from "../git/GitManager.ts";
28import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
29import * as PullRequestService from "../pullRequest/PullRequestService.ts";
30import * as ServerSettings from "../serverSettings.ts";
31import { forkParked } from "../serverActivation.ts";
32import * as TerminalManager from "../terminal/Manager.ts";
33import * as ProjectStore from "./ProjectStore.ts";
34import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
35import * as Orchestrator from "./Orchestrator.ts";
36import * as ProjectionStore from "./ProjectionStore.ts";
37
38export interface SettlementPullRequest {
39 readonly state: "open" | "closed" | "merged";
40 readonly closedAt?: string | null;
41 readonly mergedAt?: string | null;
42}
43
44const DAY_MS = 24 * 60 * 60 * 1_000;
45const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
46
47function toMillis(value: DateTime.Utc | null | undefined): number | null {
48 return value == null ? null : DateTime.toEpochMillis(value);
49}
50
51function latestMillis(values: ReadonlyArray<number | null>): number | null {
52 let latest: number | null = null;
53 for (const value of values) {
54 if (value === null) continue;
55 if (latest === null || value > latest) latest = value;
56 }
57 return latest;
58}
59
60function pullRequestMatchesProject(
61 pullRequest: GitManager.GitBranchPullRequest,
62 project: {
63 readonly repositoryIdentity?: { readonly canonicalKey: string } | null | undefined;
64 },
65): boolean {
66 return (
67 pullRequest.repositoryKey !== null &&
68 project.repositoryIdentity != null &&
69 sourceControlDefinitions.canonicalRepositoryKey(pullRequest.repositoryKey) ===
70 sourceControlDefinitions.canonicalRepositoryKey(project.repositoryIdentity.canonicalKey)
71 );
72}
73
74type SettlementPullRequestLink = NonNullable<
75 ProjectionStore.ProjectionSettlementCandidate["pullRequests"]
76>[number];
77
78/** When the linked pull request merged or closed, or -Infinity if it has not. */
79function linkTerminalAtMs(link: SettlementPullRequestLink): number {
80 const snapshot = link.snapshot;
81 const value = snapshot?.state === "merged" ? snapshot.mergedAt : snapshot?.closedAt;
82 const timestamp = Date.parse(value ?? "");
83 return Number.isNaN(timestamp) ? Number.NEGATIVE_INFINITY : timestamp;
84}
85
86/** Exclude links added after merge or close; they record completed work rather than outcomes this thread awaits. */
87function settlementPullRequestLinks(
88 links: ReadonlyArray<SettlementPullRequestLink>,
89): ReadonlyArray<SettlementPullRequestLink> {
90 return visibleThreadPullRequests(links).filter((link) => {
91 if (link.snapshot === null || link.snapshot.state === "open") return true;
92 const linkedAtMs = Date.parse(link.linkedAt);
93 return Number.isNaN(linkedAtMs) || linkTerminalAtMs(link) >= linkedAtMs;
94 });
95}
96
97/** Absolute age bounds clock skew in both directions and expires stale pre-adoption data. */
98export function threadHasQueuedTurnStart(
99 thread: Pick<
100 OrchestrationV2ThreadShell,
101 | "latestUserMessageAt"
102 | "latestRunRequestedAt"
103 | "latestRunStartedAt"
104 | "latestRunCompletedAt"
105 | "latestRunId"
106 | "status"
107 >,
108 nowMs: number,
109): boolean {
110 const messageAtMs = toMillis(thread.latestUserMessageAt);
111 if (messageAtMs === null || thread.status === "failed") return false;
112 const age = nowMs - messageAtMs;
113 if (Number.isNaN(age) || Math.abs(age) > QUEUED_TURN_START_GRACE_MS) return false;
114 if (thread.latestRunId === null) return true;
115 return [
116 toMillis(thread.latestRunRequestedAt),
117 toMillis(thread.latestRunStartedAt),
118 toMillis(thread.latestRunCompletedAt),
119 ].every((value) => value === null || value < messageAtMs);
120}
121
122function pullRequestSettles(
123 thread: Pick<
124 ProjectionStore.ProjectionSettlementCandidate,
125 "createdAt" | "latestUserAuthoredMessageAt"
126 >,
127 pullRequest: SettlementPullRequest,
128 autoSettleOnMerge: boolean,
129): boolean {
130 if (pullRequest.state !== "closed" && (pullRequest.state !== "merged" || !autoSettleOnMerge)) {
131 return false;
132 }
133 const terminalAt = pullRequest.state === "merged" ? pullRequest.mergedAt : pullRequest.closedAt;
134 if (terminalAt == null) return false;
135 const userAnchorMs = latestMillis([
136 toMillis(thread.createdAt),
137 toMillis(thread.latestUserAuthoredMessageAt),
138 ]);
139 if (userAnchorMs === null) return false;
140 const pullRequestAtMs = Date.parse(terminalAt);
141 if (Number.isNaN(pullRequestAtMs)) return false;
142 return pullRequestAtMs >= userAnchorMs;
143}
144
145export function isAutoSettlementCandidate(
146 thread: Omit<ProjectionStore.ProjectionSettlementCandidate, "latestUserAuthoredMessageAt">,
147 nowMs: number,
148): boolean {
149 if (thread.archivedAt !== null || thread.settledOverride !== null) return false;
150 if (thread.pinnedAt != null || thread.autoSettleDisabledAt != null) return false;
151 if (thread.pendingRuntimeRequest !== null) return false;
152 // A guest is waiting on the owner; settling would hide the Request.
153 if ((thread.pendingGuestMessageCount ?? 0) > 0) return false;
154 if (thread.activityRunStatus != null) return false;
155 if (backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])) return false;
156 if (threadHasQueuedTurnStart(thread, nowMs)) return false;
157 // Interrupted runs must keep the same snooze protection the sidebar shows.
158 return !isSnoozed(thread, nowMs);
159}
160
161/** Match client effectiveSnoozed so agents and sidebar agree. */
162export function isSnoozed(
163 thread: Pick<
164 ProjectionStore.ProjectionSettlementCandidate,
165 | "snoozedUntil"
166 | "snoozedAt"
167 | "latestRunCompletedAt"
168 | "status"
169 | "pendingRuntimeRequest"
170 | "pendingGuestMessageCount"
171 >,
172 nowMs: number,
173): boolean {
174 const snoozedUntilMs = toMillis(thread.snoozedUntil);
175 if (snoozedUntilMs === null || snoozedUntilMs <= nowMs) return false;
176 if (thread.pendingRuntimeRequest !== null) return false;
177 // Same as the client: a waiting guest message wakes the thread, and the snooze stays stored.
178 if ((thread.pendingGuestMessageCount ?? 0) > 0) return false;
179 const snoozedAtMs = toMillis(thread.snoozedAt);
180 const completedAtMs = toMillis(thread.latestRunCompletedAt);
181 const wokeOnError =
182 thread.status === "failed" &&
183 (snoozedAtMs === null || (completedAtMs !== null && completedAtMs > snoozedAtMs));
184 return !wokeOnError;
185}
186
187export function resolveAutoSettlementAt(input: {
188 readonly thread: ProjectionStore.ProjectionSettlementCandidate;
189 readonly pullRequest: SettlementPullRequest | null;
190 readonly nowMs: number;
191 readonly autoSettleAfterDays: number | null;
192 readonly autoSettleOnMerge: boolean;
193 readonly autoSettleKeepPullRequests?: boolean;
194}): DateTime.Utc | null {
195 const { thread } = input;
196 let pullRequest = input.pullRequest;
197 const links = settlementPullRequestLinks(thread.pullRequests ?? []);
198 if (links.some((link) => link.snapshot === null)) return null;
199 // An open link means the pull request has not finished, so only inactivity
200 // can settle the thread, never a merged or closed lookup.
201 const hasOpenLink = links.some((link) => link.snapshot?.state === "open");
202 if (hasOpenLink) {
203 pullRequest = null;
204 } else if (links.length > 0) {
205 const latest = links.reduce((current, candidate) =>
206 linkTerminalAtMs(candidate) > linkTerminalAtMs(current) ? candidate : current,
207 );
208 pullRequest =
209 latest.snapshot === null
210 ? null
211 : {
212 state: latest.snapshot.state,
213 mergedAt: latest.snapshot.mergedAt ?? null,
214 closedAt: latest.snapshot.closedAt ?? null,
215 };
216 }
217 if (!isAutoSettlementCandidate(thread, input.nowMs)) return null;
218 const activityAtMs =
219 latestMillis([
220 toMillis(thread.latestUserMessageAt),
221 toMillis(thread.latestRunRequestedAt),
222 toMillis(thread.latestRunStartedAt),
223 toMillis(thread.latestRunCompletedAt),
224 ]) ?? DateTime.toEpochMillis(thread.createdAt);
225 if (pullRequest !== null && pullRequestSettles(thread, pullRequest, input.autoSettleOnMerge)) {
226 return DateTime.makeUnsafe(activityAtMs);
227 }
228 const hasPullRequest =
229 hasOpenLink ||
230 pullRequest !== null ||
231 thread.linkedPullRequest != null ||
232 thread.branchPullRequest != null;
233 if (input.autoSettleKeepPullRequests === true && hasPullRequest) return null;
234 if (input.autoSettleAfterDays === null) return null;
235 const snoozedUntilMs = toMillis(thread.snoozedUntil);
236 const timerWakeAtMs =
237 snoozedUntilMs !== null && snoozedUntilMs <= input.nowMs ? snoozedUntilMs : null;
238 const inactivityAtMs =
239 latestMillis([activityAtMs, toMillis(thread.lastSnoozeWakeAt), timerWakeAtMs]) ?? activityAtMs;
240 return inactivityAtMs < input.nowMs - input.autoSettleAfterDays * DAY_MS
241 ? DateTime.makeUnsafe(inactivityAtMs)
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/** @internal Exported for tests. */
265export function autoSettlementSettingsKey(
266 settings: import("@t3tools/contracts").ServerSettings,
267): string {
268 return JSON.stringify([
269 settings.sidebarAutoSettleOnMerge,
270 settings.sidebarAutoSettleAfterDays,
271 settings.sidebarAutoSettleKeepPullRequests,
272 Object.entries(settings.projectSettingsOverrides)
273 .filter(
274 ([, entry]) =>
275 entry.sidebarAutoSettleOnMerge !== undefined ||
276 entry.sidebarAutoSettleAfterDays !== undefined ||
277 entry.sidebarAutoSettleKeepPullRequests !== undefined,
278 )
279 .sort(([left], [right]) => left.localeCompare(right))
280 .map(([projectId, entry]) => [
281 projectId,
282 entry.sidebarAutoSettleOnMerge ?? "inherit",
283 entry.sidebarAutoSettleAfterDays === undefined
284 ? "inherit"
285 : entry.sidebarAutoSettleAfterDays,
286 entry.sidebarAutoSettleKeepPullRequests ?? "inherit",
287 ]),
288 ]);
289}
290
291export const make = Effect.gen(function* () {
292 const orchestrator = yield* Orchestrator.OrchestratorV2;
293 const projections = yield* ProjectionStore.ProjectionStoreV2;
294 const projectStore = yield* ProjectStore.ProjectStoreV2;
295 const settingsService = yield* ServerSettings.ServerSettingsService;
296 const git = yield* GitManager.GitManager;
297 const pullRequests = yield* PullRequestService.PullRequestService;
298 const crypto = yield* Crypto.Crypto;
299 const fileSystem = yield* FileSystem.FileSystem;
300 // A shell merge or close sends no event, and the branch lookup caches an open pull request for
301 // a minute, so these threads' next lookup reads the host fresh.
302 const shellClosedThreads = new Set<ThreadId>();
303 const terminals = yield* TerminalManager.TerminalManager;
304 const projectScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
305 // Repeated thread.settled retains settledAt; run the action only once per settlement.
306 const settleActionRunAt = new Map<ThreadId, number>();
307
308 const sweep = Effect.fn("ThreadSettlementServiceV2.sweep")(function* (
309 mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
310 threadId?: ThreadId,
311 ) {
312 const settings = yield* settingsService.getSettings;
313 if (!autoSettlementConfigured(settings)) {
314 return;
315 }
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 // Merge events resweep all candidates because unlinked threads settle through branch lookup.
322 const candidates = threads.filter((thread) => isAutoSettlementCandidate(thread, nowMs));
323
324 const settleThread = Effect.fn("ThreadSettlementServiceV2.settleThread")(
325 function* (thread: (typeof candidates)[number], pullRequest: SettlementPullRequest | null) {
326 const currentSettings = resolveProjectSettings(
327 yield* settingsService.getSettings,
328 thread.projectId,
329 ).settings;
330 const decisionNow = yield* DateTime.now;
331 const settledAt = resolveAutoSettlementAt({
332 thread,
333 pullRequest,
334 nowMs: DateTime.toEpochMillis(decisionNow),
335 autoSettleAfterDays: currentSettings.sidebarAutoSettleAfterDays,
336 autoSettleOnMerge: currentSettings.sidebarAutoSettleOnMerge,
337 autoSettleKeepPullRequests: currentSettings.sidebarAutoSettleKeepPullRequests,
338 });
339 if (settledAt === null) return thread;
340 const uuid = yield* crypto.randomUUIDv4();
341 yield* orchestrator.dispatch({
342 type: "thread.auto-settle",
343 commandId: CommandId.make(`server:auto-settle:${thread.id}:${uuid}`),
344 threadId: thread.id,
345 snapshotAt: thread.updatedAt,
346 settledAt,
347 });
348 return null;
349 },
350 (effect, thread) =>
351 effect.pipe(
352 Effect.catchCauseIf(
353 (cause) => !Cause.hasInterruptsOnly(cause),
354 (cause) =>
355 Effect.logWarning("automatic thread settlement skipped", {
356 threadId: thread.id,
357 cause: Cause.pretty(cause),
358 }).pipe(Effect.as(null)),
359 ),
360 ),
361 );
362
363 const lookupCandidates = (yield* Effect.forEach(
364 candidates,
365 (thread) => settleThread(thread, null),
366 { concurrency: 8 },
367 ))
368 .filter((thread) => thread !== null)
369 .filter((thread) => visibleThreadPullRequests(thread.pullRequests ?? []).length === 0);
370 const lookupCwdByThreadId = new Map<string, string>();
371 yield* Effect.forEach(
372 lookupCandidates,
373 (thread) =>
374 Effect.gen(function* () {
375 const project = projects.get(thread.projectId);
376 if (project === undefined || thread.branch === null) return;
377 const worktreeExists =
378 thread.worktreePath !== null &&
379 (yield* fileSystem.exists(thread.worktreePath).pipe(Effect.orElseSucceed(() => false)));
380 lookupCwdByThreadId.set(
381 thread.id,
382 worktreeExists && thread.worktreePath !== null
383 ? thread.worktreePath
384 : project.workspaceRoot,
385 );
386 }),
387 { concurrency: 8, discard: true },
388 );
389 if (mergedPullRequest !== null) {
390 // Invalidate checkout caches on merge; cached open branches would delay settlement beyond this sweep.
391 const cwds = [...new Set(lookupCwdByThreadId.values())];
392 yield* Effect.forEach(cwds, (cwd) => git.invalidateStatus(cwd), {
393 concurrency: 8,
394 discard: true,
395 });
396 }
397 const lookupKey = (thread: (typeof lookupCandidates)[number]) => {
398 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
399 if (reference != null) {
400 return JSON.stringify([
401 "linked",
402 reference.projectId,
403 reference.repository,
404 reference.number,
405 lookupCwdByThreadId.get(thread.id),
406 thread.branch,
407 ]);
408 }
409 if (thread.branch === null) return JSON.stringify(["none", thread.id]);
410 const cwd = lookupCwdByThreadId.get(thread.id);
411 return JSON.stringify(
412 cwd === undefined ? ["missing-project", thread.id] : ["branch", cwd, thread.branch],
413 );
414 };
415 const groups = Map.groupBy(lookupCandidates, lookupKey);
416
417 const wouldSettle = Effect.fn("ThreadSettlementServiceV2.wouldSettle")(function* (
418 group: ReadonlyArray<(typeof lookupCandidates)[number]>,
419 pullRequest: SettlementPullRequest,
420 ) {
421 const currentSettings = yield* settingsService.getSettings;
422 const decisionNow = yield* DateTime.now;
423 return group.some((thread) => {
424 const { settings } = resolveProjectSettings(currentSettings, thread.projectId);
425 return (
426 resolveAutoSettlementAt({
427 thread,
428 pullRequest,
429 nowMs: DateTime.toEpochMillis(decisionNow),
430 autoSettleAfterDays: settings.sidebarAutoSettleAfterDays,
431 autoSettleOnMerge: settings.sidebarAutoSettleOnMerge,
432 autoSettleKeepPullRequests: settings.sidebarAutoSettleKeepPullRequests,
433 }) !== null
434 );
435 });
436 });
437
438 const pullRequestFor = Effect.fn("ThreadSettlementServiceV2.pullRequestFor")(function* (
439 group: ReadonlyArray<(typeof lookupCandidates)[number]>,
440 ) {
441 const thread = group[0]!;
442 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
443 if (reference != null) {
444 // Only matching PR links settle from this merge event; unrelated links require fresh lookup.
445 const matchesMerge =
446 mergedPullRequest !== null &&
447 reference.projectId === mergedPullRequest.projectId &&
448 reference.repository.toLowerCase() === mergedPullRequest.repository.toLowerCase() &&
449 reference.number === mergedPullRequest.number;
450 if (!matchesMerge && !projects.has(reference.projectId)) {
451 return yield* Effect.die(new Error("linked pull request project not found"));
452 }
453 const summary = matchesMerge
454 ? ({
455 state: "merged",
456 closedAt: null,
457 mergedAt: mergedPullRequest.mergedAt,
458 } satisfies SettlementPullRequest)
459 : yield* pullRequests.summary(
460 {
461 projectId: reference.projectId,
462 repository: reference.repository,
463 number: reference.number,
464 },
465 { recoverTransientFailure: false },
466 );
467 const terminal = {
468 state: summary.state,
469 closedAt: summary.closedAt ?? null,
470 mergedAt: summary.mergedAt ?? null,
471 } satisfies SettlementPullRequest;
472 const cwd = lookupCwdByThreadId.get(thread.id);
473 if (summary.state !== "open" && thread.branch !== null && cwd !== undefined) {
474 if (!(yield* wouldSettle(group, terminal))) return undefined;
475 const current = yield* git.branchPullRequest(
476 { cwd, branch: thread.branch },
477 { refresh: true },
478 );
479 const project = projects.get(thread.projectId);
480 if (
481 current?.state === "open" &&
482 project !== undefined &&
483 pullRequestMatchesProject(current, project)
484 ) {
485 return current;
486 }
487 }
488 return terminal;
489 }
490 if (thread.branch === null) return null;
491 const cwd = lookupCwdByThreadId.get(thread.id);
492 if (cwd === undefined) {
493 return yield* Effect.die(new Error("thread project not found"));
494 }
495 const refresh = group.filter((member) => shellClosedThreads.delete(member.id)).length > 0;
496 return yield* git.branchPullRequest({ cwd, branch: thread.branch }, { refresh });
497 });
498
499 yield* Effect.forEach(
500 groups.values(),
501 (group) =>
502 Effect.gen(function* () {
503 const pullRequest = yield* pullRequestFor(group);
504 if (pullRequest === undefined) return;
505 yield* Effect.forEach(group, (thread) => settleThread(thread, pullRequest), {
506 discard: true,
507 });
508 }).pipe(
509 Effect.catchCauseIf(
510 (cause) => !Cause.hasInterruptsOnly(cause),
511 (cause) =>
512 Effect.logWarning("automatic thread settlement skipped", {
513 threadIds: group.map((thread) => thread.id),
514 cause: Cause.pretty(cause),
515 }),
516 ),
517 ),
518 { concurrency: 8, discard: true },
519 );
520 });
521
522 const runSweep = (
523 mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
524 threadId?: ThreadId,
525 ) =>
526 sweep(mergedPullRequest, threadId).pipe(
527 Effect.catchCauseIf(
528 (cause) => !Cause.hasInterruptsOnly(cause),
529 (cause) =>
530 Effect.logWarning("automatic thread settlement sweep failed", {
531 cause: Cause.pretty(cause),
532 }),
533 ),
534 );
535 // A thread that just stopped must not wait behind a full sweep or another thread's host
536 // reads: clients hold it in Working only briefly, so a late settle makes it appear and then vanish.
537 const fullSweeps = yield* makeDrainableWorker(() => runSweep(null));
538 const threadSweeps = yield* FiberSet.make<void>();
539 const threadSweepSlots = yield* Semaphore.make(8);
540 // One sweep per thread at a time; events during a running sweep coalesce into one more pass.
541 const threadSweepStates = new Map<ThreadId, "queued" | "running" | "rerun">();
542 const sweepThread = (
543 threadId: ThreadId,
544 ): Effect.Effect<void, Effect.Error<ReturnType<typeof runSweep>>> =>
545 Effect.sync(() => threadSweepStates.set(threadId, "running")).pipe(
546 Effect.andThen(runSweep(null, threadId)),
547 threadSweepSlots.withPermits(1),
548 Effect.andThen(
549 Effect.suspend(() => {
550 if (threadSweepStates.get(threadId) === "rerun") return sweepThread(threadId);
551 threadSweepStates.delete(threadId);
552 return Effect.void;
553 }),
554 ),
555 );
556 const enqueueThread = (threadId: ThreadId) =>
557 Effect.suspend(() => {
558 const state = threadSweepStates.get(threadId);
559 if (state === "running") threadSweepStates.set(threadId, "rerun");
560 if (state !== undefined) return Effect.void;
561 threadSweepStates.set(threadId, "queued");
562 return sweepThread(threadId).pipe(FiberSet.run(threadSweeps), Effect.asVoid);
563 });
564
565 // Skip settle scripts in shared checkouts where other threads may still work.
566 const cleanUpSettledThread = Effect.fn("ThreadSettlementServiceV2.cleanUpSettledThread")(
567 function* (threadId: ThreadId) {
568 const settled = yield* projections.getThread(threadId);
569 if (settled.settledOverride !== "settled") return;
570 yield* terminals.closeIdle({ threadId });
571 const worktreePath = settled.worktreePath;
572 if (worktreePath === null || !(yield* fileSystem.exists(worktreePath))) return;
573 // Recheck after closing and worktree I/O; re-engaged threads must not be cleaned up.
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 observeCompletion: {},
584 });
585 settleActionRunAt.set(threadId, settledAtMs);
586 if (run.status === "started" && run.completion) {
587 yield* run.completion.pipe(Effect.forkDetach);
588 }
589 },
590 (effect, threadId) =>
591 effect.pipe(
592 Effect.catchCauseIf(
593 (cause) => !Cause.hasInterruptsOnly(cause),
594 (cause) =>
595 Effect.logWarning("cleaning up a settled thread failed", {
596 threadId,
597 cause: Cause.pretty(cause),
598 }),
599 ),
600 ),
601 );
602
603 const processEvent = (event: OrchestrationV2DomainEvent) => {
604 switch (event.type) {
605 case "thread.settled":
606 return cleanUpSettledThread(event.threadId);
607 case "thread.pull-request-link-updated":
608 case "thread.pull-request-synced":
609 case "provider-session.detached":
610 case "run.background-work-cancelled":
611 return enqueueThread(event.threadId);
612 // Sweep only when the work can have ended: progress updates cannot settle anything.
613 case "subagent.updated":
614 return isOrchestrationV2WorkActive(event.payload.status)
615 ? Effect.void
616 : enqueueThread(event.threadId);
617 case "provider-thread.updated":
618 return backgroundWorkHoldsCompletion(event.payload.pendingBackgroundTasks ?? [])
619 ? Effect.void
620 : enqueueThread(event.threadId);
621 case "turn-item.updated": {
622 const item = event.payload;
623 if (
624 item.type === "command_execution" &&
625 !isOrchestrationV2WorkActive(item.status) &&
626 sourceControlDefinitions.definitions.some(
627 (definition) => definition.changeRequestCloseCommand?.test(item.input) === true,
628 )
629 ) {
630 shellClosedThreads.add(event.threadId);
631 }
632 return turnItemUpdateCanEndBackgroundWork(item)
633 ? enqueueThread(event.threadId)
634 : Effect.void;
635 }
636 case "provider-session.updated":
637 return event.payload.status !== "starting" && event.payload.status !== "running"
638 ? enqueueThread(event.threadId)
639 : Effect.void;
640 case "run.updated":
641 return ["completed", "interrupted", "failed", "cancelled", "rolled_back"].includes(
642 event.payload.status,
643 )
644 ? enqueueThread(event.threadId)
645 : Effect.void;
646 default:
647 return Effect.void;
648 }
649 };
650
651 const start: ThreadSettlementServiceV2["Service"]["start"] = Effect.fn(
652 "ThreadSettlementServiceV2.start",
653 )(function* () {
654 const settingsChanges = yield* settingsService.subscribeChanges;
655 const mergedPullRequests = yield* pullRequests.subscribeMerges;
656 const events = orchestrator.streamDomainEvents;
657 const initialSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
658 let lastSettlementSettings = autoSettlementSettingsKey(initialSettings);
659 yield* forkParked(
660 Effect.gen(function* () {
661 yield* fullSweeps.enqueue(undefined);
662 yield* fullSweeps.drain;
663 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
664 );
665 yield* forkParked(
666 Stream.runForEach(settingsChanges, (settings) => {
667 const key = autoSettlementSettingsKey(settings);
668 if (key === lastSettlementSettings) {
669 return Effect.void;
670 }
671 lastSettlementSettings = key;
672 return fullSweeps.enqueue(undefined);
673 }),
674 );
675 yield* forkParked(Stream.runForEach(mergedPullRequests, (event) => runSweep(event)));
676 yield* forkParked(
677 Stream.runForEach(events, processEvent).pipe(
678 Effect.catchCause((cause) =>
679 Effect.logWarning("Thread settlement event stream failed", { cause }),
680 ),
681 ),
682 );
683 });
684
685 return {
686 start,
687 drain: Effect.andThen(fullSweeps.drain, FiberSet.awaitEmpty(threadSweeps)),
688 } satisfies ThreadSettlementServiceV2["Service"];
689});