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