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
165 const updateSettings = (patch: ServerSettingsPatch) =>
166 Effect.gen(function* () {
167 const next = applyServerSettingsPatch(yield* Ref.get(settings), patch);
168 yield* Ref.set(settings, next);
169 yield* PubSub.publish(settingsChanges, next);
170 return next;
171 });
172
173 const branchPullRequest: GitManager["Service"]["branchPullRequest"] = (input) =>
174 Ref.update(branchCalls, (calls) => [...calls, input]).pipe(
175 Effect.andThen(options.branchPullRequest?.(input) ?? Effect.succeed(null)),
176 );
177 const pullRequestSummary: PullRequestService["Service"]["summary"] = (input, readOptions) =>
178 Effect.gen(function* () {
179 yield* Ref.update(summaryCalls, (calls) => [...calls, input]);
180 yield* Ref.update(summaryRecovery, (values) => [
181 ...values,
182 readOptions?.recoverTransientFailure,
183 ]);
184 return yield* (
185 options.pullRequestSummary?.(input, readOptions) ??
186 Effect.succeed(
187 makePullRequestSummary({
188 ...input,
189 state: "open",
190 }),
191 )
192 );
193 });
194
195 const dispatch: OrchestrationEngineShape["dispatch"] = (command) => {
196 if (command.type !== "thread.auto-settle") {
197 return Effect.die(new Error(`Unexpected command: ${command.type}`));
198 }
199 return Ref.update(commands, (recorded) => [...recorded, command]).pipe(
200 Effect.andThen(options.onDispatch?.(command) ?? Effect.void),
201 Effect.as({ sequence: 1 }),
202 );
203 };
204
205 const serverSettings = ServerSettingsService.of({
206 start: Effect.void,
207 ready: Effect.void,
208 getSettings: Ref.get(settings),
209 updateSettings,
210 streamChanges: Stream.fromPubSub(settingsChanges),
211 subscribeChanges: PubSub.subscribe(settingsChanges).pipe(
212 Effect.map((subscription) => Stream.fromSubscription(subscription)),
213 ),
214 });
215
216 const dependencies = Layer.mergeAll(
217 Layer.mock(ProjectionSnapshotQuery)({
218 getShellSnapshot: () =>
219 Ref.updateAndGet(snapshotReadCount, (count) => count + 1).pipe(
220 Effect.tap((count) => Queue.offer(snapshotReads, count)),
221 Effect.andThen(Ref.get(snapshots)),
222 ),
223 }),
224 Layer.mock(GitManager)({ branchPullRequest }),
225 Layer.mock(PullRequestService)({
226 summary: pullRequestSummary,
227 subscribeMerges: PubSub.subscribe(mergedPullRequests).pipe(
228 Effect.map((subscription) => Stream.fromSubscription(subscription)),
229 ),
230 }),
231 Layer.mock(OrchestrationEngineService)({
232 readEvents: () => Stream.empty,
233 dispatch,
234 streamDomainEvents: Stream.empty,
235 latestSequence: Effect.succeed(0),
236 }),
237 Layer.succeed(ServerSettingsService, serverSettings),
238 Layer.succeed(ServerActivation, Deferred.await(activation)),
239 Layer.succeed(Crypto.Crypto, testCrypto),
240 FileSystem.layerNoop({
241 exists: (path) => Effect.succeed(options.existingWorktreePaths?.includes(path) ?? false),
242 }),
243 );
244
245 return {
246 activation,
247 snapshots,
248 snapshotReadCount,
249 snapshotReads,
250 commands,
251 branchCalls,
252 summaryCalls,
253 summaryRecovery,
254 updateSettings,
255 publishMerge: PubSub.publish(mergedPullRequests, {
256 projectId: PROJECT_ID,
257 repository: "owner/repository",
258 number: 42,
259 mergedAt: NOW,
260 }),
261 layer: ThreadSettlementReactor.layer.pipe(Layer.provide(dependencies)),
262 };
263});
264
265const startHarness = Effect.fn("startThreadSettlementHarness")(function* (
266 reactor: ThreadSettlementReactor.ThreadSettlementReactor["Service"],
267 activation: Deferred.Deferred<void>,
268 snapshotReads: Queue.Queue<number>,
269) {
270 yield* reactor.start();
271 yield* Deferred.succeed(activation, undefined);
272 yield* Queue.take(snapshotReads);
273 yield* reactor.drain;
274});
275
276describe("ThreadSettlementReactor", () => {
277 it.effect("starts without clients and skips protected threads before pull request lookup", () =>
278 Effect.scoped(
279 Effect.gen(function* () {
280 yield* TestClock.setTime(Date.parse(NOW));
281 const linkedPullRequest = {
282 projectId: LINKED_PROJECT_ID,
283 repository: "owner/repository",
284 number: 42,
285 url: "https://example.test/owner/repository/pull/42",
286 } as const;
287 const skipped = [
288 makeThread("pending-approval", {
289 branch: "skip-approval",
290 hasPendingApprovals: true,
291 }),
292 makeThread("snoozed", {
293 branch: "skip-snoozed",
294 snoozedUntil: "2026-08-29T00:00:00.000Z",
295 }),
296 ];
297 const fixture = yield* makeHarness({
298 snapshot: makeSnapshot(
299 [
300 makeThread("inactive", { branch: "inactive-feature" }),
301 makeThread("closed-pr", { linkedPullRequest }),
302 ...skipped,
303 ],
304 [makeProject(), makeProject(LINKED_PROJECT_ID, "/workspace/linked")],
305 ),
306 branchPullRequest: () => Effect.succeed(null),
307 pullRequestSummary: (input) =>
308 Effect.succeed(makePullRequestSummary({ ...input, state: "closed" })),
309 });
310
311 yield* Effect.gen(function* () {
312 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
313 yield* reactor.start();
314 assert.strictEqual(yield* Ref.get(fixture.snapshotReadCount), 0);
315
316 yield* Deferred.succeed(fixture.activation, undefined);
317 yield* Queue.take(fixture.snapshotReads);
318 yield* reactor.drain;
319
320 const commands = yield* Ref.get(fixture.commands);
321 assert.deepStrictEqual(
322 commands
323 .map(({ threadId, snapshotSequence, settledAt }) => ({
324 threadId,
325 snapshotSequence,
326 settledAt,
327 }))
328 .sort((left, right) => left.threadId.localeCompare(right.threadId)),
329 [
330 {
331 threadId: ThreadId.make("closed-pr"),
332 snapshotSequence: 1,
333 settledAt: "2026-08-20T00:00:00.000Z",
334 },
335 {
336 threadId: ThreadId.make("inactive"),
337 snapshotSequence: 1,
338 settledAt: "2026-08-20T00:00:00.000Z",
339 },
340 ],
341 );
342 assert.deepStrictEqual(yield* Ref.get(fixture.branchCalls), [
343 { cwd: "/workspace/project", branch: "inactive-feature" },
344 ]);
345 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), [
346 { projectId: LINKED_PROJECT_ID, repository: "owner/repository", number: 42 },
347 ]);
348 assert.deepStrictEqual(yield* Ref.get(fixture.summaryRecovery), [false]);
349 }).pipe(Effect.provide(fixture.layer));
350 }),
351 ),
352 );
353
354 it.effect("reevaluates inactivity and pull request state once per minute", () =>
355 Effect.scoped(
356 Effect.gen(function* () {
357 yield* TestClock.setTime(Date.parse(NOW));
358 const pullRequest = yield* Ref.make<"open" | "merged">("open");
359 const fixture = yield* makeHarness({
360 snapshot: makeSnapshot([
361 makeThread("at-boundary", {
362 latestUserMessageAt: "2026-08-25T12:00:00.000Z",
363 }),
364 makeThread("open-pr", {
365 branch: "saved-feature",
366 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
367 }),
368 ]),
369 branchPullRequest: () =>
370 Ref.get(pullRequest).pipe(Effect.map((state) => ({ state, updatedAt: NOW }))),
371 });
372
373 yield* Effect.gen(function* () {
374 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
375 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
376 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
377
378 yield* Ref.set(pullRequest, "merged");
379 yield* TestClock.adjust("1 minute");
380 yield* Queue.take(fixture.snapshotReads);
381 yield* reactor.drain;
382
383 assert.deepStrictEqual(
384 (yield* Ref.get(fixture.commands))
385 .map((command) => command.threadId)
386 .sort((left, right) => left.localeCompare(right)),
387 [ThreadId.make("at-boundary"), ThreadId.make("open-pr")],
388 );
389 assert.strictEqual((yield* Ref.get(fixture.branchCalls)).length, 2);
390 }).pipe(Effect.provide(fixture.layer));
391 }),
392 ),
393 );
394
395 it.effect("reevaluates immediately after a pull request merge", () =>
396 Effect.scoped(
397 Effect.gen(function* () {
398 yield* TestClock.setTime(Date.parse(NOW));
399 const periodicLookupStarted = yield* Deferred.make<void>();
400 const releasePeriodicLookup = yield* Deferred.make<void>();
401 const mergedThreadSettled = yield* Deferred.make<void>();
402 const branchLookupCount = yield* Ref.make(0);
403 const fixture = yield* makeHarness({
404 snapshot: makeSnapshot([
405 makeThread("merged-in-app", {
406 linkedPullRequest: {
407 projectId: PROJECT_ID,
408 repository: "owner/repository",
409 number: 42,
410 url: "https://example.test/owner/repository/pull/42",
411 },
412 }),
413 makeThread("slow-periodic-lookup", { branch: "another-feature" }),
414 ]),
415 branchPullRequest: () =>
416 Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
417 Effect.flatMap((count) =>
418 count === 1
419 ? Effect.succeed({ state: "open" as const, updatedAt: NOW })
420 : Deferred.succeed(periodicLookupStarted, undefined).pipe(
421 Effect.andThen(Deferred.await(releasePeriodicLookup)),
422 Effect.as({ state: "open" as const, updatedAt: NOW }),
423 ),
424 ),
425 ),
426 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
427 });
428
429 yield* Effect.gen(function* () {
430 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
431 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
432 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
433 yield* Deferred.await(periodicLookupStarted);
434
435 yield* fixture.publishMerge;
436 yield* Deferred.await(mergedThreadSettled);
437
438 assert.deepStrictEqual(
439 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
440 [ThreadId.make("merged-in-app")],
441 );
442 yield* Deferred.succeed(releasePeriodicLookup, undefined);
443 yield* reactor.drain;
444 }).pipe(Effect.provide(fixture.layer));
445 }),
446 ),
447 );
448
449 it.effect("uses fresh settlement settings after lookup and ignores unrelated changes", () =>
450 Effect.scoped(
451 Effect.gen(function* () {
452 yield* TestClock.setTime(Date.parse(NOW));
453 const state = yield* Ref.make<"merged" | "closed">("merged");
454 const firstLookupStarted = yield* Deferred.make<void>();
455 const releaseFirstLookup = yield* Deferred.make<void>();
456 const laterLookupStarted = yield* Deferred.make<void>();
457 const releaseLaterLookup = yield* Deferred.make<void>();
458 const lookupCount = yield* Ref.make(0);
459 const fixture = yield* makeHarness({
460 snapshot: makeSnapshot([makeThread("settings-thread", { branch: "saved-feature" })]),
461 settings: {
462 ...DEFAULT_SERVER_SETTINGS,
463 sidebarAutoSettleAfterDays: null,
464 sidebarAutoSettleOnMerge: true,
465 },
466 branchPullRequest: () =>
467 Ref.updateAndGet(lookupCount, (count) => count + 1).pipe(
468 Effect.tap((count) =>
469 count === 1
470 ? Deferred.succeed(firstLookupStarted, undefined)
471 : count === 3
472 ? Deferred.succeed(laterLookupStarted, undefined)
473 : Effect.void,
474 ),
475 Effect.tap((count) =>
476 count === 1
477 ? Deferred.await(releaseFirstLookup)
478 : count === 3
479 ? Deferred.await(releaseLaterLookup)
480 : Effect.void,
481 ),
482 Effect.andThen(Ref.get(state)),
483 Effect.map((pullRequestState) => ({ state: pullRequestState, updatedAt: NOW })),
484 ),
485 });
486
487 yield* Effect.gen(function* () {
488 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
489 yield* reactor.start();
490 yield* Deferred.succeed(fixture.activation, undefined);
491 yield* Queue.take(fixture.snapshotReads);
492 yield* Deferred.await(firstLookupStarted);
493
494 yield* fixture.updateSettings({ sidebarAutoSettleOnMerge: false });
495 yield* Deferred.succeed(releaseFirstLookup, undefined);
496 yield* Queue.take(fixture.snapshotReads);
497 yield* reactor.drain;
498 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
499 assert.strictEqual(yield* Ref.get(fixture.snapshotReadCount), 2);
500
501 yield* Ref.set(state, "closed");
502 yield* fixture.updateSettings({ enableAgentBrowserAccess: false });
503 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 1 });
504 yield* Deferred.await(laterLookupStarted);
505 yield* Deferred.succeed(releaseLaterLookup, undefined);
506 yield* reactor.drain;
507
508 assert.strictEqual(yield* Ref.get(fixture.snapshotReadCount), 3);
509 assert.strictEqual(yield* Ref.get(lookupCount), 3);
510 assert.deepStrictEqual(
511 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
512 [ThreadId.make("settings-thread")],
513 );
514 }).pipe(Effect.provide(fixture.layer));
515 }),
516 ),
517 );
518
519 it.effect("keeps an unknown pull request active and continues with other candidates", () =>
520 Effect.scoped(
521 Effect.gen(function* () {
522 yield* TestClock.setTime(Date.parse(NOW));
523 const fixture = yield* makeHarness({
524 snapshot: makeSnapshot(
525 [
526 makeThread("lookup-failed", {
527 linkedPullRequest: {
528 projectId: LINKED_PROJECT_ID,
529 repository: "owner/repository",
530 number: 9,
531 url: "https://example.test/owner/repository/pull/9",
532 },
533 }),
534 makeThread("inactive-without-pr"),
535 ],
536 [makeProject(), makeProject(LINKED_PROJECT_ID, "/workspace/linked")],
537 ),
538 pullRequestSummary: () =>
539 Effect.fail(
540 new PullRequestOperationError({
541 operation: "summary",
542 detail: "host unavailable",
543 }),
544 ),
545 });
546
547 yield* Effect.gen(function* () {
548 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
549 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
550
551 assert.deepStrictEqual(
552 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
553 [ThreadId.make("inactive-without-pr")],
554 );
555 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
556 }).pipe(Effect.provide(fixture.layer));
557 }),
558 ),
559 );
560
561 it.effect("keeps threads active when their pull request project is unavailable", () =>
562 Effect.scoped(
563 Effect.gen(function* () {
564 yield* TestClock.setTime(Date.parse(NOW));
565 const linkedPullRequest = {
566 projectId: LINKED_PROJECT_ID,
567 repository: "owner/repository",
568 number: 10,
569 url: "https://example.test/owner/repository/pull/10",
570 } as const;
571 const fixture = yield* makeHarness({
572 snapshot: makeSnapshot(
573 [
574 makeThread("missing-own-project", { linkedPullRequest }),
575 makeThread("missing-branch-project", { branch: "saved-feature" }),
576 ],
577 [makeProject(LINKED_PROJECT_ID, "/workspace/linked")],
578 ),
579 pullRequestSummary: (input) =>
580 Effect.succeed(makePullRequestSummary({ ...input, state: "open" })),
581 });
582
583 yield* Effect.gen(function* () {
584 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
585 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
586
587 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
588 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), [
589 { projectId: LINKED_PROJECT_ID, repository: "owner/repository", number: 10 },
590 ]);
591 assert.deepStrictEqual(yield* Ref.get(fixture.branchCalls), []);
592 }).pipe(Effect.provide(fixture.layer));
593 }),
594 ),
595 );
596
597 it.effect("deduplicates saved-branch and linked pull request lookups within a sweep", () =>
598 Effect.scoped(
599 Effect.gen(function* () {
600 yield* TestClock.setTime(Date.parse(NOW));
601 const linkedPullRequest = {
602 projectId: LINKED_PROJECT_ID,
603 repository: "owner/repository",
604 number: 77,
605 url: "https://example.test/owner/repository/pull/77",
606 } as const;
607 const fixture = yield* makeHarness({
608 snapshot: makeSnapshot(
609 [
610 makeThread("branch-one", {
611 branch: "saved-feature",
612 worktreePath: "/deleted/worktree-one",
613 }),
614 makeThread("branch-two", {
615 branch: "saved-feature",
616 worktreePath: "/deleted/worktree-two",
617 }),
618 makeThread("linked-one", { linkedPullRequest }),
619 makeThread("linked-two", { linkedPullRequest }),
620 ],
621 [
622 makeProject(PROJECT_ID, "/workspace/project-root"),
623 makeProject(LINKED_PROJECT_ID, "/workspace/linked-root"),
624 ],
625 ),
626 branchPullRequest: () => Effect.succeed({ state: "closed", updatedAt: NOW }),
627 pullRequestSummary: (input) =>
628 Effect.succeed(makePullRequestSummary({ ...input, state: "merged" })),
629 });
630
631 yield* Effect.gen(function* () {
632 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
633 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
634
635 assert.deepStrictEqual(yield* Ref.get(fixture.branchCalls), [
636 { cwd: "/workspace/project-root", branch: "saved-feature" },
637 ]);
638 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), [
639 { projectId: LINKED_PROJECT_ID, repository: "owner/repository", number: 77 },
640 ]);
641 assert.deepStrictEqual(
642 new Set((yield* Ref.get(fixture.commands)).map((command) => command.threadId)),
643 new Set([
644 ThreadId.make("branch-one"),
645 ThreadId.make("branch-two"),
646 ThreadId.make("linked-one"),
647 ThreadId.make("linked-two"),
648 ]),
649 );
650 }).pipe(Effect.provide(fixture.layer));
651 }),
652 ),
653 );
654
655 it.effect("looks up the branch pull request from a thread's live worktree", () =>
656 Effect.scoped(
657 Effect.gen(function* () {
658 yield* TestClock.setTime(Date.parse(NOW));
659 const fixture = yield* makeHarness({
660 snapshot: makeSnapshot(
661 [
662 makeThread("live-worktree", {
663 branch: "feature/live",
664 worktreePath: "/workspace/project-root/.worktrees/live",
665 }),
666 makeThread("deleted-worktree", {
667 branch: "feature/deleted",
668 worktreePath: "/workspace/project-root/.worktrees/deleted",
669 }),
670 ],
671 [makeProject(PROJECT_ID, "/workspace/project-root")],
672 ),
673 existingWorktreePaths: ["/workspace/project-root/.worktrees/live"],
674 });
675
676 yield* Effect.gen(function* () {
677 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
678 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
679
680 assert.deepStrictEqual(
681 new Set(yield* Ref.get(fixture.branchCalls)),
682 new Set([
683 { cwd: "/workspace/project-root/.worktrees/live", branch: "feature/live" },
684 { cwd: "/workspace/project-root", branch: "feature/deleted" },
685 ]),
686 );
687 }).pipe(Effect.provide(fixture.layer));
688 }),
689 ),
690 );
691
692 it.effect("carries the snapshot guard and survives a stale dispatch rejection", () =>
693 Effect.scoped(
694 Effect.gen(function* () {
695 yield* TestClock.setTime(Date.parse(NOW));
696 const fixture = yield* makeHarness({
697 snapshot: makeSnapshot([makeThread("stale"), makeThread("next-candidate")]),
698 onDispatch: (command) =>
699 command.threadId === ThreadId.make("stale")
700 ? Effect.fail(
701 new OrchestrationCommandInvariantError({
702 commandType: command.type,
703 detail: "thread changed after settlement evaluation",
704 }),
705 )
706 : Effect.void,
707 });
708
709 yield* Effect.gen(function* () {
710 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
711 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
712
713 const firstSweep = yield* Ref.get(fixture.commands);
714 assert.strictEqual(
715 firstSweep.find((command) => command.threadId === ThreadId.make("stale"))
716 ?.snapshotSequence,
717 1,
718 );
719 assert.strictEqual(
720 firstSweep.some((command) => command.threadId === ThreadId.make("next-candidate")),
721 true,
722 );
723
724 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
725 yield* Queue.take(fixture.snapshotReads);
726 yield* reactor.drain;
727 assert.strictEqual((yield* Ref.get(fixture.commands)).length, 4);
728 }).pipe(Effect.provide(fixture.layer));
729 }),
730 ),
731 );
732});