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