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 SecureRandom from "effect/crypto/SecureRandom";
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 Path from "effect/Path";
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 // 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 if (
181 thread.pendingRuntimeRequest !== null &&
182 (thread.pendingRuntimeRequest.kind !== "user_input" ||
183 snoozedAtMs === null ||
184 DateTime.toEpochMillis(thread.pendingRuntimeRequest.createdAt) > snoozedAtMs)
185 ) {
186 return false;
187 }
188 const completedAtMs = toMillis(thread.latestRunCompletedAt);
189 const wokeOnError =
190 thread.status === "failed" &&
191 (snoozedAtMs === null || (completedAtMs !== null && completedAtMs > snoozedAtMs));
192 return !wokeOnError;
193}
194
195export function resolveAutoSettlementAt(input: {
196 readonly thread: ProjectionStore.ProjectionSettlementCandidate;
197 readonly pullRequest: SettlementPullRequest | null;
198 readonly nowMs: number;
199 readonly autoSettleAfterDays: number | null;
200 readonly autoSettleOnMerge: boolean;
201 readonly autoSettleKeepPullRequests?: boolean;
202}): DateTime.Utc | null {
203 const { thread } = input;
204 let pullRequest = input.pullRequest;
205 const links = settlementPullRequestLinks(thread.pullRequests ?? []);
206 if (links.some((link) => link.snapshot === null)) return null;
207 // An open link means the pull request has not finished, so only inactivity
208 // can settle the thread, never a merged or closed lookup.
209 const hasOpenLink = links.some((link) => link.snapshot?.state === "open");
210 if (hasOpenLink) {
211 pullRequest = null;
212 } else if (links.length > 0) {
213 const latest = links.reduce((current, candidate) =>
214 linkTerminalAtMs(candidate) > linkTerminalAtMs(current) ? candidate : current,
215 );
216 pullRequest =
217 latest.snapshot === null
218 ? null
219 : {
220 state: latest.snapshot.state,
221 mergedAt: latest.snapshot.mergedAt ?? null,
222 closedAt: latest.snapshot.closedAt ?? null,
223 };
224 }
225 if (!isAutoSettlementCandidate(thread, input.nowMs)) return null;
226 const activityAtMs =
227 latestMillis([
228 toMillis(thread.latestUserMessageAt),
229 toMillis(thread.latestRunRequestedAt),
230 toMillis(thread.latestRunStartedAt),
231 toMillis(thread.latestRunCompletedAt),
232 ]) ?? DateTime.toEpochMillis(thread.createdAt);
233 if (pullRequest !== null && pullRequestSettles(thread, pullRequest, input.autoSettleOnMerge)) {
234 return DateTime.makeUnsafe(activityAtMs);
235 }
236 const hasPullRequest =
237 hasOpenLink ||
238 pullRequest !== null ||
239 thread.linkedPullRequest != null ||
240 thread.branchPullRequest != null;
241 if (input.autoSettleKeepPullRequests === true && hasPullRequest) return null;
242 if (input.autoSettleAfterDays === null) return null;
243 const snoozedUntilMs = toMillis(thread.snoozedUntil);
244 const timerWakeAtMs =
245 snoozedUntilMs !== null && snoozedUntilMs <= input.nowMs ? snoozedUntilMs : null;
246 const inactivityAtMs =
247 latestMillis([activityAtMs, toMillis(thread.lastSnoozeWakeAt), timerWakeAtMs]) ?? activityAtMs;
248 return inactivityAtMs < input.nowMs - input.autoSettleAfterDays * DAY_MS
249 ? DateTime.makeUnsafe(inactivityAtMs)
250 : null;
251}
252
253export class ThreadSettlementServiceV2 extends Context.Service<
254 ThreadSettlementServiceV2,
255 {
256 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
257 readonly drain: Effect.Effect<void>;
258 }
259>()("t3/orchestration-v2/ThreadSettlementService/ThreadSettlementServiceV2") {}
260
261function autoSettlementConfigured(settings: import("@t3tools/contracts").ServerSettings): boolean {
262 if (settings.sidebarAutoSettleOnMerge || settings.sidebarAutoSettleAfterDays !== null) {
263 return true;
264 }
265 return Object.values(settings.projectSettingsOverrides).some(
266 (entry) =>
267 entry.sidebarAutoSettleOnMerge === true ||
268 (entry.sidebarAutoSettleAfterDays !== undefined && entry.sidebarAutoSettleAfterDays !== null),
269 );
270}
271
272/** @internal Exported for tests. */
273export function autoSettlementSettingsKey(
274 settings: import("@t3tools/contracts").ServerSettings,
275): string {
276 return JSON.stringify([
277 settings.sidebarAutoSettleOnMerge,
278 settings.sidebarAutoSettleAfterDays,
279 settings.sidebarAutoSettleKeepPullRequests,
280 Object.entries(settings.projectSettingsOverrides)
281 .filter(
282 ([, entry]) =>
283 entry.sidebarAutoSettleOnMerge !== undefined ||
284 entry.sidebarAutoSettleAfterDays !== undefined ||
285 entry.sidebarAutoSettleKeepPullRequests !== 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 entry.sidebarAutoSettleKeepPullRequests ?? "inherit",
295 ]),
296 ]);
297}
298
299export const make = Effect.gen(function* () {
300 const orchestrator = yield* Orchestrator.OrchestratorV2;
301 const projections = yield* ProjectionStore.ProjectionStoreV2;
302 const projectStore = yield* ProjectStore.ProjectStoreV2;
303 const settingsService = yield* ServerSettings.ServerSettingsService;
304 const git = yield* GitManager.GitManager;
305 const pullRequests = yield* PullRequestService.PullRequestService;
306 const random = yield* SecureRandom.SecureRandom;
307 const fileSystem = yield* FileSystem.FileSystem;
308 const path = yield* Path.Path;
309 // A shell merge or close sends no event, and the branch lookup caches an open pull request for
310 // a minute, so these threads' next lookup reads the host fresh.
311 const shellClosedThreads = new Set<ThreadId>();
312 const terminals = yield* TerminalManager.TerminalManager;
313 const projectScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
314 // Repeated thread.settled retains settledAt; run the action only once per settlement.
315 const settleActionRunAt = new Map<ThreadId, number>();
316
317 const sweep = Effect.fn("ThreadSettlementServiceV2.sweep")(function* (
318 mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
319 threadId?: ThreadId,
320 ) {
321 const settings = yield* settingsService.getSettings;
322 if (!autoSettlementConfigured(settings)) {
323 return;
324 }
325 const threads = yield* projections.getSettlementCandidates(threadId);
326 if (threads.length === 0) return;
327 const projectShells = yield* projectStore.listShells();
328 const nowMs = DateTime.toEpochMillis(yield* DateTime.now);
329 const projects = new Map(projectShells.map((project) => [project.id, project]));
330 // Merge events resweep all candidates because unlinked threads settle through branch lookup.
331 const candidates = threads.filter((thread) => isAutoSettlementCandidate(thread, nowMs));
332
333 // Runs per candidate thread, thousands per sweep on busy servers; the sweep owns the span.
334 const settleThread = Effect.fnUntraced(
335 function* (thread: (typeof candidates)[number], pullRequest: SettlementPullRequest | null) {
336 // thread.auto-settle does not recheck settings, so read them per decision; reads are cached.
337 const currentSettings = resolveProjectSettings(
338 yield* settingsService.getSettings,
339 thread.projectId,
340 ).settings;
341 const decisionNow = yield* DateTime.now;
342 const settledAt = resolveAutoSettlementAt({
343 thread,
344 pullRequest,
345 nowMs: DateTime.toEpochMillis(decisionNow),
346 autoSettleAfterDays: currentSettings.sidebarAutoSettleAfterDays,
347 autoSettleOnMerge: currentSettings.sidebarAutoSettleOnMerge,
348 autoSettleKeepPullRequests: currentSettings.sidebarAutoSettleKeepPullRequests,
349 });
350 if (settledAt === null) return thread;
351 const uuid = yield* random.uuidV4();
352 yield* orchestrator.dispatch({
353 type: "thread.auto-settle",
354 commandId: CommandId.make(`server:auto-settle:${thread.id}:${uuid}`),
355 threadId: thread.id,
356 snapshotAt: thread.updatedAt,
357 settledAt,
358 });
359 return null;
360 },
361 (effect, thread) =>
362 effect.pipe(
363 Effect.catchCauseIf(
364 (cause) => !Cause.hasInterruptsOnly(cause),
365 (cause) =>
366 Effect.logWarning("automatic thread settlement skipped", {
367 threadId: thread.id,
368 cause: Cause.pretty(cause),
369 }).pipe(Effect.as(null)),
370 ),
371 ),
372 );
373
374 const lookupCandidates = (yield* Effect.forEach(
375 candidates,
376 (thread) => {
377 const projectSettings = resolveProjectSettings(settings, thread.projectId).settings;
378 // Skip no-op decisions; actual settlement still reads fresh settings before dispatch.
379 const settledAt = resolveAutoSettlementAt({
380 thread,
381 pullRequest: null,
382 nowMs,
383 autoSettleAfterDays: projectSettings.sidebarAutoSettleAfterDays,
384 autoSettleOnMerge: projectSettings.sidebarAutoSettleOnMerge,
385 autoSettleKeepPullRequests: projectSettings.sidebarAutoSettleKeepPullRequests,
386 });
387 return settledAt === null ? Effect.succeed(thread) : settleThread(thread, null);
388 },
389 { concurrency: 8 },
390 ))
391 .filter((thread) => thread !== null)
392 .filter((thread) => visibleThreadPullRequests(thread.pullRequests ?? []).length === 0)
393 .filter(
394 (thread) =>
395 thread.branch !== null ||
396 thread.linkedPullRequest != null ||
397 thread.branchPullRequest != null,
398 );
399 const lookupCwdByThreadId = new Map<string, string>();
400 yield* Effect.forEach(
401 lookupCandidates,
402 (thread) =>
403 Effect.gen(function* () {
404 const project = projects.get(thread.projectId);
405 if (project === undefined || thread.branch === null) return;
406 // A worktree folder can outlive its .git, and git there fails with not_a_repository.
407 // An unreadable .git keeps the worktree, so git fails there and the thread is skipped.
408 lookupCwdByThreadId.set(
409 thread.id,
410 thread.worktreePath !== null &&
411 (yield* fileSystem
412 .exists(path.join(thread.worktreePath, ".git"))
413 .pipe(Effect.orElseSucceed(() => true)))
414 ? thread.worktreePath
415 : project.workspaceRoot,
416 );
417 }),
418 { concurrency: 8, discard: true },
419 );
420 if (mergedPullRequest !== null) {
421 // Invalidate checkout caches on merge; cached open branches would delay settlement beyond this sweep.
422 const cwds = [...new Set(lookupCwdByThreadId.values())];
423 yield* Effect.forEach(cwds, (cwd) => git.invalidateStatus(cwd), {
424 concurrency: 8,
425 discard: true,
426 });
427 }
428 const lookupKey = (thread: (typeof lookupCandidates)[number]) => {
429 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
430 if (reference != null) {
431 return JSON.stringify([
432 "linked",
433 reference.projectId,
434 reference.repository,
435 reference.number,
436 lookupCwdByThreadId.get(thread.id),
437 thread.branch,
438 ]);
439 }
440 if (thread.branch === null) return JSON.stringify(["none", thread.id]);
441 const cwd = lookupCwdByThreadId.get(thread.id);
442 return JSON.stringify(
443 cwd === undefined ? ["missing-project", thread.id] : ["branch", cwd, thread.branch],
444 );
445 };
446 const groups = Map.groupBy(lookupCandidates, lookupKey);
447
448 // wouldSettle and pullRequestFor run per lookup group; the git and pull request reads they make carry the spans.
449 const wouldSettle = Effect.fnUntraced(function* (
450 group: ReadonlyArray<(typeof lookupCandidates)[number]>,
451 pullRequest: SettlementPullRequest,
452 ) {
453 const currentSettings = yield* settingsService.getSettings;
454 const decisionNow = yield* DateTime.now;
455 return group.some((thread) => {
456 const { settings } = resolveProjectSettings(currentSettings, thread.projectId);
457 return (
458 resolveAutoSettlementAt({
459 thread,
460 pullRequest,
461 nowMs: DateTime.toEpochMillis(decisionNow),
462 autoSettleAfterDays: settings.sidebarAutoSettleAfterDays,
463 autoSettleOnMerge: settings.sidebarAutoSettleOnMerge,
464 autoSettleKeepPullRequests: settings.sidebarAutoSettleKeepPullRequests,
465 }) !== null
466 );
467 });
468 });
469
470 const pullRequestFor = Effect.fnUntraced(function* (
471 group: ReadonlyArray<(typeof lookupCandidates)[number]>,
472 ) {
473 const thread = group[0]!;
474 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
475 if (reference != null) {
476 // Only matching PR links settle from this merge event; unrelated links require fresh lookup.
477 const matchesMerge =
478 mergedPullRequest !== null &&
479 reference.projectId === mergedPullRequest.projectId &&
480 reference.repository.toLowerCase() === mergedPullRequest.repository.toLowerCase() &&
481 reference.number === mergedPullRequest.number;
482 if (!matchesMerge && !projects.has(reference.projectId)) {
483 return yield* Effect.die(new Error("linked pull request project not found"));
484 }
485 const summary = matchesMerge
486 ? ({
487 state: "merged",
488 closedAt: null,
489 mergedAt: mergedPullRequest.mergedAt,
490 } satisfies SettlementPullRequest)
491 : yield* pullRequests.summary(
492 {
493 projectId: reference.projectId,
494 repository: reference.repository,
495 number: reference.number,
496 },
497 { recoverTransientFailure: false },
498 );
499 const terminal = {
500 state: summary.state,
501 closedAt: summary.closedAt ?? null,
502 mergedAt: summary.mergedAt ?? null,
503 } satisfies SettlementPullRequest;
504 const cwd = lookupCwdByThreadId.get(thread.id);
505 if (summary.state !== "open" && thread.branch !== null && cwd !== undefined) {
506 if (!(yield* wouldSettle(group, terminal))) return undefined;
507 const current = yield* git.branchPullRequest(
508 { cwd, branch: thread.branch },
509 { refresh: true },
510 );
511 const project = projects.get(thread.projectId);
512 if (
513 current?.state === "open" &&
514 project !== undefined &&
515 pullRequestMatchesProject(current, project)
516 ) {
517 return current;
518 }
519 }
520 return terminal;
521 }
522 if (thread.branch === null) return null;
523 const cwd = lookupCwdByThreadId.get(thread.id);
524 if (cwd === undefined) {
525 return yield* Effect.die(new Error("thread project not found"));
526 }
527 const refresh = group.filter((member) => shellClosedThreads.delete(member.id)).length > 0;
528 return yield* git.branchPullRequest({ cwd, branch: thread.branch }, { refresh });
529 });
530
531 yield* Effect.forEach(
532 groups.values(),
533 (group) =>
534 Effect.gen(function* () {
535 const pullRequest = yield* pullRequestFor(group);
536 if (pullRequest === undefined) return;
537 yield* Effect.forEach(group, (thread) => settleThread(thread, pullRequest), {
538 discard: true,
539 });
540 }).pipe(
541 Effect.catchCauseIf(
542 (cause) => !Cause.hasInterruptsOnly(cause),
543 (cause) =>
544 Effect.logWarning("automatic thread settlement skipped", {
545 threadIds: group.map((thread) => thread.id),
546 cause: Cause.pretty(cause),
547 }),
548 ),
549 ),
550 { concurrency: 8, discard: true },
551 );
552 });
553
554 const runSweep = (
555 mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
556 threadId?: ThreadId,
557 ) =>
558 sweep(mergedPullRequest, threadId).pipe(
559 Effect.catchCauseIf(
560 (cause) => !Cause.hasInterruptsOnly(cause),
561 (cause) =>
562 Effect.logWarning("automatic thread settlement sweep failed", {
563 cause: Cause.pretty(cause),
564 }),
565 ),
566 );
567 // A thread that just stopped must not wait behind a full sweep or another thread's host
568 // reads: clients hold it in Working only briefly, so a late settle makes it appear and then vanish.
569 const fullSweeps = yield* makeDrainableWorker(() => runSweep(null));
570 const threadSweeps = yield* FiberSet.make<void>();
571 const threadSweepSlots = yield* Semaphore.make(8);
572 // One sweep per thread at a time; events during a running sweep coalesce into one more pass.
573 const threadSweepStates = new Map<ThreadId, "queued" | "running" | "rerun">();
574 const sweepThread = (
575 threadId: ThreadId,
576 ): Effect.Effect<void, Effect.Error<ReturnType<typeof runSweep>>> =>
577 Effect.sync(() => threadSweepStates.set(threadId, "running")).pipe(
578 Effect.andThen(runSweep(null, threadId)),
579 threadSweepSlots.withPermits(1),
580 Effect.andThen(
581 Effect.suspend(() => {
582 if (threadSweepStates.get(threadId) === "rerun") return sweepThread(threadId);
583 threadSweepStates.delete(threadId);
584 return Effect.void;
585 }),
586 ),
587 );
588 const enqueueThread = (threadId: ThreadId) =>
589 Effect.suspend(() => {
590 const state = threadSweepStates.get(threadId);
591 if (state === "running") threadSweepStates.set(threadId, "rerun");
592 if (state !== undefined) return Effect.void;
593 threadSweepStates.set(threadId, "queued");
594 return sweepThread(threadId).pipe(FiberSet.run(threadSweeps), Effect.asVoid);
595 });
596
597 // Skip settle scripts in shared checkouts where other threads may still work.
598 const cleanUpSettledThread = Effect.fn("ThreadSettlementServiceV2.cleanUpSettledThread")(
599 function* (threadId: ThreadId) {
600 const settled = yield* projections.getThread(threadId);
601 if (settled.settledOverride !== "settled") return;
602 yield* terminals.closeOnSettle({ threadId });
603 const worktreePath = settled.worktreePath;
604 if (worktreePath === null || !(yield* fileSystem.exists(worktreePath))) return;
605 // Recheck after closing and worktree I/O; re-engaged threads must not be cleaned up.
606 const thread = yield* projections.getThread(threadId);
607 if (thread.settledOverride !== "settled") return;
608 const settledAtMs = toMillis(thread.settledAt);
609 if (settledAtMs === null || settleActionRunAt.get(threadId) === settledAtMs) return;
610 const run = yield* projectScripts.runForThread({
611 threadId,
612 projectId: thread.projectId,
613 worktreePath,
614 trigger: "settle",
615 observeCompletion: {},
616 });
617 settleActionRunAt.set(threadId, settledAtMs);
618 if (run.status === "started" && run.completion) {
619 yield* run.completion.pipe(Effect.forkDetach);
620 }
621 },
622 (effect, threadId) =>
623 effect.pipe(
624 Effect.catchCauseIf(
625 (cause) => !Cause.hasInterruptsOnly(cause),
626 (cause) =>
627 Effect.logWarning("cleaning up a settled thread failed", {
628 threadId,
629 cause: Cause.pretty(cause),
630 }),
631 ),
632 ),
633 );
634
635 const processEvent = (event: OrchestrationV2DomainEvent) => {
636 switch (event.type) {
637 case "thread.settled":
638 return cleanUpSettledThread(event.threadId);
639 case "thread.pull-request-link-updated":
640 case "thread.pull-request-synced":
641 case "provider-session.detached":
642 case "run.background-work-cancelled":
643 return enqueueThread(event.threadId);
644 // Sweep only when the work can have ended: progress updates cannot settle anything.
645 case "subagent.updated":
646 return isOrchestrationV2WorkActive(event.payload.status)
647 ? Effect.void
648 : enqueueThread(event.threadId);
649 case "provider-thread.updated":
650 return backgroundWorkHoldsCompletion(event.payload.pendingBackgroundTasks ?? [])
651 ? Effect.void
652 : enqueueThread(event.threadId);
653 case "turn-item.updated": {
654 const item = event.payload;
655 if (
656 item.type === "command_execution" &&
657 !isOrchestrationV2WorkActive(item.status) &&
658 sourceControlDefinitions.definitions.some(
659 (definition) => definition.changeRequestCloseCommand?.test(item.input) === true,
660 )
661 ) {
662 shellClosedThreads.add(event.threadId);
663 }
664 return turnItemUpdateCanEndBackgroundWork(item)
665 ? enqueueThread(event.threadId)
666 : Effect.void;
667 }
668 case "provider-session.updated":
669 return event.payload.status !== "starting" && event.payload.status !== "running"
670 ? enqueueThread(event.threadId)
671 : Effect.void;
672 case "run.updated":
673 return ["completed", "interrupted", "failed", "cancelled", "rolled_back"].includes(
674 event.payload.status,
675 )
676 ? enqueueThread(event.threadId)
677 : Effect.void;
678 default:
679 return Effect.void;
680 }
681 };
682
683 const start: ThreadSettlementServiceV2["Service"]["start"] = Effect.fn(
684 "ThreadSettlementServiceV2.start",
685 )(function* () {
686 const settingsChanges = yield* settingsService.subscribeChanges;
687 const mergedPullRequests = yield* pullRequests.subscribeMerges;
688 const events = orchestrator.streamDomainEvents;
689 const initialSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
690 let lastSettlementSettings = autoSettlementSettingsKey(initialSettings);
691 yield* forkParked(
692 Effect.gen(function* () {
693 yield* fullSweeps.enqueue(undefined);
694 yield* fullSweeps.drain;
695 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
696 );
697 yield* forkParked(
698 Stream.runForEach(settingsChanges, (settings) => {
699 const key = autoSettlementSettingsKey(settings);
700 if (key === lastSettlementSettings) {
701 return Effect.void;
702 }
703 lastSettlementSettings = key;
704 return fullSweeps.enqueue(undefined);
705 }),
706 );
707 yield* forkParked(Stream.runForEach(mergedPullRequests, (event) => runSweep(event)));
708 yield* forkParked(
709 Stream.runForEach(events, processEvent).pipe(
710 Effect.catchCause((cause) =>
711 Effect.logWarning("Thread settlement event stream failed", { cause }),
712 ),
713 ),
714 );
715 });
716
717 return {
718 start,
719 drain: Effect.andThen(fullSweeps.drain, FiberSet.awaitEmpty(threadSweeps)),
720 } satisfies ThreadSettlementServiceV2["Service"];
721});