Open History to see the last commit
1import {
2 DEFAULT_SERVER_SETTINGS,
3 ProjectId,
4 ProviderInstanceId,
5 PullRequestOperationError,
6 ThreadId,
7 type OrchestrationCommand,
8 type OrchestrationProjectShell,
9 type OrchestrationShellSnapshot,
10 type OrchestrationThreadShell,
11 type PullRequestSummary,
12 type ServerSettings,
13 type ServerSettingsPatch,
14} from "@t3tools/contracts";
15import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
16import { assert, describe, it } from "@effect/vitest";
17import * as Crypto from "effect/Crypto";
18import * as Deferred from "effect/Deferred";
19import * as Effect from "effect/Effect";
20import * as FileSystem from "effect/FileSystem";
21import * as Layer from "effect/Layer";
22import * as PubSub from "effect/PubSub";
23import * as Queue from "effect/Queue";
24import * as Ref from "effect/Ref";
25import * as Stream from "effect/Stream";
26import { TestClock } from "effect/testing";
27
28import { GitManager } from "../git/GitManager.ts";
29import {
30 PullRequestService,
31 type PullRequestMergeEvent,
32} from "../pullRequest/PullRequestService.ts";
33import { ServerActivation } from "../serverActivation.ts";
34import { ServerSettingsService } from "../serverSettings.ts";
35import { OrchestrationCommandInvariantError } from "./Errors.ts";
36import {
37 OrchestrationEngineService,
38 type OrchestrationEngineShape,
39} from "./Services/OrchestrationEngine.ts";
40import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";
41import * as ThreadSettlementReactor from "./ThreadSettlementReactor.ts";
42
43const NOW = "2026-08-28T12:00:00.000Z";
44const PROJECT_ID = ProjectId.make("settlement-project");
45const LINKED_PROJECT_ID = ProjectId.make("linked-settlement-project");
46
47type AutoSettleCommand = Extract<OrchestrationCommand, { readonly type: "thread.auto-settle" }>;
48
49const testCrypto = Crypto.make({
50 randomBytes: (size) => new Uint8Array(size).fill(1),
51 digest: (_algorithm, data) => Effect.succeed(data),
52});
53
54function makeProject(
55 id: ProjectId = PROJECT_ID,
56 workspaceRoot = "/workspace/project",
57): OrchestrationProjectShell {
58 return {
59 id,
60 title: `Project ${id}`,
61 workspaceRoot,
62 defaultModelSelection: null,
63 scripts: [],
64 createdAt: "2026-08-01T00:00:00.000Z",
65 updatedAt: NOW,
66 };
67}
68
69function makeThread(
70 id: string,
71 overrides: Partial<OrchestrationThreadShell> = {},
72): OrchestrationThreadShell {
73 return {
74 id: ThreadId.make(id),
75 projectId: PROJECT_ID,
76 title: id,
77 modelSelection: {
78 instanceId: ProviderInstanceId.make("codex"),
79 model: "gpt-5",
80 },
81 runtimeMode: "full-access",
82 interactionMode: "default",
83 branch: null,
84 worktreePath: null,
85 latestTurn: null,
86 createdAt: "2026-08-01T00:00:00.000Z",
87 updatedAt: "2026-08-20T00:00:00.000Z",
88 archivedAt: null,
89 settledOverride: null,
90 settledAt: null,
91 session: null,
92 latestUserMessageAt: "2026-08-20T00:00:00.000Z",
93 hasPendingApprovals: false,
94 hasPendingUserInput: false,
95 hasActionableProposedPlan: false,
96 ...overrides,
97 };
98}
99
100function makeSnapshot(
101 threads: ReadonlyArray<OrchestrationThreadShell>,
102 projects: ReadonlyArray<OrchestrationProjectShell> = [makeProject()],
103): OrchestrationShellSnapshot {
104 return {
105 snapshotSequence: 1,
106 projects,
107 threads,
108 updatedAt: NOW,
109 };
110}
111
112function makePullRequestSummary(input: {
113 readonly projectId: ProjectId;
114 readonly repository: string;
115 readonly number: number;
116 readonly state: "open" | "closed" | "merged";
117 readonly updatedAt?: string;
118}): PullRequestSummary {
119 return {
120 provider: "github",
121 projectId: input.projectId,
122 repository: input.repository,
123 number: input.number,
124 title: "Pull request",
125 url: `https://example.test/${input.repository}/pull/${input.number}`,
126 state: input.state,
127 headBranch: "feature",
128 baseBranch: "main",
129 updatedAt: input.updatedAt ?? NOW,
130 };
131}
132
133interface HarnessOptions {
134 readonly snapshot: OrchestrationShellSnapshot;
135 readonly settings?: ServerSettings;
136 readonly branchPullRequest?: GitManager["Service"]["branchPullRequest"];
137 readonly pullRequestSummary?: PullRequestService["Service"]["summary"];
138 readonly existingWorktreePaths?: ReadonlyArray<string>;
139 readonly onDispatch?: (
140 command: AutoSettleCommand,
141 ) => Effect.Effect<void, OrchestrationCommandInvariantError>;
142}
143
144const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: HarnessOptions) {
145 const activation = yield* Deferred.make<void>();
146 const snapshots = yield* Ref.make(options.snapshot);
147 const snapshotReadCount = yield* Ref.make(0);
148 const snapshotReads = yield* Queue.unbounded<number>();
149 const settings = yield* Ref.make(options.settings ?? DEFAULT_SERVER_SETTINGS);
150 const settingsChanges = yield* PubSub.unbounded<ServerSettings>();
151 const mergedPullRequests = yield* PubSub.unbounded<PullRequestMergeEvent>();
152 const commands = yield* Ref.make<ReadonlyArray<AutoSettleCommand>>([]);
153 const branchCalls = yield* Ref.make<
154 ReadonlyArray<{ readonly cwd: string; readonly branch: string }>
155 >([]);
156 const summaryCalls = yield* Ref.make<
157 ReadonlyArray<{
158 readonly projectId: ProjectId;
159 readonly repository: string;
160 readonly number: number;
161 }>
162 >([]);
163 const summaryRecovery = yield* Ref.make<ReadonlyArray<boolean | undefined>>([]);
164 const invalidatedCwds = yield* Ref.make<ReadonlyArray<string>>([]);
165
166 const updateSettings = (patch: ServerSettingsPatch) =>
167 Effect.gen(function* () {
168 const next = applyServerSettingsPatch(yield* Ref.get(settings), patch);
169 yield* Ref.set(settings, next);
170 yield* PubSub.publish(settingsChanges, next);
171 return next;
172 });
173
174 const branchPullRequest: GitManager["Service"]["branchPullRequest"] = (input) =>
175 Ref.update(branchCalls, (calls) => [...calls, input]).pipe(
176 Effect.andThen(options.branchPullRequest?.(input) ?? Effect.succeed(null)),
177 );
178 const pullRequestSummary: PullRequestService["Service"]["summary"] = (input, readOptions) =>
179 Effect.gen(function* () {
180 yield* Ref.update(summaryCalls, (calls) => [...calls, input]);
181 yield* Ref.update(summaryRecovery, (values) => [
182 ...values,
183 readOptions?.recoverTransientFailure,
184 ]);
185 return yield* (
186 options.pullRequestSummary?.(input, readOptions) ??
187 Effect.succeed(
188 makePullRequestSummary({
189 ...input,
190 state: "open",
191 }),
192 )
193 );
194 });
195
196 const dispatch: OrchestrationEngineShape["dispatch"] = (command) => {
197 if (command.type !== "thread.auto-settle") {
198 return Effect.die(new Error(`Unexpected command: ${command.type}`));
199 }
200 return Ref.update(commands, (recorded) => [...recorded, command]).pipe(
201 Effect.andThen(options.onDispatch?.(command) ?? Effect.void),
202 Effect.as({ sequence: 1 }),
203 );
204 };
205
206 const serverSettings = ServerSettingsService.of({
207 start: Effect.void,
208 ready: Effect.void,
209 getSettings: Ref.get(settings),
210 updateSettings,
211 streamChanges: Stream.fromPubSub(settingsChanges),
212 subscribeChanges: PubSub.subscribe(settingsChanges).pipe(
213 Effect.map((subscription) => Stream.fromSubscription(subscription)),
214 ),
215 });
216
217 const dependencies = Layer.mergeAll(
218 Layer.mock(ProjectionSnapshotQuery)({
219 getShellSnapshot: () =>
220 Ref.updateAndGet(snapshotReadCount, (count) => count + 1).pipe(
221 Effect.tap((count) => Queue.offer(snapshotReads, count)),
222 Effect.andThen(Ref.get(snapshots)),
223 ),
224 }),
225 Layer.mock(GitManager)({
226 branchPullRequest,
227 invalidateStatus: (cwd) => Ref.update(invalidatedCwds, (cwds) => [...cwds, cwd]),
228 }),
229 Layer.mock(PullRequestService)({
230 summary: pullRequestSummary,
231 subscribeMerges: PubSub.subscribe(mergedPullRequests).pipe(
232 Effect.map((subscription) => Stream.fromSubscription(subscription)),
233 ),
234 }),
235 Layer.mock(OrchestrationEngineService)({
236 readEvents: () => Stream.empty,
237 dispatch,
238 streamDomainEvents: Stream.empty,
239 latestSequence: Effect.succeed(0),
240 }),
241 Layer.succeed(ServerSettingsService, serverSettings),
242 Layer.succeed(ServerActivation, Deferred.await(activation)),
243 Layer.succeed(Crypto.Crypto, testCrypto),
244 FileSystem.layerNoop({
245 exists: (path) => Effect.succeed(options.existingWorktreePaths?.includes(path) ?? false),
246 }),
247 );
248
249 return {
250 activation,
251 snapshots,
252 snapshotReadCount,
253 snapshotReads,
254 commands,
255 branchCalls,
256 summaryCalls,
257 summaryRecovery,
258 invalidatedCwds,
259 updateSettings,
260 publishMerge: PubSub.publish(mergedPullRequests, {
261 projectId: PROJECT_ID,
262 repository: "owner/repository",
263 number: 42,
264 mergedAt: NOW,
265 }),
266 layer: ThreadSettlementReactor.layer.pipe(Layer.provide(dependencies)),
267 };
268});
269
270const startHarness = Effect.fn("startThreadSettlementHarness")(function* (
271 reactor: ThreadSettlementReactor.ThreadSettlementReactor["Service"],
272 activation: Deferred.Deferred<void>,
273 snapshotReads: Queue.Queue<number>,
274) {
275 yield* reactor.start();
276 yield* Deferred.succeed(activation, undefined);
277 yield* Queue.take(snapshotReads);
278 yield* reactor.drain;
279});
280
281describe("ThreadSettlementReactor", () => {
282 it.effect("starts without clients and skips protected threads before pull request lookup", () =>
283 Effect.scoped(
284 Effect.gen(function* () {
285 yield* TestClock.setTime(Date.parse(NOW));
286 const linkedPullRequest = {
287 projectId: LINKED_PROJECT_ID,
288 repository: "owner/repository",
289 number: 42,
290 url: "https://example.test/owner/repository/pull/42",
291 } as const;
292 const skipped = [
293 makeThread("pending-approval", {
294 branch: "skip-approval",
295 hasPendingApprovals: true,
296 }),
297 makeThread("snoozed", {
298 branch: "skip-snoozed",
299 snoozedUntil: "2026-08-29T00:00:00.000Z",
300 }),
301 ];
302 const fixture = yield* makeHarness({
303 snapshot: makeSnapshot(
304 [
305 makeThread("inactive", { branch: "inactive-feature" }),
306 makeThread("closed-pr", { linkedPullRequest }),
307 ...skipped,
308 ],
309 [makeProject(), makeProject(LINKED_PROJECT_ID, "/workspace/linked")],
310 ),
311 branchPullRequest: () => Effect.succeed(null),
312 pullRequestSummary: (input) =>
313 Effect.succeed(makePullRequestSummary({ ...input, state: "closed" })),
314 });
315
316 yield* Effect.gen(function* () {
317 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
318 yield* reactor.start();
319 assert.strictEqual(yield* Ref.get(fixture.snapshotReadCount), 0);
320
321 yield* Deferred.succeed(fixture.activation, undefined);
322 yield* Queue.take(fixture.snapshotReads);
323 yield* reactor.drain;
324
325 const commands = yield* Ref.get(fixture.commands);
326 assert.deepStrictEqual(
327 commands
328 .map(({ threadId, snapshotSequence, settledAt }) => ({
329 threadId,
330 snapshotSequence,
331 settledAt,
332 }))
333 .sort((left, right) => left.threadId.localeCompare(right.threadId)),
334 [
335 {
336 threadId: ThreadId.make("closed-pr"),
337 snapshotSequence: 1,
338 settledAt: "2026-08-20T00:00:00.000Z",
339 },
340 {
341 threadId: ThreadId.make("inactive"),
342 snapshotSequence: 1,
343 settledAt: "2026-08-20T00:00:00.000Z",
344 },
345 ],
346 );
347 assert.deepStrictEqual(yield* Ref.get(fixture.branchCalls), [
348 { cwd: "/workspace/project", branch: "inactive-feature" },
349 ]);
350 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), [
351 { projectId: LINKED_PROJECT_ID, repository: "owner/repository", number: 42 },
352 ]);
353 assert.deepStrictEqual(yield* Ref.get(fixture.summaryRecovery), [false]);
354 }).pipe(Effect.provide(fixture.layer));
355 }),
356 ),
357 );
358
359 it.effect("reevaluates inactivity and pull request state once per minute", () =>
360 Effect.scoped(
361 Effect.gen(function* () {
362 yield* TestClock.setTime(Date.parse(NOW));
363 const pullRequest = yield* Ref.make<"open" | "merged">("open");
364 const fixture = yield* makeHarness({
365 snapshot: makeSnapshot([
366 makeThread("at-boundary", {
367 latestUserMessageAt: "2026-08-25T12:00:00.000Z",
368 }),
369 makeThread("open-pr", {
370 branch: "saved-feature",
371 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
372 }),
373 ]),
374 branchPullRequest: () =>
375 Ref.get(pullRequest).pipe(Effect.map((state) => ({ state, updatedAt: NOW }))),
376 });
377
378 yield* Effect.gen(function* () {
379 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
380 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
381 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
382
383 yield* Ref.set(pullRequest, "merged");
384 yield* TestClock.adjust("1 minute");
385 yield* Queue.take(fixture.snapshotReads);
386 yield* reactor.drain;
387
388 assert.deepStrictEqual(
389 (yield* Ref.get(fixture.commands))
390 .map((command) => command.threadId)
391 .sort((left, right) => left.localeCompare(right)),
392 [ThreadId.make("at-boundary"), ThreadId.make("open-pr")],
393 );
394 assert.strictEqual((yield* Ref.get(fixture.branchCalls)).length, 2);
395 }).pipe(Effect.provide(fixture.layer));
396 }),
397 ),
398 );
399
400 it.effect("reevaluates immediately after a pull request merge", () =>
401 Effect.scoped(
402 Effect.gen(function* () {
403 yield* TestClock.setTime(Date.parse(NOW));
404 const periodicLookupStarted = yield* Deferred.make<void>();
405 const releasePeriodicLookup = yield* Deferred.make<void>();
406 const mergedThreadSettled = yield* Deferred.make<void>();
407 const branchLookupCount = yield* Ref.make(0);
408 const fixture = yield* makeHarness({
409 snapshot: makeSnapshot([
410 makeThread("merged-in-app", {
411 linkedPullRequest: {
412 projectId: PROJECT_ID,
413 repository: "owner/repository",
414 number: 42,
415 url: "https://example.test/owner/repository/pull/42",
416 },
417 }),
418 makeThread("slow-periodic-lookup", { branch: "another-feature" }),
419 ]),
420 branchPullRequest: () =>
421 Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
422 Effect.flatMap((count) =>
423 count === 1
424 ? Effect.succeed({ state: "open" as const, updatedAt: NOW })
425 : Deferred.succeed(periodicLookupStarted, undefined).pipe(
426 Effect.andThen(Deferred.await(releasePeriodicLookup)),
427 Effect.as({ state: "open" as const, updatedAt: NOW }),
428 ),
429 ),
430 ),
431 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
432 });
433
434 yield* Effect.gen(function* () {
435 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
436 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
437 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
438 yield* Deferred.await(periodicLookupStarted);
439
440 yield* fixture.publishMerge;
441 yield* Deferred.await(mergedThreadSettled);
442
443 assert.deepStrictEqual(
444 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
445 [ThreadId.make("merged-in-app")],
446 );
447 yield* Deferred.succeed(releasePeriodicLookup, undefined);
448 yield* reactor.drain;
449 }).pipe(Effect.provide(fixture.layer));
450 }),
451 ),
452 );
453
454 it.effect(
455 "settles branch threads on a pull request merge without waiting for the next sweep",
456 () =>
457 Effect.scoped(
458 Effect.gen(function* () {
459 yield* TestClock.setTime(Date.parse(NOW));
460 const state = yield* Ref.make<"open" | "merged">("open");
461 const mergedThreadSettled = yield* Deferred.make<void>();
462 const fixture = yield* makeHarness({
463 snapshot: makeSnapshot([makeThread("branch-thread", { branch: "saved-feature" })]),
464 branchPullRequest: () =>
465 Ref.get(state).pipe(
466 Effect.map((pullRequestState) => ({ state: pullRequestState, updatedAt: NOW })),
467 ),
468 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
469 });
470
471 yield* Effect.gen(function* () {
472 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
473 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
474 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
475 assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), []);
476
477 yield* Ref.set(state, "merged");
478 yield* fixture.publishMerge;
479 yield* Deferred.await(mergedThreadSettled);
480
481 assert.deepStrictEqual(
482 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
483 [ThreadId.make("branch-thread")],
484 );
485 assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), ["/workspace/project"]);
486 yield* reactor.drain;
487 }).pipe(Effect.provide(fixture.layer));
488 }),
489 ),
490 );
491
492 it.effect("a merge does not settle threads linked to an unrelated pull request", () =>
493 Effect.scoped(
494 Effect.gen(function* () {
495 yield* TestClock.setTime(Date.parse(NOW));
496 const mergedThreadSettled = yield* Deferred.make<void>();
497 const mergeLookupStarted = yield* Deferred.make<void>();
498 const releaseMergeLookup = yield* Deferred.make<void>();
499 const lookupCount = yield* Ref.make(0);
500 const fixture = yield* makeHarness({
501 snapshot: makeSnapshot([
502 makeThread("merged-in-app", {
503 linkedPullRequest: {
504 projectId: PROJECT_ID,
505 repository: "owner/repository",
506 number: 42,
507 url: "https://example.test/owner/repository/pull/42",
508 },
509 }),
510 makeThread("unrelated-linked", {
511 linkedPullRequest: {
512 projectId: PROJECT_ID,
513 repository: "owner/repository",
514 number: 99,
515 url: "https://example.test/owner/repository/pull/99",
516 },
517 }),
518 ]),
519 pullRequestSummary: (input) =>
520 Ref.updateAndGet(lookupCount, (count) => count + 1).pipe(
521 // The initial sweep looks up both linked threads; the merge
522 // sweep only looks up the unrelated one, since the merged
523 // thread settles from the event itself.
524 Effect.tap((count) =>
525 count === 3 ? Deferred.succeed(mergeLookupStarted, undefined) : Effect.void,
526 ),
527 Effect.tap((count) =>
528 count === 3 ? Deferred.await(releaseMergeLookup) : Effect.void,
529 ),
530 Effect.map(() => makePullRequestSummary({ ...input, state: "open" })),
531 ),
532 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
533 });
534
535 yield* Effect.gen(function* () {
536 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
537 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
538 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
539
540 yield* fixture.publishMerge;
541 yield* Deferred.await(mergeLookupStarted);
542 yield* Deferred.await(mergedThreadSettled);
543 yield* Deferred.succeed(releaseMergeLookup, undefined);
544 yield* reactor.drain;
545
546 assert.deepStrictEqual(
547 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
548 [ThreadId.make("merged-in-app")],
549 );
550 assert.deepStrictEqual(
551 (yield* Ref.get(fixture.summaryCalls))
552 .map((call) => call.number)
553 .toSorted((left, right) => left - right),
554 [42, 99, 99],
555 );
556 }).pipe(Effect.provide(fixture.layer));
557 }),
558 ),
559 );
560
561 it.effect("uses fresh settlement settings after lookup and ignores unrelated changes", () =>
562 Effect.scoped(
563 Effect.gen(function* () {
564 yield* TestClock.setTime(Date.parse(NOW));
565 const state = yield* Ref.make<"merged" | "closed">("merged");
566 const firstLookupStarted = yield* Deferred.make<void>();
567 const releaseFirstLookup = yield* Deferred.make<void>();
568 const laterLookupStarted = yield* Deferred.make<void>();
569 const releaseLaterLookup = yield* Deferred.make<void>();
570 const lookupCount = yield* Ref.make(0);
571 const fixture = yield* makeHarness({
572 snapshot: makeSnapshot([makeThread("settings-thread", { branch: "saved-feature" })]),
573 settings: {
574 ...DEFAULT_SERVER_SETTINGS,
575 sidebarAutoSettleAfterDays: null,
576 sidebarAutoSettleOnMerge: true,
577 },
578 branchPullRequest: () =>
579 Ref.updateAndGet(lookupCount, (count) => count + 1).pipe(
580 Effect.tap((count) =>
581 count === 1
582 ? Deferred.succeed(firstLookupStarted, undefined)
583 : count === 3
584 ? Deferred.succeed(laterLookupStarted, undefined)
585 : Effect.void,
586 ),
587 Effect.tap((count) =>
588 count === 1
589 ? Deferred.await(releaseFirstLookup)
590 : count === 3
591 ? Deferred.await(releaseLaterLookup)
592 : Effect.void,
593 ),
594 Effect.andThen(Ref.get(state)),
595 Effect.map((pullRequestState) => ({ state: pullRequestState, updatedAt: NOW })),
596 ),
597 });
598
599 yield* Effect.gen(function* () {
600 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
601 yield* reactor.start();
602 yield* Deferred.succeed(fixture.activation, undefined);
603 yield* Queue.take(fixture.snapshotReads);
604 yield* Deferred.await(firstLookupStarted);
605
606 yield* fixture.updateSettings({ sidebarAutoSettleOnMerge: false });
607 yield* Deferred.succeed(releaseFirstLookup, undefined);
608 yield* Queue.take(fixture.snapshotReads);
609 yield* reactor.drain;
610 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
611 assert.strictEqual(yield* Ref.get(fixture.snapshotReadCount), 2);
612
613 yield* Ref.set(state, "closed");
614 yield* fixture.updateSettings({ enableAgentBrowserAccess: false });
615 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 1 });
616 yield* Deferred.await(laterLookupStarted);
617 yield* Deferred.succeed(releaseLaterLookup, undefined);
618 yield* reactor.drain;
619
620 assert.strictEqual(yield* Ref.get(fixture.snapshotReadCount), 3);
621 assert.strictEqual(yield* Ref.get(lookupCount), 3);
622 assert.deepStrictEqual(
623 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
624 [ThreadId.make("settings-thread")],
625 );
626 }).pipe(Effect.provide(fixture.layer));
627 }),
628 ),
629 );
630
631 it.effect("keeps an unknown pull request active and continues with other candidates", () =>
632 Effect.scoped(
633 Effect.gen(function* () {
634 yield* TestClock.setTime(Date.parse(NOW));
635 const fixture = yield* makeHarness({
636 snapshot: makeSnapshot(
637 [
638 makeThread("lookup-failed", {
639 linkedPullRequest: {
640 projectId: LINKED_PROJECT_ID,
641 repository: "owner/repository",
642 number: 9,
643 url: "https://example.test/owner/repository/pull/9",
644 },
645 }),
646 makeThread("inactive-without-pr"),
647 ],
648 [makeProject(), makeProject(LINKED_PROJECT_ID, "/workspace/linked")],
649 ),
650 pullRequestSummary: () =>
651 Effect.fail(
652 new PullRequestOperationError({
653 operation: "summary",
654 detail: "host unavailable",
655 }),
656 ),
657 });
658
659 yield* Effect.gen(function* () {
660 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
661 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
662
663 assert.deepStrictEqual(
664 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
665 [ThreadId.make("inactive-without-pr")],
666 );
667 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
668 }).pipe(Effect.provide(fixture.layer));
669 }),
670 ),
671 );
672
673 it.effect("keeps threads active when their pull request project is unavailable", () =>
674 Effect.scoped(
675 Effect.gen(function* () {
676 yield* TestClock.setTime(Date.parse(NOW));
677 const linkedPullRequest = {
678 projectId: LINKED_PROJECT_ID,
679 repository: "owner/repository",
680 number: 10,
681 url: "https://example.test/owner/repository/pull/10",
682 } as const;
683 const fixture = yield* makeHarness({
684 snapshot: makeSnapshot(
685 [
686 makeThread("missing-own-project", { linkedPullRequest }),
687 makeThread("missing-branch-project", { branch: "saved-feature" }),
688 ],
689 [makeProject(LINKED_PROJECT_ID, "/workspace/linked")],
690 ),
691 pullRequestSummary: (input) =>
692 Effect.succeed(makePullRequestSummary({ ...input, state: "open" })),
693 });
694
695 yield* Effect.gen(function* () {
696 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
697 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
698
699 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
700 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), [
701 { projectId: LINKED_PROJECT_ID, repository: "owner/repository", number: 10 },
702 ]);
703 assert.deepStrictEqual(yield* Ref.get(fixture.branchCalls), []);
704 }).pipe(Effect.provide(fixture.layer));
705 }),
706 ),
707 );
708
709 it.effect("deduplicates saved-branch and linked pull request lookups within a sweep", () =>
710 Effect.scoped(
711 Effect.gen(function* () {
712 yield* TestClock.setTime(Date.parse(NOW));
713 const linkedPullRequest = {
714 projectId: LINKED_PROJECT_ID,
715 repository: "owner/repository",
716 number: 77,
717 url: "https://example.test/owner/repository/pull/77",
718 } as const;
719 const fixture = yield* makeHarness({
720 snapshot: makeSnapshot(
721 [
722 makeThread("branch-one", {
723 branch: "saved-feature",
724 worktreePath: "/deleted/worktree-one",
725 }),
726 makeThread("branch-two", {
727 branch: "saved-feature",
728 worktreePath: "/deleted/worktree-two",
729 }),
730 makeThread("linked-one", { linkedPullRequest }),
731 makeThread("linked-two", { linkedPullRequest }),
732 ],
733 [
734 makeProject(PROJECT_ID, "/workspace/project-root"),
735 makeProject(LINKED_PROJECT_ID, "/workspace/linked-root"),
736 ],
737 ),
738 branchPullRequest: () => Effect.succeed({ state: "closed", updatedAt: NOW }),
739 pullRequestSummary: (input) =>
740 Effect.succeed(makePullRequestSummary({ ...input, state: "merged" })),
741 });
742
743 yield* Effect.gen(function* () {
744 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
745 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
746
747 assert.deepStrictEqual(yield* Ref.get(fixture.branchCalls), [
748 { cwd: "/workspace/project-root", branch: "saved-feature" },
749 ]);
750 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), [
751 { projectId: LINKED_PROJECT_ID, repository: "owner/repository", number: 77 },
752 ]);
753 assert.deepStrictEqual(
754 new Set((yield* Ref.get(fixture.commands)).map((command) => command.threadId)),
755 new Set([
756 ThreadId.make("branch-one"),
757 ThreadId.make("branch-two"),
758 ThreadId.make("linked-one"),
759 ThreadId.make("linked-two"),
760 ]),
761 );
762 }).pipe(Effect.provide(fixture.layer));
763 }),
764 ),
765 );
766
767 it.effect("looks up the branch pull request from a thread's live worktree", () =>
768 Effect.scoped(
769 Effect.gen(function* () {
770 yield* TestClock.setTime(Date.parse(NOW));
771 const fixture = yield* makeHarness({
772 snapshot: makeSnapshot(
773 [
774 makeThread("live-worktree", {
775 branch: "feature/live",
776 worktreePath: "/workspace/project-root/.worktrees/live",
777 }),
778 makeThread("deleted-worktree", {
779 branch: "feature/deleted",
780 worktreePath: "/workspace/project-root/.worktrees/deleted",
781 }),
782 ],
783 [makeProject(PROJECT_ID, "/workspace/project-root")],
784 ),
785 existingWorktreePaths: ["/workspace/project-root/.worktrees/live"],
786 });
787
788 yield* Effect.gen(function* () {
789 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
790 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
791
792 assert.deepStrictEqual(
793 new Set(yield* Ref.get(fixture.branchCalls)),
794 new Set([
795 { cwd: "/workspace/project-root/.worktrees/live", branch: "feature/live" },
796 { cwd: "/workspace/project-root", branch: "feature/deleted" },
797 ]),
798 );
799 }).pipe(Effect.provide(fixture.layer));
800 }),
801 ),
802 );
803
804 it.effect("carries the snapshot guard and survives a stale dispatch rejection", () =>
805 Effect.scoped(
806 Effect.gen(function* () {
807 yield* TestClock.setTime(Date.parse(NOW));
808 const fixture = yield* makeHarness({
809 snapshot: makeSnapshot([makeThread("stale"), makeThread("next-candidate")]),
810 onDispatch: (command) =>
811 command.threadId === ThreadId.make("stale")
812 ? Effect.fail(
813 new OrchestrationCommandInvariantError({
814 commandType: command.type,
815 detail: "thread changed after settlement evaluation",
816 }),
817 )
818 : Effect.void,
819 });
820
821 yield* Effect.gen(function* () {
822 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
823 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
824
825 const firstSweep = yield* Ref.get(fixture.commands);
826 assert.strictEqual(
827 firstSweep.find((command) => command.threadId === ThreadId.make("stale"))
828 ?.snapshotSequence,
829 1,
830 );
831 assert.strictEqual(
832 firstSweep.some((command) => command.threadId === ThreadId.make("next-candidate")),
833 true,
834 );
835
836 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
837 yield* Queue.take(fixture.snapshotReads);
838 yield* reactor.drain;
839 assert.strictEqual((yield* Ref.get(fixture.commands)).length, 4);
840 }).pipe(Effect.provide(fixture.layer));
841 }),
842 ),
843 );
844});