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 isOrchestrationV2WorkActive,
12 type ThreadId,
13 type OrchestrationV2DomainEvent,
14 type OrchestrationV2ThreadShell,
15} from "@t3tools/contracts";
16import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
17import * as Cause from "effect/Cause";
18import * as Context from "effect/Context";
19import * as SecureRandom from "effect/crypto/SecureRandom";
20import * as DateTime from "effect/DateTime";
21import * as Effect from "effect/Effect";
22import * as FiberSet from "effect/FiberSet";
23import * as FileSystem from "effect/FileSystem";
24import * as Option from "effect/Option";
25import * as Path from "effect/Path";
26import * as Schedule from "effect/Schedule";
27import * as Semaphore from "effect/Semaphore";
28import type * as Scope from "effect/Scope";
29import * as Stream from "effect/Stream";
30
31import * as GitManager from "../git/GitManager.ts";
32import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
33import * as PullRequestService from "../pullRequest/PullRequestService.ts";
34import * as ServerSettings from "../serverSettings.ts";
35import { forkParked } from "../serverActivation.ts";
36import * as TerminalManager from "../terminal/Manager.ts";
37import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
38import * as ProjectStore from "./ProjectStore.ts";
39import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
40import {
41 legacyThreadPullRequestKey,
42 threadPullRequestKeyOf,
43} from "../sourceControl/threadPullRequests.ts";
44import { makeNoPullRequestRechecks } from "./noPullRequestRechecks.ts";
45import * as Orchestrator from "./Orchestrator.ts";
46import * as ProjectionStore from "./ProjectionStore.ts";
47import { QUIET_AFTER_MS, QUIET_SYNC_INTERVAL_MS } from "./PullRequestSyncReactor.ts";
48
49export interface SettlementPullRequest {
50 readonly state: "open" | "closed" | "merged";
51 readonly closedAt?: string | null;
52 readonly mergedAt?: string | null;
53}
54
55const DAY_MS = 24 * 60 * 60 * 1_000;
56const QUEUED_TURN_START_GRACE_MS = 2 * 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) > 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" | "latestUserAuthoredMessageAt"
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.latestUserAuthoredMessageAt),
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, "latestUserAuthoredMessageAt">,
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 || thread.lineage.relationshipToParent === "subagent") &&
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 (thread.lineage.relationshipToParent === "subagent") {
393 if (yield* terminals.hasActiveSubprocess({ threadId: thread.id })) return null;
394 // The store returns a subagent only once its parent is done, so it
395 // settles with the parent and never runs its own lookup.
396 const uuid = yield* random.uuidV4();
397 yield* orchestrator.dispatch({
398 type: "thread.auto-settle",
399 commandId: CommandId.make(`server:auto-settle:${thread.id}:${uuid}`),
400 threadId: thread.id,
401 snapshotAt: thread.updatedAt,
402 });
403 return null;
404 }
405 // thread.auto-settle does not recheck settings, so read them per decision; reads are cached.
406 const currentSettings = resolveProjectSettings(
407 yield* settingsService.getSettings,
408 thread.projectId,
409 ).settings;
410 const decisionNow = yield* DateTime.now;
411 const settledAt = resolveAutoSettlementAt({
412 thread,
413 pullRequest,
414 nowMs: DateTime.toEpochMillis(decisionNow),
415 autoSettleAfterDays: currentSettings.sidebarAutoSettleAfterDays,
416 autoSettleOnMerge: currentSettings.sidebarAutoSettleOnMerge,
417 autoSettleKeepPullRequests: currentSettings.sidebarAutoSettleKeepPullRequests,
418 });
419 if (settledAt === null) return thread;
420 // A terminal still running a program keeps its thread open; a later sweep settles it.
421 if (yield* terminals.hasActiveSubprocess({ threadId: thread.id })) return null;
422 const uuid = yield* random.uuidV4();
423 yield* orchestrator.dispatch({
424 type: "thread.auto-settle",
425 commandId: CommandId.make(`server:auto-settle:${thread.id}:${uuid}`),
426 threadId: thread.id,
427 snapshotAt: thread.updatedAt,
428 settledAt,
429 });
430 return null;
431 },
432 (effect, thread) =>
433 effect.pipe(
434 Effect.catchCauseIf(
435 (cause) => !Cause.hasInterruptsOnly(cause),
436 (cause) =>
437 Effect.logWarning("automatic thread settlement skipped", {
438 threadId: thread.id,
439 cause: Cause.pretty(cause),
440 }).pipe(Effect.as(null)),
441 ),
442 ),
443 );
444
445 const lookupCandidates = (yield* Effect.forEach(
446 candidates,
447 (thread) => {
448 if (thread.lineage.relationshipToParent === "subagent") return settleThread(thread, null);
449 const projectSettings = resolveProjectSettings(settings, thread.projectId).settings;
450 // Skip no-op decisions; actual settlement still reads fresh settings before dispatch.
451 const settledAt = resolveAutoSettlementAt({
452 thread,
453 pullRequest: null,
454 nowMs,
455 autoSettleAfterDays: projectSettings.sidebarAutoSettleAfterDays,
456 autoSettleOnMerge: projectSettings.sidebarAutoSettleOnMerge,
457 autoSettleKeepPullRequests: projectSettings.sidebarAutoSettleKeepPullRequests,
458 });
459 return settledAt === null ? Effect.succeed(thread) : settleThread(thread, null);
460 },
461 { concurrency: 8 },
462 ))
463 .filter((thread) => thread !== null)
464 .filter((thread) => visibleThreadPullRequests(thread.pullRequests ?? []).length === 0)
465 .filter(
466 (thread) =>
467 thread.branch !== null ||
468 thread.linkedPullRequest != null ||
469 thread.branchPullRequest != null,
470 );
471 const lookupCwdByThreadId = new Map<string, string>();
472 yield* Effect.forEach(
473 lookupCandidates,
474 (thread) =>
475 Effect.gen(function* () {
476 const project = projects.get(thread.projectId);
477 if (project === undefined || thread.branch === null) return;
478 // A worktree folder can outlive its .git, and git there fails with not_a_repository.
479 // An unreadable .git keeps the worktree, so git fails there and the thread is skipped.
480 lookupCwdByThreadId.set(
481 thread.id,
482 thread.worktreePath !== null &&
483 (yield* fileSystem
484 .exists(path.join(thread.worktreePath, ".git"))
485 .pipe(Effect.orElseSucceed(() => true)))
486 ? thread.worktreePath
487 : project.workspaceRoot,
488 );
489 }),
490 { concurrency: 8, discard: true },
491 );
492 if (mergedPullRequest !== null) {
493 // Invalidate checkout caches on merge; cached open branches would delay settlement beyond this sweep.
494 const cwds = [...new Set(lookupCwdByThreadId.values())];
495 yield* Effect.forEach(cwds, (cwd) => git.invalidateStatus(cwd), {
496 concurrency: 8,
497 discard: true,
498 });
499 }
500 const lookupKey = (thread: (typeof lookupCandidates)[number]) => {
501 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
502 if (reference != null) {
503 return JSON.stringify([
504 thread.linkedPullRequest != null ? "linked" : "branch-reference",
505 reference.projectId,
506 reference.repository,
507 reference.number,
508 lookupCwdByThreadId.get(thread.id),
509 thread.branch,
510 ]);
511 }
512 if (thread.branch === null) return JSON.stringify(["none", thread.id]);
513 const cwd = lookupCwdByThreadId.get(thread.id);
514 return JSON.stringify(
515 cwd === undefined ? ["missing-project", thread.id] : ["branch", cwd, thread.branch],
516 );
517 };
518 const groups = Map.groupBy(lookupCandidates, lookupKey);
519 // A thread with no link of its own does not settle from a pull request another thread links,
520 // archived threads included.
521 const explicitlyLinked = new Set(
522 groups.size === 0
523 ? []
524 : (yield* projections.getThreadsWithPullRequests(undefined, {
525 includeArchived: true,
526 })).flatMap((thread) =>
527 visibleThreadPullRequests(thread.pullRequests ?? []).map(threadPullRequestKeyOf),
528 ),
529 );
530 const ownedByAnotherThread = (pullRequest: GitManager.GitBranchPullRequest | null) => {
531 if (pullRequest === null || pullRequest.state === "open") return false;
532 const key = branchPullRequestKey(pullRequest);
533 return key !== null && explicitlyLinked.has(key);
534 };
535
536 // wouldSettle and pullRequestFor run per lookup group; the git and pull request reads they make carry the spans.
537 const wouldSettle = Effect.fnUntraced(function* (
538 group: ReadonlyArray<(typeof lookupCandidates)[number]>,
539 pullRequest: SettlementPullRequest,
540 ) {
541 const currentSettings = yield* settingsService.getSettings;
542 const decisionNow = yield* DateTime.now;
543 return group.some((thread) => {
544 const { settings } = resolveProjectSettings(currentSettings, thread.projectId);
545 return (
546 resolveAutoSettlementAt({
547 thread,
548 pullRequest,
549 nowMs: DateTime.toEpochMillis(decisionNow),
550 autoSettleAfterDays: settings.sidebarAutoSettleAfterDays,
551 autoSettleOnMerge: settings.sidebarAutoSettleOnMerge,
552 autoSettleKeepPullRequests: settings.sidebarAutoSettleKeepPullRequests,
553 }) !== null
554 );
555 });
556 });
557
558 const pullRequestFor = Effect.fnUntraced(function* (
559 group: ReadonlyArray<(typeof lookupCandidates)[number]>,
560 ) {
561 const thread = group[0]!;
562 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
563 if (
564 thread.linkedPullRequest == null &&
565 reference != null &&
566 explicitlyLinked.has(threadPullRequestKeyOf(legacyThreadPullRequestKey(reference)))
567 ) {
568 return undefined;
569 }
570 if (reference != null) {
571 // Only matching PR links settle from this merge event; unrelated links require fresh lookup.
572 const matchesMerge =
573 mergedPullRequest !== null &&
574 reference.projectId === mergedPullRequest.projectId &&
575 reference.repository.toLowerCase() === mergedPullRequest.repository.toLowerCase() &&
576 reference.number === mergedPullRequest.number;
577 if (!matchesMerge && !projects.has(reference.projectId)) {
578 return yield* Effect.die(new Error("linked pull request project not found"));
579 }
580 const readKey = quietReadKey(reference);
581 const shellClosed =
582 group.filter((member) => shellClosedThreads.delete(member.id)).length > 0;
583 if (shellClosed) quietOpenReadAt.delete(readKey);
584 else if (!matchesMerge && quietOpenReadAt.has(readKey)) {
585 return { state: "open", closedAt: null, mergedAt: null } satisfies SettlementPullRequest;
586 }
587 const summary = matchesMerge
588 ? ({
589 state: "merged",
590 closedAt: null,
591 mergedAt: mergedPullRequest.mergedAt,
592 } satisfies SettlementPullRequest)
593 : yield* pullRequests.summary(
594 {
595 projectId: reference.projectId,
596 repository: reference.repository,
597 number: reference.number,
598 },
599 { recoverTransientFailure: false, bypassCache: shellClosed },
600 );
601 if (
602 "updatedAt" in summary &&
603 summary.state === "open" &&
604 nowMs - quietPausedAtMs >= QUIET_SYNC_INTERVAL_MS &&
605 nowMs - Date.parse(summary.updatedAt) >= QUIET_AFTER_MS
606 ) {
607 quietOpenReadAt.set(readKey, nowMs);
608 }
609 const terminal = {
610 state: summary.state,
611 closedAt: summary.closedAt ?? null,
612 mergedAt: summary.mergedAt ?? null,
613 } satisfies SettlementPullRequest;
614 const cwd = lookupCwdByThreadId.get(thread.id);
615 if (summary.state !== "open" && thread.branch !== null && cwd !== undefined) {
616 if (!(yield* wouldSettle(group, terminal))) return undefined;
617 const current = yield* git.branchPullRequest(
618 { cwd, branch: thread.branch },
619 { refresh: true },
620 );
621 const project = projects.get(thread.projectId);
622 if (
623 current?.state === "open" &&
624 project !== undefined &&
625 pullRequestMatchesProject(current, project)
626 ) {
627 return current;
628 }
629 }
630 return terminal;
631 }
632 if (thread.branch === null) return null;
633 const cwd = lookupCwdByThreadId.get(thread.id);
634 if (cwd === undefined) {
635 return yield* Effect.die(new Error("thread project not found"));
636 }
637 const refresh = group.filter((member) => shellClosedThreads.delete(member.id)).length > 0;
638 const key = lookupKey(thread);
639 if (scheduledLookups !== null && !refresh && !scheduledLookups.has(key)) return undefined;
640 // Remembered git state is enough to rule a thread out; only an answer
641 // that would settle it is confirmed against fresh git state.
642 const remembered = yield* git.branchPullRequest(
643 { cwd, branch: thread.branch },
644 { refresh, confirmTerminal: false },
645 );
646 noPullRequestRechecks.record(key, nowMs, remembered !== null);
647 if (ownedByAnotherThread(remembered)) return undefined;
648 if (refresh || remembered === null || remembered.state === "open") return remembered;
649 if (!(yield* wouldSettle(group, remembered))) return undefined;
650 const fresh = yield* git.branchPullRequest(
651 { cwd, branch: thread.branch },
652 { freshGitState: true },
653 );
654 return ownedByAnotherThread(fresh) ? undefined : fresh;
655 });
656
657 // A merge, a shell close and a thread's own events read at once; only scheduled sweeps wait.
658 const scheduledLookups =
659 mergedPullRequest !== null || threadId !== undefined
660 ? null
661 : noPullRequestRechecks.select(
662 nowMs,
663 [...groups]
664 .filter(([key]) => key.startsWith('["branch",'))
665 .map(([key, group]) => ({
666 key,
667 activityAtMs: Math.max(...group.map(threadActivityAtMs)),
668 })),
669 );
670
671 yield* Effect.forEach(
672 groups.values(),
673 (group) =>
674 Effect.gen(function* () {
675 // A thread of a project whose folder is not a repository has no branch pull request.
676 const pullRequest = yield* pullRequestFor(group).pipe(
677 Effect.catchIf(
678 (error) => error._tag === "GitCommandError" && error.reason === "not_a_repository",
679 () => Effect.void,
680 ),
681 );
682 if (pullRequest === undefined) return;
683 yield* Effect.forEach(group, (thread) => settleThread(thread, pullRequest), {
684 discard: true,
685 });
686 }).pipe(
687 Effect.catchCauseIf(
688 (cause) => !Cause.hasInterruptsOnly(cause),
689 (cause) =>
690 Effect.logWarning("automatic thread settlement skipped", {
691 threadIds: group.map((thread) => thread.id),
692 cause: Cause.pretty(cause),
693 }),
694 ),
695 ),
696 { concurrency: 8, discard: true },
697 );
698 if (threadId === undefined) noPullRequestRechecks.retain(groups);
699 });
700
701 const runSweep = (
702 mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
703 threadId?: ThreadId,
704 ) =>
705 sweep(mergedPullRequest, threadId).pipe(
706 Effect.provideService(GitVcsDriver.BackgroundGitWork, true),
707 Effect.catchCauseIf(
708 (cause) => !Cause.hasInterruptsOnly(cause),
709 (cause) =>
710 Effect.logWarning("automatic thread settlement sweep failed", {
711 cause: Cause.pretty(cause),
712 }),
713 ),
714 );
715 let fullSweepPending = false;
716 // A thread that just stopped must not wait behind a full sweep or another thread's host
717 // reads: clients hold it in Working only briefly, so a late settle makes it appear and then vanish.
718 const fullSweeps = yield* makeDrainableWorker(() => {
719 // Clear at the start so events during this sweep can request one follow-up.
720 fullSweepPending = false;
721 return runSweep(null);
722 });
723 const enqueueFullSweep = () =>
724 Effect.suspend(() => {
725 if (fullSweepPending) return Effect.void;
726 fullSweepPending = true;
727 return fullSweeps.enqueue(undefined);
728 });
729 const threadSweeps = yield* FiberSet.make<void>();
730 const threadSweepSlots = yield* Semaphore.make(8);
731 // One sweep per thread at a time; events during a running sweep coalesce into one more pass.
732 const threadSweepStates = new Map<ThreadId, "queued" | "running" | "rerun">();
733 const sweepThread = (
734 threadId: ThreadId,
735 ): Effect.Effect<void, Effect.Error<ReturnType<typeof runSweep>>> =>
736 Effect.sync(() => threadSweepStates.set(threadId, "running")).pipe(
737 Effect.andThen(runSweep(null, threadId)),
738 threadSweepSlots.withPermits(1),
739 Effect.andThen(
740 Effect.suspend(() => {
741 if (threadSweepStates.get(threadId) === "rerun") return sweepThread(threadId);
742 threadSweepStates.delete(threadId);
743 return Effect.void;
744 }),
745 ),
746 );
747 const enqueueThread = (threadId: ThreadId) =>
748 Effect.suspend(() => {
749 const state = threadSweepStates.get(threadId);
750 if (state === "running") threadSweepStates.set(threadId, "rerun");
751 if (state !== undefined) return Effect.void;
752 threadSweepStates.set(threadId, "queued");
753 return sweepThread(threadId).pipe(FiberSet.run(threadSweeps), Effect.asVoid);
754 });
755
756 // Skip settle scripts in shared checkouts where other threads may still work.
757 const cleanUpSettledThread = Effect.fn("ThreadSettlementServiceV2.cleanUpSettledThread")(
758 function* (threadId: ThreadId) {
759 const settled = yield* projections.getThread(threadId);
760 if (settled.deletedAt !== null || settled.settledOverride !== "settled") return;
761 yield* terminals.closeOnSettle({ threadId });
762 const worktreePath = settled.worktreePath;
763 if (worktreePath === null) return;
764 if (!(yield* fileSystem.exists(worktreePath))) {
765 // A settle script that tears something down would otherwise be skipped with no trace.
766 const project = Option.getOrUndefined(yield* projectStore.getShell(settled.projectId));
767 if (
768 project !== undefined &&
769 settleProjectScript(resolveProjectScripts(yield* settingsService.getSettings, project))
770 ) {
771 yield* Effect.logWarning(
772 "settle script skipped: the thread's worktree no longer exists",
773 { threadId, worktreePath },
774 );
775 }
776 return;
777 }
778 // Recheck after closing and worktree I/O; only live, settled threads may run scripts.
779 const thread = yield* projections.getThread(threadId);
780 if (thread.deletedAt !== null || thread.settledOverride !== "settled") return;
781 const settledAtMs = toMillis(thread.settledAt);
782 if (settledAtMs === null || settleActionRunAt.get(threadId) === settledAtMs) return;
783 // The parent's worktree belongs to the parent; shared-worktree children
784 // skip duplicate cleanup there.
785 if (
786 thread.lineage.relationshipToParent === "subagent" &&
787 thread.lineage.parentThreadId !== null
788 ) {
789 const parent = yield* projections.getThread(thread.lineage.parentThreadId).pipe(
790 Effect.catchTags({
791 ProjectionStoreThreadNotFoundError: () => Effect.succeed(null),
792 }),
793 );
794 if (parent?.worktreePath === worktreePath) return;
795 }
796 const run = yield* projectScripts.runForThread({
797 threadId,
798 projectId: thread.projectId,
799 worktreePath,
800 trigger: "settle",
801 observeCompletion: {},
802 });
803 settleActionRunAt.set(threadId, settledAtMs);
804 if (run.status === "started" && run.completion) {
805 yield* run.completion.pipe(Effect.forkDetach);
806 }
807 },
808 (effect, threadId) =>
809 effect.pipe(
810 Effect.catchCauseIf(
811 (cause) => !Cause.hasInterruptsOnly(cause),
812 (cause) =>
813 Effect.logWarning("cleaning up a settled thread failed", {
814 threadId,
815 cause: Cause.pretty(cause),
816 }),
817 ),
818 ),
819 );
820
821 const processEvent = (event: OrchestrationV2DomainEvent) => {
822 switch (event.type) {
823 case "thread.settled":
824 return cleanUpSettledThread(event.threadId).pipe(Effect.andThen(enqueueFullSweep()));
825 case "thread.archived":
826 case "thread.deleted":
827 return enqueueFullSweep();
828 case "thread.pull-request-link-updated":
829 case "thread.pull-request-synced":
830 case "thread.issue-synced":
831 case "provider-session.detached":
832 case "run.background-work-cancelled":
833 return enqueueThread(event.threadId);
834 // Sweep only when the work can have ended: progress updates cannot settle anything.
835 case "subagent.updated":
836 return isOrchestrationV2WorkActive(event.payload.status)
837 ? Effect.void
838 : enqueueThread(event.threadId);
839 case "provider-thread.updated":
840 return backgroundWorkHoldsCompletion(event.payload.pendingBackgroundTasks ?? [])
841 ? Effect.void
842 : enqueueThread(event.threadId);
843 case "turn-item.updated": {
844 const item = event.payload;
845 if (
846 item.type === "command_execution" &&
847 !isOrchestrationV2WorkActive(item.status) &&
848 sourceControlDefinitions.definitions.some(
849 (definition) => definition.changeRequestCloseCommand?.test(item.input) === true,
850 )
851 ) {
852 shellClosedThreads.add(event.threadId);
853 }
854 return turnItemUpdateCanEndBackgroundWork(item)
855 ? enqueueThread(event.threadId)
856 : Effect.void;
857 }
858 case "provider-session.updated":
859 return event.payload.status !== "starting" && event.payload.status !== "running"
860 ? enqueueThread(event.threadId)
861 : Effect.void;
862 case "run.updated":
863 return ["completed", "interrupted", "failed", "cancelled", "rolled_back"].includes(
864 event.payload.status,
865 )
866 ? enqueueThread(event.threadId)
867 : Effect.void;
868 default:
869 return Effect.void;
870 }
871 };
872
873 const start: ThreadSettlementServiceV2["Service"]["start"] = Effect.fn(
874 "ThreadSettlementServiceV2.start",
875 )(function* () {
876 const settingsChanges = yield* settingsService.subscribeChanges;
877 const mergedPullRequests = yield* pullRequests.subscribeMerges;
878 const events = orchestrator.streamDomainEvents;
879 const initialSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
880 let lastSettlementSettings = autoSettlementSettingsKey(initialSettings);
881 yield* forkParked(
882 Effect.gen(function* () {
883 yield* enqueueFullSweep();
884 yield* fullSweeps.drain;
885 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
886 );
887 yield* forkParked(
888 Stream.runForEach(settingsChanges, (settings) => {
889 const key = autoSettlementSettingsKey(settings);
890 if (key === lastSettlementSettings) {
891 return Effect.void;
892 }
893 lastSettlementSettings = key;
894 return enqueueFullSweep();
895 }),
896 );
897 yield* forkParked(Stream.runForEach(mergedPullRequests, (event) => runSweep(event)));
898 yield* forkParked(Stream.runForEach(pullRequests.subscribeRefreshes, pauseQuietReads));
899 yield* forkParked(
900 Stream.runForEach(events, processEvent).pipe(
901 Effect.catchCause((cause) =>
902 Effect.logWarning("Thread settlement event stream failed", { cause }),
903 ),
904 ),
905 );
906 });
907
908 return {
909 start,
910 drain: Effect.andThen(fullSweeps.drain, FiberSet.awaitEmpty(threadSweeps)),
911 } satisfies ThreadSettlementServiceV2["Service"];
912});