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