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