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

ThreadSettlementService.ts

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