Open History to see the last commit
1import {
2 CommandId,
3 type OrchestrationEvent,
4 type ServerSettings as ServerSettingsValue,
5 type ThreadId,
6} from "@t3tools/contracts";
7import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
8import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
9import * as Cause from "effect/Cause";
10import * as Context from "effect/Context";
11import * as Crypto from "effect/Crypto";
12import * as DateTime from "effect/DateTime";
13import * as Effect from "effect/Effect";
14import * as FileSystem from "effect/FileSystem";
15import * as Layer from "effect/Layer";
16import * as Schedule from "effect/Schedule";
17import type * as Scope from "effect/Scope";
18import * as Stream from "effect/Stream";
19
20import * as GitManager from "../git/GitManager.ts";
21import * as PullRequestService from "../pullRequest/PullRequestService.ts";
22import * as ServerSettings from "../serverSettings.ts";
23import { forkParked } from "../serverActivation.ts";
24import * as OrchestrationEngine from "./Services/OrchestrationEngine.ts";
25import * as ProjectionSnapshotQuery from "./Services/ProjectionSnapshotQuery.ts";
26import { pullRequestMatchesProject } from "./ThreadPullRequestReactor.ts";
27import {
28 isAutoSettlementCandidate,
29 resolveAutoSettlementAt,
30 type SettlementPullRequest,
31} from "./ThreadSettlementPolicy.ts";
32
33export class ThreadSettlementReactor extends Context.Service<
34 ThreadSettlementReactor,
35 {
36 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
37 readonly drain: Effect.Effect<void>;
38 }
39>()("t3/orchestration/ThreadSettlementReactor") {}
40
41/** @public Service construction is part of the canonical Effect module API. */
42/** Whether any environment default or project override can settle a thread. */
43function autoSettlementConfigured(settings: ServerSettingsValue): boolean {
44 if (settings.sidebarAutoSettleOnMerge || settings.sidebarAutoSettleAfterDays !== null) {
45 return true;
46 }
47 return Object.values(settings.projectSettingsOverrides).some(
48 (entry) =>
49 entry.sidebarAutoSettleOnMerge === true ||
50 (entry.sidebarAutoSettleAfterDays !== undefined && entry.sidebarAutoSettleAfterDays !== null),
51 );
52}
53
54/** Identity of every settlement input, so unrelated settings edits do not trigger a sweep. */
55/** @internal Exported for tests. */
56export function autoSettlementSettingsKey(settings: ServerSettingsValue): string {
57 return JSON.stringify([
58 settings.sidebarAutoSettleOnMerge,
59 settings.sidebarAutoSettleAfterDays,
60 // Only entries that touch settlement, in a stable order, so a project
61 // override on an unrelated key does not queue a sweep. JSON drops
62 // undefined, so inherit (absent) and never (null) need distinct marks.
63 Object.entries(settings.projectSettingsOverrides)
64 .filter(
65 ([, entry]) =>
66 entry.sidebarAutoSettleOnMerge !== undefined ||
67 entry.sidebarAutoSettleAfterDays !== undefined,
68 )
69 .sort(([left], [right]) => left.localeCompare(right))
70 .map(([projectId, entry]) => [
71 projectId,
72 entry.sidebarAutoSettleOnMerge ?? "inherit",
73 entry.sidebarAutoSettleAfterDays === undefined
74 ? "inherit"
75 : entry.sidebarAutoSettleAfterDays,
76 ]),
77 ]);
78}
79
80/** @public Service construction is part of the canonical Effect module API. */
81export const make = Effect.gen(function* () {
82 const engine = yield* OrchestrationEngine.OrchestrationEngineService;
83 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
84 const settingsService = yield* ServerSettings.ServerSettingsService;
85 const git = yield* GitManager.GitManager;
86 const pullRequests = yield* PullRequestService.PullRequestService;
87 const crypto = yield* Crypto.Crypto;
88 const fileSystem = yield* FileSystem.FileSystem;
89
90 const sweep = Effect.fn("ThreadSettlementReactor.sweep")(function* (
91 mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
92 threadId?: ThreadId,
93 ) {
94 const settings = yield* settingsService.getSettings;
95 if (!autoSettlementConfigured(settings)) {
96 return;
97 }
98 const snapshot = yield* snapshots.getShellSnapshot();
99 const now = DateTime.formatIso(yield* DateTime.now);
100 const projects = new Map(snapshot.projects.map((project) => [project.id, project]));
101 // A merge rechecks all candidates, including branches that discovery has
102 // not linked yet. Those lookups can still have cached the PR as open.
103 const candidates = snapshot.threads.filter(
104 (thread) =>
105 (threadId === undefined || thread.id === threadId) &&
106 isAutoSettlementCandidate(thread, now),
107 );
108
109 // Return the thread when it still needs a pull request decision. A rejected
110 // dispatch skips it for this snapshot instead of retrying through a lookup.
111 const settleThread = Effect.fn("ThreadSettlementReactor.settleThread")(
112 function* (thread: (typeof candidates)[number], pullRequest: SettlementPullRequest | null) {
113 const settings = resolveProjectSettings(
114 yield* settingsService.getSettings,
115 thread.projectId,
116 ).settings;
117 const decisionNow = DateTime.formatIso(yield* DateTime.now);
118 const settledAt = resolveAutoSettlementAt({
119 thread,
120 pullRequest,
121 now: decisionNow,
122 autoSettleAfterDays: settings.sidebarAutoSettleAfterDays,
123 autoSettleOnMerge: settings.sidebarAutoSettleOnMerge,
124 });
125 if (settledAt === null) {
126 return thread;
127 }
128 const uuid = yield* crypto.randomUUIDv4;
129 yield* engine.dispatch({
130 type: "thread.auto-settle",
131 commandId: CommandId.make(`server:auto-settle:${thread.id}:${uuid}`),
132 threadId: thread.id,
133 snapshotSequence: snapshot.snapshotSequence,
134 settledAt,
135 });
136 return null;
137 },
138 (effect, thread) =>
139 effect.pipe(
140 Effect.catchCause((cause) =>
141 Cause.hasInterruptsOnly(cause)
142 ? Effect.failCause(cause)
143 : Effect.logWarning("automatic thread settlement skipped", {
144 threadId: thread.id,
145 cause: Cause.pretty(cause),
146 }).pipe(Effect.as(null)),
147 ),
148 ),
149 );
150
151 // Inactivity needs no host state. Finish these decisions before any lookup
152 // can fail or wait on the network, including lookups shared by recent threads.
153 const lookupCandidates = (yield* Effect.forEach(
154 candidates,
155 (thread) => settleThread(thread, null),
156 {
157 concurrency: 8,
158 },
159 ))
160 .filter((thread) => thread !== null)
161 .filter((thread) => !thread.pullRequests.some((link) => link.source !== "stack-dismissed"));
162
163 // Use the same cwd as PR discovery so both paths share GitManager's cache.
164 const lookupCwdByThreadId = new Map<string, string>();
165 yield* Effect.forEach(
166 lookupCandidates,
167 (thread) =>
168 Effect.gen(function* () {
169 const project = projects.get(thread.projectId);
170 if (project === undefined || thread.branch === null) return;
171 const worktreeExists =
172 thread.worktreePath !== null &&
173 (yield* fileSystem.exists(thread.worktreePath).pipe(Effect.orElseSucceed(() => false)));
174 lookupCwdByThreadId.set(
175 thread.id,
176 worktreeExists && thread.worktreePath !== null
177 ? thread.worktreePath
178 : project.workspaceRoot,
179 );
180 }),
181 { concurrency: 8, discard: true },
182 );
183 if (mergedPullRequest !== null) {
184 // The merge confirmed a state the branch cache can still call open.
185 // Recheck those branches now instead of waiting for cache expiry.
186 const cwds = [...new Set(lookupCwdByThreadId.values())];
187 yield* Effect.forEach(cwds, (cwd) => git.invalidateStatus(cwd), {
188 concurrency: 8,
189 discard: true,
190 });
191 }
192 const lookupKey = (thread: (typeof candidates)[number]) => {
193 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
194 if (reference != null) {
195 return JSON.stringify([
196 "linked",
197 reference.projectId,
198 reference.repository,
199 reference.number,
200 lookupCwdByThreadId.get(thread.id),
201 thread.branch,
202 ]);
203 }
204 if (thread.branch === null) return JSON.stringify(["none", thread.id]);
205 const cwd = lookupCwdByThreadId.get(thread.id);
206 return JSON.stringify(
207 cwd === undefined ? ["missing-project", thread.id] : ["branch", cwd, thread.branch],
208 );
209 };
210 const groups = Map.groupBy(lookupCandidates, lookupKey);
211
212 const pullRequestFor = Effect.fn("ThreadSettlementReactor.pullRequestFor")(function* (
213 thread: (typeof candidates)[number],
214 ) {
215 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
216 if (reference != null) {
217 const matchesMerge =
218 mergedPullRequest !== null &&
219 reference.projectId === mergedPullRequest.projectId &&
220 reference.repository.toLowerCase() === mergedPullRequest.repository.toLowerCase() &&
221 reference.number === mergedPullRequest.number;
222 if (!matchesMerge && !projects.has(reference.projectId)) {
223 return yield* Effect.die(new Error("linked pull request project not found"));
224 }
225 const summary = matchesMerge
226 ? ({
227 state: "merged",
228 closedAt: null,
229 mergedAt: mergedPullRequest.mergedAt,
230 } satisfies SettlementPullRequest)
231 : yield* pullRequests.summary(
232 {
233 projectId: reference.projectId,
234 repository: reference.repository,
235 number: reference.number,
236 },
237 { recoverTransientFailure: false },
238 );
239 const cwd = lookupCwdByThreadId.get(thread.id);
240 if (summary.state !== "open" && thread.branch !== null && cwd !== undefined) {
241 // A reused branch can already have a new open PR while discovery
242 // is replacing its old link. Do not let settlement win that race.
243 const current = yield* git.branchPullRequest(
244 { cwd, branch: thread.branch },
245 { refresh: true },
246 );
247 const project = projects.get(thread.projectId);
248 if (
249 current?.state === "open" &&
250 project !== undefined &&
251 pullRequestMatchesProject(current, project)
252 ) {
253 return current;
254 }
255 }
256 return {
257 state: summary.state,
258 closedAt: summary.closedAt ?? null,
259 mergedAt: summary.mergedAt ?? null,
260 } satisfies SettlementPullRequest;
261 }
262 if (thread.branch === null) return null;
263 const cwd = lookupCwdByThreadId.get(thread.id);
264 if (cwd === undefined) {
265 return yield* Effect.die(new Error("thread project not found"));
266 }
267 return yield* git.branchPullRequest({ cwd, branch: thread.branch });
268 });
269
270 yield* Effect.forEach(
271 groups.values(),
272 (group) =>
273 Effect.gen(function* () {
274 const pullRequest = yield* pullRequestFor(group[0]!);
275 yield* Effect.forEach(group, (thread) => settleThread(thread, pullRequest), {
276 discard: true,
277 });
278 }).pipe(
279 Effect.catchCause((cause) =>
280 Cause.hasInterruptsOnly(cause)
281 ? Effect.failCause(cause)
282 : Effect.logWarning("automatic thread settlement skipped", {
283 threadIds: group.map((thread) => thread.id),
284 cause: Cause.pretty(cause),
285 }),
286 ),
287 ),
288 { concurrency: 8, discard: true },
289 );
290 });
291
292 const runSweep = (
293 mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
294 threadId?: ThreadId,
295 ) =>
296 sweep(mergedPullRequest, threadId).pipe(
297 Effect.catchCause((cause) =>
298 Cause.hasInterruptsOnly(cause)
299 ? Effect.failCause(cause)
300 : Effect.logWarning("automatic thread settlement sweep failed", {
301 cause: Cause.pretty(cause),
302 }),
303 ),
304 );
305 const worker = yield* makeDrainableWorker((threadId: ThreadId | undefined) =>
306 runSweep(null, threadId),
307 );
308
309 const processEvent = (event: OrchestrationEvent) => {
310 switch (event.type) {
311 case "thread.pull-request-linked":
312 case "thread.pull-request-synced":
313 case "thread.pull-request-unlinked":
314 // Merge notifications can arrive before the linked snapshot is projected.
315 // Recheck the persisted state so terminal links settle without the timer.
316 return worker.enqueue(event.payload.threadId);
317 case "thread.session-set":
318 if (
319 event.payload.session.status !== "running" &&
320 event.payload.session.status !== "starting"
321 ) {
322 return worker.enqueue(event.payload.threadId);
323 }
324 break;
325 }
326 return Effect.void;
327 };
328
329 const start: ThreadSettlementReactor["Service"]["start"] = Effect.fn(
330 "ThreadSettlementReactor.start",
331 )(function* () {
332 const settingsChanges = yield* settingsService.subscribeChanges;
333 const mergedPullRequests = yield* pullRequests.subscribeMerges;
334 const events = yield* engine.subscribeDomainEvents;
335 const initialSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
336 let lastSettlementSettings = autoSettlementSettingsKey(initialSettings);
337 yield* forkParked(
338 Effect.gen(function* () {
339 yield* worker.enqueue(undefined);
340 yield* worker.drain;
341 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
342 );
343 yield* forkParked(
344 Stream.runForEach(settingsChanges, (settings) => {
345 const key = autoSettlementSettingsKey(settings);
346 if (key === lastSettlementSettings) {
347 return Effect.void;
348 }
349 lastSettlementSettings = key;
350 return worker.enqueue(undefined);
351 }),
352 );
353 yield* forkParked(Stream.runForEach(mergedPullRequests, (event) => runSweep(event)));
354 yield* forkParked(Stream.runForEach(events, processEvent));
355 });
356
357 return { start, drain: worker.drain } satisfies ThreadSettlementReactor["Service"];
358});
359
360export const layer = Layer.effect(ThreadSettlementReactor, make);