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