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