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 ))
107 .filter((thread) => thread !== null)
108 .filter((thread) => !thread.pullRequests.some((link) => link.source !== "stack-dismissed"));
109
110 // Use the same cwd as PR discovery so both paths share GitManager's cache.
111 const lookupCwdByThreadId = new Map<string, string>();
112 yield* Effect.forEach(
113 lookupCandidates,
114 (thread) =>
115 Effect.gen(function* () {
116 const project = projects.get(thread.projectId);
117 if (project === undefined || thread.branch === null) return;
118 const worktreeExists =
119 thread.worktreePath !== null &&
120 (yield* fileSystem.exists(thread.worktreePath).pipe(Effect.orElseSucceed(() => false)));
121 lookupCwdByThreadId.set(
122 thread.id,
123 worktreeExists && thread.worktreePath !== null
124 ? thread.worktreePath
125 : project.workspaceRoot,
126 );
127 }),
128 { concurrency: 8, discard: true },
129 );
130 if (mergedPullRequest !== null) {
131 // The merge confirmed a state the branch cache can still call open.
132 // Recheck those branches now instead of waiting for cache expiry.
133 const cwds = [...new Set(lookupCwdByThreadId.values())];
134 yield* Effect.forEach(cwds, (cwd) => git.invalidateStatus(cwd), {
135 concurrency: 8,
136 discard: true,
137 });
138 }
139 const lookupKey = (thread: (typeof candidates)[number]) => {
140 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
141 if (reference != null) {
142 return JSON.stringify([
143 "linked",
144 reference.projectId,
145 reference.repository,
146 reference.number,
147 lookupCwdByThreadId.get(thread.id),
148 thread.branch,
149 ]);
150 }
151 if (thread.branch === null) return JSON.stringify(["none", thread.id]);
152 const cwd = lookupCwdByThreadId.get(thread.id);
153 return JSON.stringify(
154 cwd === undefined ? ["missing-project", thread.id] : ["branch", cwd, thread.branch],
155 );
156 };
157 const groups = Map.groupBy(lookupCandidates, lookupKey);
158
159 const pullRequestFor = Effect.fn("ThreadSettlementReactor.pullRequestFor")(function* (
160 thread: (typeof candidates)[number],
161 ) {
162 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
163 if (reference != null) {
164 const matchesMerge =
165 mergedPullRequest !== null &&
166 reference.projectId === mergedPullRequest.projectId &&
167 reference.repository.toLowerCase() === mergedPullRequest.repository.toLowerCase() &&
168 reference.number === mergedPullRequest.number;
169 if (!matchesMerge && !projects.has(reference.projectId)) {
170 return yield* Effect.die(new Error("linked pull request project not found"));
171 }
172 const summary = matchesMerge
173 ? ({
174 state: "merged",
175 closedAt: null,
176 mergedAt: mergedPullRequest.mergedAt,
177 } satisfies SettlementPullRequest)
178 : yield* pullRequests.summary(
179 {
180 projectId: reference.projectId,
181 repository: reference.repository,
182 number: reference.number,
183 },
184 { recoverTransientFailure: false },
185 );
186 const cwd = lookupCwdByThreadId.get(thread.id);
187 if (summary.state !== "open" && thread.branch !== null && cwd !== undefined) {
188 // A reused branch can already have a new open PR while discovery
189 // is replacing its old link. Do not let settlement win that race.
190 const current = yield* git.branchPullRequest(
191 { cwd, branch: thread.branch },
192 { refresh: true },
193 );
194 const project = projects.get(thread.projectId);
195 if (
196 current?.state === "open" &&
197 project !== undefined &&
198 pullRequestMatchesProject(current, project)
199 ) {
200 return current;
201 }
202 }
203 return {
204 state: summary.state,
205 closedAt: summary.closedAt ?? null,
206 mergedAt: summary.mergedAt ?? null,
207 } satisfies SettlementPullRequest;
208 }
209 if (thread.branch === null) return null;
210 const cwd = lookupCwdByThreadId.get(thread.id);
211 if (cwd === undefined) {
212 return yield* Effect.die(new Error("thread project not found"));
213 }
214 return yield* git.branchPullRequest({ cwd, branch: thread.branch });
215 });
216
217 yield* Effect.forEach(
218 groups.values(),
219 (group) =>
220 Effect.gen(function* () {
221 const pullRequest = yield* pullRequestFor(group[0]!);
222 yield* Effect.forEach(group, (thread) => settleThread(thread, pullRequest), {
223 discard: true,
224 });
225 }).pipe(
226 Effect.catchCause((cause) =>
227 Cause.hasInterruptsOnly(cause)
228 ? Effect.failCause(cause)
229 : Effect.logWarning("automatic thread settlement skipped", {
230 threadIds: group.map((thread) => thread.id),
231 cause: Cause.pretty(cause),
232 }),
233 ),
234 ),
235 { concurrency: 8, discard: true },
236 );
237 });
238
239 const runSweep = (mergedPullRequest: PullRequestService.PullRequestMergeEvent | null) =>
240 sweep(mergedPullRequest).pipe(
241 Effect.catchCause((cause) =>
242 Cause.hasInterruptsOnly(cause)
243 ? Effect.failCause(cause)
244 : Effect.logWarning("automatic thread settlement sweep failed", {
245 cause: Cause.pretty(cause),
246 }),
247 ),
248 );
249 const worker = yield* makeDrainableWorker(() => runSweep(null));
250
251 const start: ThreadSettlementReactor["Service"]["start"] = Effect.fn(
252 "ThreadSettlementReactor.start",
253 )(function* () {
254 const settingsChanges = yield* settingsService.subscribeChanges;
255 const mergedPullRequests = yield* pullRequests.subscribeMerges;
256 const initialSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
257 let lastAfterDays = initialSettings.sidebarAutoSettleAfterDays;
258 let lastOnMerge = initialSettings.sidebarAutoSettleOnMerge;
259 yield* forkParked(
260 Effect.gen(function* () {
261 yield* worker.enqueue(undefined);
262 yield* worker.drain;
263 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
264 );
265 yield* forkParked(
266 Stream.runForEach(settingsChanges, (settings) => {
267 if (
268 settings.sidebarAutoSettleAfterDays === lastAfterDays &&
269 settings.sidebarAutoSettleOnMerge === lastOnMerge
270 ) {
271 return Effect.void;
272 }
273 lastAfterDays = settings.sidebarAutoSettleAfterDays;
274 lastOnMerge = settings.sidebarAutoSettleOnMerge;
275 return worker.enqueue(undefined);
276 }),
277 );
278 yield* forkParked(Stream.runForEach(mergedPullRequests, runSweep));
279 });
280
281 return { start, drain: worker.drain } satisfies ThreadSettlementReactor["Service"];
282});
283
284export const layer = Layer.effect(ThreadSettlementReactor, make);