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, readSweepSnapshot } 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* readSweepSnapshot(snapshots, threadId ?? null);
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((thread) => isAutoSettlementCandidate(thread, now));
104
105 // Return the thread when it still needs a pull request decision. A rejected
106 // dispatch skips it for this snapshot instead of retrying through a lookup.
107 const settleThread = Effect.fnUntraced(
108 function* (thread: (typeof candidates)[number], pullRequest: SettlementPullRequest | null) {
109 const settings = resolveProjectSettings(
110 yield* settingsService.getSettings,
111 thread.projectId,
112 ).settings;
113 const decisionNow = DateTime.formatIso(yield* DateTime.now);
114 const settledAt = resolveAutoSettlementAt({
115 thread,
116 pullRequest,
117 now: decisionNow,
118 autoSettleAfterDays: settings.sidebarAutoSettleAfterDays,
119 autoSettleOnMerge: settings.sidebarAutoSettleOnMerge,
120 });
121 if (settledAt === null) {
122 return thread;
123 }
124 const uuid = yield* crypto.randomUUIDv4;
125 yield* engine.dispatch({
126 type: "thread.auto-settle",
127 commandId: CommandId.make(`server:auto-settle:${thread.id}:${uuid}`),
128 threadId: thread.id,
129 snapshotSequence: snapshot.snapshotSequence,
130 settledAt,
131 });
132 return null;
133 },
134 (effect, thread) =>
135 effect.pipe(
136 Effect.catchCauseIf(
137 (cause) => !Cause.hasInterruptsOnly(cause),
138 (cause) =>
139 Effect.logWarning("automatic thread settlement skipped", {
140 threadId: thread.id,
141 cause: Cause.pretty(cause),
142 }).pipe(Effect.as(null)),
143 ),
144 ),
145 );
146
147 // Inactivity needs no host state. Finish these decisions before any lookup
148 // can fail or wait on the network, including lookups shared by recent threads.
149 const lookupCandidates = (yield* Effect.forEach(
150 candidates,
151 (thread) => settleThread(thread, null),
152 {
153 concurrency: 8,
154 },
155 ))
156 .filter((thread) => thread !== null)
157 .filter((thread) => !thread.pullRequests.some((link) => link.source !== "stack-dismissed"));
158
159 // Use the same cwd as PR discovery so both paths share GitManager's cache.
160 const lookupCwdByThreadId = new Map<string, string>();
161 yield* Effect.forEach(
162 lookupCandidates,
163 (thread) =>
164 Effect.gen(function* () {
165 const project = projects.get(thread.projectId);
166 if (project === undefined || thread.branch === null) return;
167 const worktreeExists =
168 thread.worktreePath !== null &&
169 (yield* fileSystem.exists(thread.worktreePath).pipe(Effect.orElseSucceed(() => false)));
170 lookupCwdByThreadId.set(
171 thread.id,
172 worktreeExists && thread.worktreePath !== null
173 ? thread.worktreePath
174 : project.workspaceRoot,
175 );
176 }),
177 { concurrency: 8, discard: true },
178 );
179 if (mergedPullRequest !== null) {
180 // The merge confirmed a state the branch cache can still call open.
181 // Recheck those branches now instead of waiting for cache expiry.
182 const cwds = [...new Set(lookupCwdByThreadId.values())];
183 yield* Effect.forEach(cwds, (cwd) => git.invalidateStatus(cwd), {
184 concurrency: 8,
185 discard: true,
186 });
187 }
188 const lookupKey = (thread: (typeof candidates)[number]) => {
189 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
190 if (reference != null) {
191 return JSON.stringify([
192 "linked",
193 reference.projectId,
194 reference.repository,
195 reference.number,
196 lookupCwdByThreadId.get(thread.id),
197 thread.branch,
198 ]);
199 }
200 if (thread.branch === null) return JSON.stringify(["none", thread.id]);
201 const cwd = lookupCwdByThreadId.get(thread.id);
202 return JSON.stringify(
203 cwd === undefined ? ["missing-project", thread.id] : ["branch", cwd, thread.branch],
204 );
205 };
206 const groups = Map.groupBy(lookupCandidates, lookupKey);
207
208 const wouldSettle = Effect.fn("ThreadSettlementReactor.wouldSettle")(function* (
209 group: ReadonlyArray<(typeof candidates)[number]>,
210 pullRequest: SettlementPullRequest,
211 ) {
212 const currentSettings = yield* settingsService.getSettings;
213 const decisionNow = DateTime.formatIso(yield* DateTime.now);
214 return group.some((thread) => {
215 const { settings } = resolveProjectSettings(currentSettings, thread.projectId);
216 return (
217 resolveAutoSettlementAt({
218 thread,
219 pullRequest,
220 now: decisionNow,
221 autoSettleAfterDays: settings.sidebarAutoSettleAfterDays,
222 autoSettleOnMerge: settings.sidebarAutoSettleOnMerge,
223 }) !== null
224 );
225 });
226 });
227
228 const pullRequestFor = Effect.fn("ThreadSettlementReactor.pullRequestFor")(function* (
229 group: ReadonlyArray<(typeof candidates)[number]>,
230 ) {
231 const thread = group[0]!;
232 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
233 if (reference != null) {
234 const matchesMerge =
235 mergedPullRequest !== null &&
236 reference.projectId === mergedPullRequest.projectId &&
237 reference.repository.toLowerCase() === mergedPullRequest.repository.toLowerCase() &&
238 reference.number === mergedPullRequest.number;
239 if (!matchesMerge && !projects.has(reference.projectId)) {
240 return yield* Effect.die(new Error("linked pull request project not found"));
241 }
242 const summary = matchesMerge
243 ? ({
244 state: "merged",
245 closedAt: null,
246 mergedAt: mergedPullRequest.mergedAt,
247 } satisfies SettlementPullRequest)
248 : yield* pullRequests.summary(
249 {
250 projectId: reference.projectId,
251 repository: reference.repository,
252 number: reference.number,
253 },
254 { recoverTransientFailure: false },
255 );
256 const terminal = {
257 state: summary.state,
258 closedAt: summary.closedAt ?? null,
259 mergedAt: summary.mergedAt ?? null,
260 } satisfies SettlementPullRequest;
261 const cwd = lookupCwdByThreadId.get(thread.id);
262 if (summary.state !== "open" && thread.branch !== null && cwd !== undefined) {
263 // A reused branch can already have a new open PR while discovery
264 // is replacing its old link. Do not let settlement win that race.
265 // Only pay for the uncached lookup when this sweep would otherwise
266 // settle: a terminal link that settles nothing (resumed thread,
267 // settle-on-merge off) would re-query the host every minute. A
268 // group that becomes eligible after this check waits for the next
269 // sweep rather than settling on the unverified link.
270 if (!(yield* wouldSettle(group, terminal))) return undefined;
271 const current = yield* git.branchPullRequest(
272 { cwd, branch: thread.branch },
273 { refresh: true },
274 );
275 const project = projects.get(thread.projectId);
276 if (
277 current?.state === "open" &&
278 project !== undefined &&
279 pullRequestMatchesProject(current, project)
280 ) {
281 return current;
282 }
283 }
284 return terminal;
285 }
286 if (thread.branch === null) return null;
287 const cwd = lookupCwdByThreadId.get(thread.id);
288 if (cwd === undefined) {
289 return yield* Effect.die(new Error("thread project not found"));
290 }
291 return yield* git.branchPullRequest({ cwd, branch: thread.branch });
292 });
293
294 yield* Effect.forEach(
295 groups.values(),
296 (group) =>
297 Effect.gen(function* () {
298 const pullRequest = yield* pullRequestFor(group);
299 if (pullRequest === undefined) return;
300 yield* Effect.forEach(group, (thread) => settleThread(thread, pullRequest), {
301 discard: true,
302 });
303 }).pipe(
304 Effect.catchCauseIf(
305 (cause) => !Cause.hasInterruptsOnly(cause),
306 (cause) =>
307 Effect.logWarning("automatic thread settlement skipped", {
308 threadIds: group.map((thread) => thread.id),
309 cause: Cause.pretty(cause),
310 }),
311 ),
312 ),
313 { concurrency: 8, discard: true },
314 );
315 });
316
317 const runSweep = (
318 mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
319 threadId?: ThreadId,
320 ) =>
321 sweep(mergedPullRequest, threadId).pipe(
322 Effect.catchCauseIf(
323 (cause) => !Cause.hasInterruptsOnly(cause),
324 (cause) =>
325 Effect.logWarning("automatic thread settlement sweep failed", {
326 cause: Cause.pretty(cause),
327 }),
328 ),
329 );
330 const worker = yield* makeDrainableWorker((threadId: ThreadId | undefined) =>
331 runSweep(null, threadId),
332 );
333
334 const processEvent = (event: OrchestrationEvent) => {
335 switch (event.type) {
336 case "thread.pull-request-linked":
337 case "thread.pull-request-synced":
338 case "thread.pull-request-unlinked":
339 // Merge notifications can arrive before the linked snapshot is projected.
340 // Recheck the persisted state so terminal links settle without the timer.
341 return worker.enqueue(event.payload.threadId);
342 case "thread.session-set":
343 if (
344 event.payload.session.status !== "running" &&
345 event.payload.session.status !== "starting"
346 ) {
347 return worker.enqueue(event.payload.threadId);
348 }
349 break;
350 }
351 return Effect.void;
352 };
353
354 const start: ThreadSettlementReactor["Service"]["start"] = Effect.fn(
355 "ThreadSettlementReactor.start",
356 )(function* () {
357 const settingsChanges = yield* settingsService.subscribeChanges;
358 const mergedPullRequests = yield* pullRequests.subscribeMerges;
359 const events = yield* engine.subscribeDomainEvents;
360 const initialSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
361 let lastSettlementSettings = autoSettlementSettingsKey(initialSettings);
362 yield* forkParked(
363 Effect.gen(function* () {
364 yield* worker.enqueue(undefined);
365 yield* worker.drain;
366 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
367 );
368 yield* forkParked(
369 Stream.runForEach(settingsChanges, (settings) => {
370 const key = autoSettlementSettingsKey(settings);
371 if (key === lastSettlementSettings) {
372 return Effect.void;
373 }
374 lastSettlementSettings = key;
375 return worker.enqueue(undefined);
376 }),
377 );
378 yield* forkParked(Stream.runForEach(mergedPullRequests, (event) => runSweep(event)));
379 yield* forkParked(Stream.runForEach(events, processEvent));
380 });
381
382 return { start, drain: worker.drain } satisfies ThreadSettlementReactor["Service"];
383});
384
385export const layer = Layer.effect(ThreadSettlementReactor, make);