Open History to see the last commit
1import { CommandId, type OrchestrationV2ThreadShell } from "@t3tools/contracts";
2import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
3import * as Cause from "effect/Cause";
4import * as Context from "effect/Context";
5import * as Crypto from "effect/Crypto";
6import * as DateTime from "effect/DateTime";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Schedule from "effect/Schedule";
11import type * as Scope from "effect/Scope";
12import * as Stream from "effect/Stream";
13
14import * as GitManager from "../git/GitManager.ts";
15import * as PullRequestService from "../pullRequest/PullRequestService.ts";
16import * as ServerSettings from "../serverSettings.ts";
17import { forkParked } from "../serverActivation.ts";
18import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
19import { OrchestratorV2 } from "./Orchestrator.ts";
20import { ProjectionStoreV2, type ProjectionSettlementCandidate } from "./ProjectionStore.ts";
21
22export interface SettlementPullRequest {
23 readonly state: "open" | "closed" | "merged";
24 readonly closedAt?: string | null;
25 readonly mergedAt?: string | null;
26}
27
28const DAY_MS = 24 * 60 * 60 * 1_000;
29export const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
30
31function toMillis(value: DateTime.Utc | null | undefined): number | null {
32 return value == null ? null : DateTime.toEpochMillis(value);
33}
34
35function latestMillis(values: ReadonlyArray<number | null>): number | null {
36 let latest: number | null = null;
37 for (const value of values) {
38 if (value === null) continue;
39 if (latest === null || value > latest) latest = value;
40 }
41 return latest;
42}
43
44function canonicalRepositoryKey(key: string): string {
45 return key
46 .replace(
47 /^(?:ssh\.dev\.azure\.com|vs-ssh\.visualstudio\.com)\/v3\/([^/]+)\/([^/]+)\/([^/]+)$/u,
48 "dev.azure.com/$1/$2/_git/$3",
49 )
50 .replace(
51 /^([^.]+)\.visualstudio\.com\/(?:defaultcollection\/)?([^/]+)\/_git\/([^/]+)$/u,
52 "dev.azure.com/$1/$2/_git/$3",
53 );
54}
55
56function pullRequestMatchesProject(
57 pullRequest: GitManager.GitBranchPullRequest,
58 project: {
59 readonly repositoryIdentity?: { readonly canonicalKey: string } | null | undefined;
60 },
61): boolean {
62 return (
63 pullRequest.repositoryKey !== null &&
64 project.repositoryIdentity != null &&
65 canonicalRepositoryKey(pullRequest.repositoryKey) ===
66 canonicalRepositoryKey(project.repositoryIdentity.canonicalKey)
67 );
68}
69
70/**
71 * A recent user message stays queued until a run adopts its timestamp.
72 * Absolute age bounds client clock skew in both directions and stops stale
73 * pre-adoption data from blocking the thread forever. A failed run start
74 * clears the block immediately (mirrors the v1 session "error" rule).
75 */
76export function threadHasQueuedTurnStart(
77 thread: Pick<
78 OrchestrationV2ThreadShell,
79 | "latestUserMessageAt"
80 | "latestRunRequestedAt"
81 | "latestRunStartedAt"
82 | "latestRunCompletedAt"
83 | "latestRunId"
84 | "status"
85 >,
86 nowMs: number,
87): boolean {
88 const messageAtMs = toMillis(thread.latestUserMessageAt);
89 if (messageAtMs === null || thread.status === "failed") return false;
90 const age = nowMs - messageAtMs;
91 if (Number.isNaN(age) || Math.abs(age) > QUEUED_TURN_START_GRACE_MS) return false;
92 if (thread.latestRunId === null) return true;
93 return [
94 toMillis(thread.latestRunRequestedAt),
95 toMillis(thread.latestRunStartedAt),
96 toMillis(thread.latestRunCompletedAt),
97 ].every((value) => value === null || value < messageAtMs);
98}
99
100function pullRequestSettles(
101 thread: Pick<
102 OrchestrationV2ThreadShell,
103 "createdAt" | "latestUserMessageAt" | "latestRunRequestedAt"
104 >,
105 pullRequest: SettlementPullRequest,
106 autoSettleOnMerge: boolean,
107): boolean {
108 if (pullRequest.state !== "closed" && (pullRequest.state !== "merged" || !autoSettleOnMerge)) {
109 return false;
110 }
111 const terminalAt = pullRequest.state === "merged" ? pullRequest.mergedAt : pullRequest.closedAt;
112 if (terminalAt == null) return false;
113 const userAnchorMs = latestMillis([
114 toMillis(thread.createdAt),
115 toMillis(thread.latestUserMessageAt),
116 toMillis(thread.latestRunRequestedAt),
117 ]);
118 if (userAnchorMs === null) return false;
119 const pullRequestAtMs = Date.parse(terminalAt);
120 if (Number.isNaN(pullRequestAtMs)) return false;
121 return pullRequestAtMs >= userAnchorMs;
122}
123
124/** Cheap checks that run before any source control lookup. */
125export function isAutoSettlementCandidate(
126 thread: ProjectionSettlementCandidate,
127 nowMs: number,
128): boolean {
129 if (thread.archivedAt !== null || thread.settledOverride !== null) return false;
130 if (thread.pinnedAt != null) return false;
131 // Blocked-on-you work must never park behind a settled override.
132 if (thread.pendingRuntimeRequest !== null) return false;
133 // A live run — or post-settlement background work — is not staleness.
134 if (thread.activityRunStatus != null) return false;
135 if ((thread.pendingBackgroundTasks?.length ?? 0) > 0) return false;
136 if (threadHasQueuedTurnStart(thread, nowMs)) return false;
137 const snoozedUntilMs = toMillis(thread.snoozedUntil);
138 if (snoozedUntilMs === null || snoozedUntilMs <= nowMs) return true;
139 // A snoozed thread that woke early (error or completed work) can settle;
140 // one still parked on its wake time keeps its stronger statement.
141 const snoozedAtMs = toMillis(thread.snoozedAt);
142 const completedAtMs = toMillis(thread.latestRunCompletedAt);
143 const wokeOnError =
144 thread.status === "failed" &&
145 (snoozedAtMs === null || (completedAtMs !== null && completedAtMs > snoozedAtMs));
146 const wokeOnCompletion =
147 snoozedAtMs !== null && completedAtMs !== null && completedAtMs > snoozedAtMs;
148 return wokeOnError || wokeOnCompletion;
149}
150
151export function resolveAutoSettlementAt(input: {
152 readonly thread: ProjectionSettlementCandidate;
153 readonly pullRequest: SettlementPullRequest | null;
154 readonly nowMs: number;
155 readonly autoSettleAfterDays: number | null;
156 readonly autoSettleOnMerge: boolean;
157}): DateTime.Utc | null {
158 const { thread, pullRequest } = input;
159 if (!isAutoSettlementCandidate(thread, input.nowMs)) return null;
160 const activityAtMs = latestMillis([
161 toMillis(thread.latestUserMessageAt),
162 toMillis(thread.latestRunRequestedAt),
163 toMillis(thread.latestRunStartedAt),
164 toMillis(thread.latestRunCompletedAt),
165 ]);
166 if (pullRequest !== null && pullRequestSettles(thread, pullRequest, input.autoSettleOnMerge)) {
167 return activityAtMs === null ? thread.createdAt : DateTime.makeUnsafe(activityAtMs);
168 }
169 if (input.autoSettleAfterDays === null || activityAtMs === null) return null;
170 return activityAtMs < input.nowMs - input.autoSettleAfterDays * DAY_MS
171 ? DateTime.makeUnsafe(activityAtMs)
172 : null;
173}
174
175export class ThreadSettlementServiceV2 extends Context.Service<
176 ThreadSettlementServiceV2,
177 {
178 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
179 readonly drain: Effect.Effect<void>;
180 }
181>()("t3/orchestration-v2/ThreadSettlementService/ThreadSettlementServiceV2") {}
182
183export const make = Effect.gen(function* () {
184 const orchestrator = yield* OrchestratorV2;
185 const projections = yield* ProjectionStoreV2;
186 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
187 const settingsService = yield* ServerSettings.ServerSettingsService;
188 const git = yield* GitManager.GitManager;
189 const pullRequests = yield* PullRequestService.PullRequestService;
190 const crypto = yield* Crypto.Crypto;
191 const fileSystem = yield* FileSystem.FileSystem;
192
193 const sweep = Effect.fn("ThreadSettlementServiceV2.sweep")(function* (
194 mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
195 ) {
196 const settings = yield* settingsService.getSettings;
197 if (!settings.sidebarAutoSettleOnMerge && settings.sidebarAutoSettleAfterDays === null) {
198 return;
199 }
200 const threads = yield* projections.getSettlementCandidates();
201 const projectShells = yield* snapshots.getProjectShellsWithoutEnrichment();
202 const nowMs = DateTime.toEpochMillis(yield* DateTime.now);
203 const projects = new Map(projectShells.map((project) => [project.id, project]));
204 // A merge event re-sweeps every candidate, not just the threads linked to
205 // the merged pull request: most threads carry no link and settle from
206 // their branch lookup, which would otherwise wait for the next minute's
207 // sweep on a possibly stale cached answer.
208 const candidates = threads.filter((thread) => isAutoSettlementCandidate(thread, nowMs));
209
210 const settleThread = Effect.fn("ThreadSettlementServiceV2.settleThread")(
211 function* (thread: (typeof candidates)[number], pullRequest: SettlementPullRequest | null) {
212 const currentSettings = yield* settingsService.getSettings;
213 const decisionNow = yield* DateTime.now;
214 const settledAt = resolveAutoSettlementAt({
215 thread,
216 pullRequest,
217 nowMs: DateTime.toEpochMillis(decisionNow),
218 autoSettleAfterDays: currentSettings.sidebarAutoSettleAfterDays,
219 autoSettleOnMerge: currentSettings.sidebarAutoSettleOnMerge,
220 });
221 if (settledAt === null) return thread;
222 const uuid = yield* crypto.randomUUIDv4;
223 yield* orchestrator.dispatch({
224 type: "thread.auto-settle",
225 commandId: CommandId.make(`server:auto-settle:${thread.id}:${uuid}`),
226 threadId: thread.id,
227 snapshotAt: thread.updatedAt,
228 settledAt,
229 });
230 return null;
231 },
232 (effect, thread) =>
233 effect.pipe(
234 Effect.catchCause((cause) =>
235 Cause.hasInterruptsOnly(cause)
236 ? Effect.failCause(cause)
237 : Effect.logWarning("automatic thread settlement skipped", {
238 threadId: thread.id,
239 cause: Cause.pretty(cause),
240 }).pipe(Effect.as(null)),
241 ),
242 ),
243 );
244
245 // Inactivity is entirely projection-backed. Complete those decisions before
246 // a source-control lookup can delay or fail an otherwise eligible thread.
247 const lookupCandidates = (yield* Effect.forEach(
248 candidates,
249 (thread) => settleThread(thread, null),
250 { concurrency: 8 },
251 )).filter((thread) => thread !== null);
252 // Use the same cwd as the sidebar so both paths share GitManager's PR cache.
253 const lookupCwdByThreadId = new Map<string, string>();
254 yield* Effect.forEach(
255 lookupCandidates,
256 (thread) =>
257 Effect.gen(function* () {
258 const project = projects.get(thread.projectId);
259 if (project === undefined || thread.branch === null) return;
260 const worktreeExists =
261 thread.worktreePath !== null &&
262 (yield* fileSystem.exists(thread.worktreePath).pipe(Effect.orElseSucceed(() => false)));
263 lookupCwdByThreadId.set(
264 thread.id,
265 worktreeExists && thread.worktreePath !== null
266 ? thread.worktreePath
267 : project.workspaceRoot,
268 );
269 }),
270 { concurrency: 8, discard: true },
271 );
272 if (mergedPullRequest !== null) {
273 // The merge just confirmed a terminal state the lookup caches can still
274 // call open (branch answers live two minutes, the sweep runs every
275 // minute). Drop the swept checkouts' cached answers so the merge settles
276 // its branch threads now instead of on a later sweep. Threads linked to
277 // the merged pull request settle from the event itself below and need no
278 // lookup, so they are absent from this map by construction.
279 const cwds = [...new Set(lookupCwdByThreadId.values())];
280 yield* Effect.forEach(cwds, (cwd) => git.invalidateStatus(cwd), {
281 concurrency: 8,
282 discard: true,
283 });
284 }
285 const lookupKey = (thread: (typeof lookupCandidates)[number]) => {
286 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
287 if (reference != null) {
288 return JSON.stringify([
289 "linked",
290 reference.projectId,
291 reference.repository,
292 reference.number,
293 lookupCwdByThreadId.get(thread.id),
294 thread.branch,
295 ]);
296 }
297 if (thread.branch === null) return JSON.stringify(["none", thread.id]);
298 const cwd = lookupCwdByThreadId.get(thread.id);
299 return JSON.stringify(
300 cwd === undefined ? ["missing-project", thread.id] : ["branch", cwd, thread.branch],
301 );
302 };
303 const groups = Map.groupBy(lookupCandidates, lookupKey);
304
305 const pullRequestFor = Effect.fn("ThreadSettlementServiceV2.pullRequestFor")(function* (
306 thread: (typeof lookupCandidates)[number],
307 ) {
308 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
309 if (reference != null) {
310 // The event carries the merged state, so only the threads linked to
311 // that exact pull request settle from it. Every other linked thread
312 // falls through to a fresh summary lookup below: the merge sweep
313 // covers all candidates, and an unrelated merge must never settle
314 // them.
315 const matchesMerge =
316 mergedPullRequest !== null &&
317 reference.projectId === mergedPullRequest.projectId &&
318 reference.repository.toLowerCase() === mergedPullRequest.repository.toLowerCase() &&
319 reference.number === mergedPullRequest.number;
320 if (!matchesMerge && !projects.has(reference.projectId)) {
321 return yield* Effect.die(new Error("linked pull request project not found"));
322 }
323 const summary = matchesMerge
324 ? ({
325 state: "merged",
326 closedAt: null,
327 mergedAt: mergedPullRequest.mergedAt,
328 } satisfies SettlementPullRequest)
329 : yield* pullRequests.summary(
330 {
331 projectId: reference.projectId,
332 repository: reference.repository,
333 number: reference.number,
334 },
335 { recoverTransientFailure: false },
336 );
337 const cwd = lookupCwdByThreadId.get(thread.id);
338 if (summary.state !== "open" && thread.branch !== null && cwd !== undefined) {
339 const current = yield* git.branchPullRequest(
340 { cwd, branch: thread.branch },
341 { refresh: true },
342 );
343 const project = projects.get(thread.projectId);
344 if (
345 current?.state === "open" &&
346 project !== undefined &&
347 pullRequestMatchesProject(current, project)
348 ) {
349 return current;
350 }
351 }
352 return {
353 state: summary.state,
354 closedAt: summary.closedAt ?? null,
355 mergedAt: summary.mergedAt ?? null,
356 } satisfies SettlementPullRequest;
357 }
358 if (thread.branch === null) return null;
359 const cwd = lookupCwdByThreadId.get(thread.id);
360 if (cwd === undefined) {
361 return yield* Effect.die(new Error("thread project not found"));
362 }
363 return yield* git.branchPullRequest({ cwd, branch: thread.branch });
364 });
365
366 yield* Effect.forEach(
367 groups.values(),
368 (group) =>
369 Effect.gen(function* () {
370 const pullRequest = yield* pullRequestFor(group[0]!);
371 yield* Effect.forEach(group, (thread) => settleThread(thread, pullRequest), {
372 discard: true,
373 });
374 }).pipe(
375 Effect.catchCause((cause) =>
376 Cause.hasInterruptsOnly(cause)
377 ? Effect.failCause(cause)
378 : Effect.logWarning("automatic thread settlement skipped", {
379 threadIds: group.map((thread) => thread.id),
380 cause: Cause.pretty(cause),
381 }),
382 ),
383 ),
384 { concurrency: 8, discard: true },
385 );
386 });
387
388 const runSweep = (mergedPullRequest: PullRequestService.PullRequestMergeEvent | null) =>
389 sweep(mergedPullRequest).pipe(
390 Effect.catchCause((cause) =>
391 Cause.hasInterruptsOnly(cause)
392 ? Effect.failCause(cause)
393 : Effect.logWarning("automatic thread settlement sweep failed", {
394 cause: Cause.pretty(cause),
395 }),
396 ),
397 );
398 const worker = yield* makeDrainableWorker(() => runSweep(null));
399
400 const start: ThreadSettlementServiceV2["Service"]["start"] = Effect.fn(
401 "ThreadSettlementServiceV2.start",
402 )(function* () {
403 const settingsChanges = yield* settingsService.subscribeChanges;
404 const mergedPullRequests = yield* pullRequests.subscribeMerges;
405 const initialSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
406 let lastAfterDays = initialSettings.sidebarAutoSettleAfterDays;
407 let lastOnMerge = initialSettings.sidebarAutoSettleOnMerge;
408 yield* forkParked(
409 Effect.gen(function* () {
410 yield* worker.enqueue(undefined);
411 yield* worker.drain;
412 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
413 );
414 yield* forkParked(
415 Stream.runForEach(settingsChanges, (settings) => {
416 if (
417 settings.sidebarAutoSettleAfterDays === lastAfterDays &&
418 settings.sidebarAutoSettleOnMerge === lastOnMerge
419 ) {
420 return Effect.void;
421 }
422 lastAfterDays = settings.sidebarAutoSettleAfterDays;
423 lastOnMerge = settings.sidebarAutoSettleOnMerge;
424 return worker.enqueue(undefined);
425 }),
426 );
427 yield* forkParked(Stream.runForEach(mergedPullRequests, runSweep));
428 });
429
430 return { start, drain: worker.drain } satisfies ThreadSettlementServiceV2["Service"];
431});
432
433export const layer = Layer.effect(ThreadSettlementServiceV2, make);