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

ThreadSettlementService.ts

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