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

ThreadSettlementService.ts

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