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

ThreadSettlementService.ts

540 lines21.0 KB

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