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