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