Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadSettlementService.ts

961 lines39.5 KB

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