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