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

ThreadSettlementService.ts

692 lines27.5 KB

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;
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);
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;
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 );
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;
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 });
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);
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;
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);
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;
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;
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 );
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 ]);
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 // Runs per candidate thread, thousands per sweep on busy servers; the sweep owns the span.
325 const settleThread = Effect.fnUntraced(
326 function* (thread: (typeof candidates)[number], pullRequest: SettlementPullRequest | null) {
327 // thread.auto-settle does not recheck settings, so read them per decision; reads are cached.
328 const currentSettings = resolveProjectSettings(
329 yield* settingsService.getSettings,
330 thread.projectId,
331 ).settings;
332 const decisionNow = yield* DateTime.now;
333 const settledAt = resolveAutoSettlementAt({
334 thread,
335 pullRequest,
336 nowMs: DateTime.toEpochMillis(decisionNow),
337 autoSettleAfterDays: currentSettings.sidebarAutoSettleAfterDays,
338 autoSettleOnMerge: currentSettings.sidebarAutoSettleOnMerge,
339 autoSettleKeepPullRequests: currentSettings.sidebarAutoSettleKeepPullRequests,
340 });
341 if (settledAt === null) return thread;
342 const uuid = yield* crypto.randomUUIDv4();
343 yield* orchestrator.dispatch({
344 type: "thread.auto-settle",
345 commandId: CommandId.make(`server:auto-settle:${thread.id}:${uuid}`),
346 threadId: thread.id,
347 snapshotAt: thread.updatedAt,
348 settledAt,
349 });
350 return null;
351 },
352 (effect, thread) =>
353 effect.pipe(
354 Effect.catchCauseIf(
355 (cause) => !Cause.hasInterruptsOnly(cause),
356 (cause) =>
357 Effect.logWarning("automatic thread settlement skipped", {
358 threadId: thread.id,
359 cause: Cause.pretty(cause),
360 }).pipe(Effect.as(null)),
361 ),
362 ),
363 );
364​
365 const lookupCandidates = (yield* Effect.forEach(
366 candidates,
367 (thread) => settleThread(thread, null),
368 { concurrency: 8 },
369 ))
370 .filter((thread) => thread !== null)
371 .filter((thread) => visibleThreadPullRequests(thread.pullRequests ?? []).length === 0);
372 const lookupCwdByThreadId = new Map<string, string>();
373 yield* Effect.forEach(
374 lookupCandidates,
375 (thread) =>
376 Effect.gen(function* () {
377 const project = projects.get(thread.projectId);
378 if (project === undefined || thread.branch === null) return;
379 const worktreeExists =
380 thread.worktreePath !== null &&
381 (yield* fileSystem.exists(thread.worktreePath).pipe(Effect.orElseSucceed(() => false)));
382 lookupCwdByThreadId.set(
383 thread.id,
384 worktreeExists && thread.worktreePath !== null
385 ? thread.worktreePath
386 : project.workspaceRoot,
387 );
388 }),
389 { concurrency: 8, discard: true },
390 );
391 if (mergedPullRequest !== null) {
392 // Invalidate checkout caches on merge; cached open branches would delay settlement beyond this sweep.
393 const cwds = [...new Set(lookupCwdByThreadId.values())];
394 yield* Effect.forEach(cwds, (cwd) => git.invalidateStatus(cwd), {
395 concurrency: 8,
396 discard: true,
397 });
398 }
399 const lookupKey = (thread: (typeof lookupCandidates)[number]) => {
400 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
401 if (reference != null) {
402 return JSON.stringify([
403 "linked",
404 reference.projectId,
405 reference.repository,
406 reference.number,
407 lookupCwdByThreadId.get(thread.id),
408 thread.branch,
409 ]);
410 }
411 if (thread.branch === null) return JSON.stringify(["none", thread.id]);
412 const cwd = lookupCwdByThreadId.get(thread.id);
413 return JSON.stringify(
414 cwd === undefined ? ["missing-project", thread.id] : ["branch", cwd, thread.branch],
415 );
416 };
417 const groups = Map.groupBy(lookupCandidates, lookupKey);
418​
419 // wouldSettle and pullRequestFor run per lookup group; the git and pull request reads they make carry the spans.
420 const wouldSettle = Effect.fnUntraced(function* (
421 group: ReadonlyArray<(typeof lookupCandidates)[number]>,
422 pullRequest: SettlementPullRequest,
423 ) {
424 const currentSettings = yield* settingsService.getSettings;
425 const decisionNow = yield* DateTime.now;
426 return group.some((thread) => {
427 const { settings } = resolveProjectSettings(currentSettings, thread.projectId);
428 return (
429 resolveAutoSettlementAt({
430 thread,
431 pullRequest,
432 nowMs: DateTime.toEpochMillis(decisionNow),
433 autoSettleAfterDays: settings.sidebarAutoSettleAfterDays,
434 autoSettleOnMerge: settings.sidebarAutoSettleOnMerge,
435 autoSettleKeepPullRequests: settings.sidebarAutoSettleKeepPullRequests,
436 }) !== null
437 );
438 });
439 });
440​
441 const pullRequestFor = Effect.fnUntraced(function* (
442 group: ReadonlyArray<(typeof lookupCandidates)[number]>,
443 ) {
444 const thread = group[0]!;
445 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
446 if (reference != null) {
447 // Only matching PR links settle from this merge event; unrelated links require fresh lookup.
448 const matchesMerge =
449 mergedPullRequest !== null &&
450 reference.projectId === mergedPullRequest.projectId &&
451 reference.repository.toLowerCase() === mergedPullRequest.repository.toLowerCase() &&
452 reference.number === mergedPullRequest.number;
453 if (!matchesMerge && !projects.has(reference.projectId)) {
454 return yield* Effect.die(new Error("linked pull request project not found"));
455 }
456 const summary = matchesMerge
457 ? ({
458 state: "merged",
459 closedAt: null,
460 mergedAt: mergedPullRequest.mergedAt,
461 } satisfies SettlementPullRequest)
462 : yield* pullRequests.summary(
463 {
464 projectId: reference.projectId,
465 repository: reference.repository,
466 number: reference.number,
467 },
468 { recoverTransientFailure: false },
469 );
470 const terminal = {
471 state: summary.state,
472 closedAt: summary.closedAt ?? null,
473 mergedAt: summary.mergedAt ?? null,
474 } satisfies SettlementPullRequest;
475 const cwd = lookupCwdByThreadId.get(thread.id);
476 if (summary.state !== "open" && thread.branch !== null && cwd !== undefined) {
477 if (!(yield* wouldSettle(group, terminal))) return undefined;
478 const current = yield* git.branchPullRequest(
479 { cwd, branch: thread.branch },
480 { refresh: true },
481 );
482 const project = projects.get(thread.projectId);
483 if (
484 current?.state === "open" &&
485 project !== undefined &&
486 pullRequestMatchesProject(current, project)
487 ) {
488 return current;
489 }
490 }
491 return terminal;
492 }
493 if (thread.branch === null) return null;
494 const cwd = lookupCwdByThreadId.get(thread.id);
495 if (cwd === undefined) {
496 return yield* Effect.die(new Error("thread project not found"));
497 }
498 const refresh = group.filter((member) => shellClosedThreads.delete(member.id)).length > 0;
499 return yield* git.branchPullRequest({ cwd, branch: thread.branch }, { refresh });
500 });
501​
502 yield* Effect.forEach(
503 groups.values(),
504 (group) =>
505 Effect.gen(function* () {
506 const pullRequest = yield* pullRequestFor(group);
507 if (pullRequest === undefined) return;
508 yield* Effect.forEach(group, (thread) => settleThread(thread, pullRequest), {
509 discard: true,
510 });
511 }).pipe(
512 Effect.catchCauseIf(
513 (cause) => !Cause.hasInterruptsOnly(cause),
514 (cause) =>
515 Effect.logWarning("automatic thread settlement skipped", {
516 threadIds: group.map((thread) => thread.id),
517 cause: Cause.pretty(cause),
518 }),
519 ),
520 ),
521 { concurrency: 8, discard: true },
522 );
523 });
524​
525 const runSweep = (
526 mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
527 threadId?: ThreadId,
528 ) =>
529 sweep(mergedPullRequest, threadId).pipe(
530 Effect.catchCauseIf(
531 (cause) => !Cause.hasInterruptsOnly(cause),
532 (cause) =>
533 Effect.logWarning("automatic thread settlement sweep failed", {
534 cause: Cause.pretty(cause),
535 }),
536 ),
537 );
538 // A thread that just stopped must not wait behind a full sweep or another thread's host
539 // reads: clients hold it in Working only briefly, so a late settle makes it appear and then vanish.
540 const fullSweeps = yield* makeDrainableWorker(() => runSweep(null));
541 const threadSweeps = yield* FiberSet.make<void>();
542 const threadSweepSlots = yield* Semaphore.make(8);
543 // One sweep per thread at a time; events during a running sweep coalesce into one more pass.
544 const threadSweepStates = new Map<ThreadId, "queued" | "running" | "rerun">();
545 const sweepThread = (
546 threadId: ThreadId,
547 ): Effect.Effect<void, Effect.Error<ReturnType<typeof runSweep>>> =>
548 Effect.sync(() => threadSweepStates.set(threadId, "running")).pipe(
549 Effect.andThen(runSweep(null, threadId)),
550 threadSweepSlots.withPermits(1),
551 Effect.andThen(
552 Effect.suspend(() => {
553 if (threadSweepStates.get(threadId) === "rerun") return sweepThread(threadId);
554 threadSweepStates.delete(threadId);
555 return Effect.void;
556 }),
557 ),
558 );
559 const enqueueThread = (threadId: ThreadId) =>
560 Effect.suspend(() => {
561 const state = threadSweepStates.get(threadId);
562 if (state === "running") threadSweepStates.set(threadId, "rerun");
563 if (state !== undefined) return Effect.void;
564 threadSweepStates.set(threadId, "queued");
565 return sweepThread(threadId).pipe(FiberSet.run(threadSweeps), Effect.asVoid);
566 });
567​
568 // Skip settle scripts in shared checkouts where other threads may still work.
569 const cleanUpSettledThread = Effect.fn("ThreadSettlementServiceV2.cleanUpSettledThread")(
570 function* (threadId: ThreadId) {
571 const settled = yield* projections.getThread(threadId);
572 if (settled.settledOverride !== "settled") return;
573 yield* terminals.closeIdle({ threadId });
574 const worktreePath = settled.worktreePath;
575 if (worktreePath === null || !(yield* fileSystem.exists(worktreePath))) return;
576 // Recheck after closing and worktree I/O; re-engaged threads must not be cleaned up.
577 const thread = yield* projections.getThread(threadId);
578 if (thread.settledOverride !== "settled") return;
579 const settledAtMs = toMillis(thread.settledAt);
580 if (settledAtMs === null || settleActionRunAt.get(threadId) === settledAtMs) return;
581 const run = yield* projectScripts.runForThread({
582 threadId,
583 projectId: thread.projectId,
584 worktreePath,
585 trigger: "settle",
586 observeCompletion: {},
587 });
588 settleActionRunAt.set(threadId, settledAtMs);
589 if (run.status === "started" && run.completion) {
590 yield* run.completion.pipe(Effect.forkDetach);
591 }
592 },
593 (effect, threadId) =>
594 effect.pipe(
595 Effect.catchCauseIf(
596 (cause) => !Cause.hasInterruptsOnly(cause),
597 (cause) =>
598 Effect.logWarning("cleaning up a settled thread failed", {
599 threadId,
600 cause: Cause.pretty(cause),
601 }),
602 ),
603 ),
604 );
605​
606 const processEvent = (event: OrchestrationV2DomainEvent) => {
607 switch (event.type) {
608 case "thread.settled":
609 return cleanUpSettledThread(event.threadId);
610 case "thread.pull-request-link-updated":
611 case "thread.pull-request-synced":
612 case "provider-session.detached":
613 case "run.background-work-cancelled":
614 return enqueueThread(event.threadId);
615 // Sweep only when the work can have ended: progress updates cannot settle anything.
616 case "subagent.updated":
617 return isOrchestrationV2WorkActive(event.payload.status)
618 ? Effect.void
619 : enqueueThread(event.threadId);
620 case "provider-thread.updated":
621 return backgroundWorkHoldsCompletion(event.payload.pendingBackgroundTasks ?? [])
622 ? Effect.void
623 : enqueueThread(event.threadId);
624 case "turn-item.updated": {
625 const item = event.payload;
626 if (
627 item.type === "command_execution" &&
628 !isOrchestrationV2WorkActive(item.status) &&
629 sourceControlDefinitions.definitions.some(
630 (definition) => definition.changeRequestCloseCommand?.test(item.input) === true,
631 )
632 ) {
633 shellClosedThreads.add(event.threadId);
634 }
635 return turnItemUpdateCanEndBackgroundWork(item)
636 ? enqueueThread(event.threadId)
637 : Effect.void;
638 }
639 case "provider-session.updated":
640 return event.payload.status !== "starting" && event.payload.status !== "running"
641 ? enqueueThread(event.threadId)
642 : Effect.void;
643 case "run.updated":
644 return ["completed", "interrupted", "failed", "cancelled", "rolled_back"].includes(
645 event.payload.status,
646 )
647 ? enqueueThread(event.threadId)
648 : Effect.void;
649 default:
650 return Effect.void;
651 }
652 };
653​
654 const start: ThreadSettlementServiceV2["Service"]["start"] = Effect.fn(
655 "ThreadSettlementServiceV2.start",
656 )(function* () {
657 const settingsChanges = yield* settingsService.subscribeChanges;
658 const mergedPullRequests = yield* pullRequests.subscribeMerges;
659 const events = orchestrator.streamDomainEvents;
660 const initialSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
661 let lastSettlementSettings = autoSettlementSettingsKey(initialSettings);
662 yield* forkParked(
663 Effect.gen(function* () {
664 yield* fullSweeps.enqueue(undefined);
665 yield* fullSweeps.drain;
666 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
667 );
668 yield* forkParked(
669 Stream.runForEach(settingsChanges, (settings) => {
670 const key = autoSettlementSettingsKey(settings);
671 if (key === lastSettlementSettings) {
672 return Effect.void;
673 }
674 lastSettlementSettings = key;
675 return fullSweeps.enqueue(undefined);
676 }),
677 );
678 yield* forkParked(Stream.runForEach(mergedPullRequests, (event) => runSweep(event)));
679 yield* forkParked(
680 Stream.runForEach(events, processEvent).pipe(
681 Effect.catchCause((cause) =>
682 Effect.logWarning("Thread settlement event stream failed", { cause }),
683 ),
684 ),
685 );
686 });
687​
688 return {
689 start,
690 drain: Effect.andThen(fullSweeps.drain, FiberSet.awaitEmpty(threadSweeps)),
691 } satisfies ThreadSettlementServiceV2["Service"];
692});