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