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 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
412 linkedPullRequest: {
413 projectId: PROJECT_ID,
414 repository: "owner/repository",
415 number: 42,
416 url: "https://example.test/owner/repository/pull/42",
417 },
418 }),
419 makeThread("slow-periodic-lookup", {
420 branch: "another-feature",
421 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
422 }),
423 ]),
424 branchPullRequest: () =>
425 Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
426 Effect.flatMap((count) =>
427 count === 1
428 ? Effect.succeed({ state: "open" as const, updatedAt: NOW })
429 : Deferred.succeed(periodicLookupStarted, undefined).pipe(
430 Effect.andThen(Deferred.await(releasePeriodicLookup)),
431 Effect.as({ state: "open" as const, updatedAt: NOW }),
432 ),
433 ),
434 ),
435 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
436 });
437
438 yield* Effect.gen(function* () {
439 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
440 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
441 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
442 yield* Deferred.await(periodicLookupStarted);
443
444 yield* fixture.publishMerge;
445 yield* Deferred.await(mergedThreadSettled);
446
447 assert.deepStrictEqual(
448 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
449 [ThreadId.make("merged-in-app")],
450 );
451 yield* Deferred.succeed(releasePeriodicLookup, undefined);
452 yield* reactor.drain;
453 }).pipe(Effect.provide(fixture.layer));
454 }),
455 ),
456 );
457
458 it.effect(
459 "settles branch threads on a pull request merge without waiting for the next sweep",
460 () =>
461 Effect.scoped(
462 Effect.gen(function* () {
463 yield* TestClock.setTime(Date.parse(NOW));
464 const state = yield* Ref.make<"open" | "merged">("open");
465 const mergedThreadSettled = yield* Deferred.make<void>();
466 const fixture = yield* makeHarness({
467 snapshot: makeSnapshot([
468 makeThread("branch-thread", {
469 branch: "saved-feature",
470 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
471 }),
472 ]),
473 branchPullRequest: () =>
474 Ref.get(state).pipe(
475 Effect.map((pullRequestState) => ({ state: pullRequestState, updatedAt: NOW })),
476 ),
477 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
478 });
479
480 yield* Effect.gen(function* () {
481 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
482 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
483 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
484 assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), []);
485
486 yield* Ref.set(state, "merged");
487 yield* fixture.publishMerge;
488 yield* Deferred.await(mergedThreadSettled);
489
490 assert.deepStrictEqual(
491 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
492 [ThreadId.make("branch-thread")],
493 );
494 assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), ["/workspace/project"]);
495 yield* reactor.drain;
496 }).pipe(Effect.provide(fixture.layer));
497 }),
498 ),
499 );
500
501 it.effect("a merge does not settle threads linked to an unrelated pull request", () =>
502 Effect.scoped(
503 Effect.gen(function* () {
504 yield* TestClock.setTime(Date.parse(NOW));
505 const mergedThreadSettled = yield* Deferred.make<void>();
506 const mergeLookupStarted = yield* Deferred.make<void>();
507 const releaseMergeLookup = yield* Deferred.make<void>();
508 const lookupCount = yield* Ref.make(0);
509 const fixture = yield* makeHarness({
510 snapshot: makeSnapshot([
511 makeThread("merged-in-app", {
512 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
513 linkedPullRequest: {
514 projectId: PROJECT_ID,
515 repository: "owner/repository",
516 number: 42,
517 url: "https://example.test/owner/repository/pull/42",
518 },
519 }),
520 makeThread("unrelated-linked", {
521 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
522 linkedPullRequest: {
523 projectId: PROJECT_ID,
524 repository: "owner/repository",
525 number: 99,
526 url: "https://example.test/owner/repository/pull/99",
527 },
528 }),
529 ]),
530 pullRequestSummary: (input) =>
531 Ref.updateAndGet(lookupCount, (count) => count + 1).pipe(
532 // The initial sweep looks up both linked threads; the merge
533 // sweep only looks up the unrelated one, since the merged
534 // thread settles from the event itself.
535 Effect.tap((count) =>
536 count === 3 ? Deferred.succeed(mergeLookupStarted, undefined) : Effect.void,
537 ),
538 Effect.tap((count) =>
539 count === 3 ? Deferred.await(releaseMergeLookup) : Effect.void,
540 ),
541 Effect.map(() => makePullRequestSummary({ ...input, state: "open" })),
542 ),
543 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
544 });
545
546 yield* Effect.gen(function* () {
547 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
548 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
549 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
550
551 yield* fixture.publishMerge;
552 yield* Deferred.await(mergeLookupStarted);
553 yield* Deferred.await(mergedThreadSettled);
554 yield* Deferred.succeed(releaseMergeLookup, undefined);
555 yield* reactor.drain;
556
557 assert.deepStrictEqual(
558 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
559 [ThreadId.make("merged-in-app")],
560 );
561 assert.deepStrictEqual(
562 (yield* Ref.get(fixture.summaryCalls))
563 .map((call) => call.number)
564 .toSorted((left, right) => left - right),
565 [42, 99, 99],
566 );
567 }).pipe(Effect.provide(fixture.layer));
568 }),
569 ),
570 );
571
572 it.effect("uses fresh settlement settings after lookup and ignores unrelated changes", () =>
573 Effect.scoped(
574 Effect.gen(function* () {
575 yield* TestClock.setTime(Date.parse(NOW));
576 const state = yield* Ref.make<"merged" | "closed">("merged");
577 const firstLookupStarted = yield* Deferred.make<void>();
578 const releaseFirstLookup = yield* Deferred.make<void>();
579 const laterLookupStarted = yield* Deferred.make<void>();
580 const releaseLaterLookup = yield* Deferred.make<void>();
581 const lookupCount = yield* Ref.make(0);
582 const fixture = yield* makeHarness({
583 snapshot: makeSnapshot([makeThread("settings-thread", { branch: "saved-feature" })]),
584 settings: {
585 ...DEFAULT_SERVER_SETTINGS,
586 sidebarAutoSettleAfterDays: null,
587 sidebarAutoSettleOnMerge: true,
588 },
589 branchPullRequest: () =>
590 Ref.updateAndGet(lookupCount, (count) => count + 1).pipe(
591 Effect.tap((count) =>
592 count === 1
593 ? Deferred.succeed(firstLookupStarted, undefined)
594 : count === 3
595 ? Deferred.succeed(laterLookupStarted, undefined)
596 : Effect.void,
597 ),
598 Effect.tap((count) =>
599 count === 1
600 ? Deferred.await(releaseFirstLookup)
601 : count === 3
602 ? Deferred.await(releaseLaterLookup)
603 : Effect.void,
604 ),
605 Effect.andThen(Ref.get(state)),
606 Effect.map((pullRequestState) => ({ state: pullRequestState, updatedAt: NOW })),
607 ),
608 });
609
610 yield* Effect.gen(function* () {
611 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
612 yield* reactor.start();
613 yield* Deferred.succeed(fixture.activation, undefined);
614 yield* Queue.take(fixture.snapshotReads);
615 yield* Deferred.await(firstLookupStarted);
616
617 yield* fixture.updateSettings({ sidebarAutoSettleOnMerge: false });
618 yield* Deferred.succeed(releaseFirstLookup, undefined);
619 yield* Queue.take(fixture.snapshotReads);
620 yield* reactor.drain;
621 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
622 assert.strictEqual(yield* Ref.get(fixture.snapshotReadCount), 2);
623
624 yield* Ref.set(state, "closed");
625 yield* fixture.updateSettings({ enableAgentBrowserAccess: false });
626 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 1 });
627 yield* Deferred.await(laterLookupStarted);
628 yield* Deferred.succeed(releaseLaterLookup, undefined);
629 yield* reactor.drain;
630
631 assert.strictEqual(yield* Ref.get(fixture.snapshotReadCount), 3);
632 assert.strictEqual(yield* Ref.get(lookupCount), 3);
633 assert.deepStrictEqual(
634 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
635 [ThreadId.make("settings-thread")],
636 );
637 }).pipe(Effect.provide(fixture.layer));
638 }),
639 ),
640 );
641
642 it.effect("keeps an unknown pull request active and continues with other candidates", () =>
643 Effect.scoped(
644 Effect.gen(function* () {
645 yield* TestClock.setTime(Date.parse(NOW));
646 const fixture = yield* makeHarness({
647 snapshot: makeSnapshot(
648 [
649 makeThread("lookup-failed", {
650 linkedPullRequest: {
651 projectId: LINKED_PROJECT_ID,
652 repository: "owner/repository",
653 number: 9,
654 url: "https://example.test/owner/repository/pull/9",
655 },
656 }),
657 makeThread("inactive-without-pr"),
658 ],
659 [makeProject(), makeProject(LINKED_PROJECT_ID, "/workspace/linked")],
660 ),
661 pullRequestSummary: () =>
662 Effect.fail(
663 new PullRequestOperationError({
664 operation: "summary",
665 detail: "host unavailable",
666 }),
667 ),
668 });
669
670 yield* Effect.gen(function* () {
671 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
672 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
673
674 assert.deepStrictEqual(
675 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
676 [ThreadId.make("inactive-without-pr")],
677 );
678 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
679 }).pipe(Effect.provide(fixture.layer));
680 }),
681 ),
682 );
683
684 it.effect("keeps threads active when their pull request project is unavailable", () =>
685 Effect.scoped(
686 Effect.gen(function* () {
687 yield* TestClock.setTime(Date.parse(NOW));
688 const linkedPullRequest = {
689 projectId: LINKED_PROJECT_ID,
690 repository: "owner/repository",
691 number: 10,
692 url: "https://example.test/owner/repository/pull/10",
693 } as const;
694 const fixture = yield* makeHarness({
695 snapshot: makeSnapshot(
696 [
697 makeThread("missing-own-project", {
698 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
699 linkedPullRequest,
700 }),
701 makeThread("missing-branch-project", { branch: "saved-feature" }),
702 ],
703 [makeProject(LINKED_PROJECT_ID, "/workspace/linked")],
704 ),
705 pullRequestSummary: (input) =>
706 Effect.succeed(makePullRequestSummary({ ...input, state: "open" })),
707 });
708
709 yield* Effect.gen(function* () {
710 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
711 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
712
713 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
714 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), [
715 { projectId: LINKED_PROJECT_ID, repository: "owner/repository", number: 10 },
716 ]);
717 assert.deepStrictEqual(yield* Ref.get(fixture.branchCalls), []);
718 }).pipe(Effect.provide(fixture.layer));
719 }),
720 ),
721 );
722
723 it.effect("deduplicates saved-branch and linked pull request lookups within a sweep", () =>
724 Effect.scoped(
725 Effect.gen(function* () {
726 yield* TestClock.setTime(Date.parse(NOW));
727 const linkedPullRequest = {
728 projectId: LINKED_PROJECT_ID,
729 repository: "owner/repository",
730 number: 77,
731 url: "https://example.test/owner/repository/pull/77",
732 } as const;
733 const fixture = yield* makeHarness({
734 snapshot: makeSnapshot(
735 [
736 makeThread("branch-one", {
737 branch: "saved-feature",
738 worktreePath: "/deleted/worktree-one",
739 }),
740 makeThread("branch-two", {
741 branch: "saved-feature",
742 worktreePath: "/deleted/worktree-two",
743 }),
744 makeThread("linked-one", { linkedPullRequest }),
745 makeThread("linked-two", { linkedPullRequest }),
746 ],
747 [
748 makeProject(PROJECT_ID, "/workspace/project-root"),
749 makeProject(LINKED_PROJECT_ID, "/workspace/linked-root"),
750 ],
751 ),
752 branchPullRequest: () => Effect.succeed({ state: "closed", updatedAt: NOW }),
753 pullRequestSummary: (input) =>
754 Effect.succeed(makePullRequestSummary({ ...input, state: "merged" })),
755 });
756
757 yield* Effect.gen(function* () {
758 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
759 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
760
761 assert.deepStrictEqual(yield* Ref.get(fixture.branchCalls), [
762 { cwd: "/workspace/project-root", branch: "saved-feature" },
763 ]);
764 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), [
765 { projectId: LINKED_PROJECT_ID, repository: "owner/repository", number: 77 },
766 ]);
767 assert.deepStrictEqual(
768 new Set((yield* Ref.get(fixture.commands)).map((command) => command.threadId)),
769 new Set([
770 ThreadId.make("branch-one"),
771 ThreadId.make("branch-two"),
772 ThreadId.make("linked-one"),
773 ThreadId.make("linked-two"),
774 ]),
775 );
776 }).pipe(Effect.provide(fixture.layer));
777 }),
778 ),
779 );
780
781 it.effect("looks up the branch pull request from a thread's live worktree", () =>
782 Effect.scoped(
783 Effect.gen(function* () {
784 yield* TestClock.setTime(Date.parse(NOW));
785 const fixture = yield* makeHarness({
786 snapshot: makeSnapshot(
787 [
788 makeThread("live-worktree", {
789 branch: "feature/live",
790 worktreePath: "/workspace/project-root/.worktrees/live",
791 }),
792 makeThread("deleted-worktree", {
793 branch: "feature/deleted",
794 worktreePath: "/workspace/project-root/.worktrees/deleted",
795 }),
796 ],
797 [makeProject(PROJECT_ID, "/workspace/project-root")],
798 ),
799 existingWorktreePaths: ["/workspace/project-root/.worktrees/live"],
800 });
801
802 yield* Effect.gen(function* () {
803 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
804 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
805
806 assert.deepStrictEqual(
807 new Set(yield* Ref.get(fixture.branchCalls)),
808 new Set([
809 { cwd: "/workspace/project-root/.worktrees/live", branch: "feature/live" },
810 { cwd: "/workspace/project-root", branch: "feature/deleted" },
811 ]),
812 );
813 }).pipe(Effect.provide(fixture.layer));
814 }),
815 ),
816 );
817
818 it.effect("carries the snapshot guard and survives a stale dispatch rejection", () =>
819 Effect.scoped(
820 Effect.gen(function* () {
821 yield* TestClock.setTime(Date.parse(NOW));
822 const fixture = yield* makeHarness({
823 snapshot: makeSnapshot([makeThread("stale"), makeThread("next-candidate")]),
824 onDispatch: (command) =>
825 command.threadId === ThreadId.make("stale")
826 ? Effect.fail(
827 new OrchestrationCommandInvariantError({
828 commandType: command.type,
829 detail: "thread changed after settlement evaluation",
830 }),
831 )
832 : Effect.void,
833 });
834
835 yield* Effect.gen(function* () {
836 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
837 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
838
839 const firstSweep = yield* Ref.get(fixture.commands);
840 assert.strictEqual(
841 firstSweep.find((command) => command.threadId === ThreadId.make("stale"))
842 ?.snapshotSequence,
843 1,
844 );
845 assert.strictEqual(
846 firstSweep.some((command) => command.threadId === ThreadId.make("next-candidate")),
847 true,
848 );
849
850 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
851 yield* Queue.take(fixture.snapshotReads);
852 yield* reactor.drain;
853 assert.strictEqual((yield* Ref.get(fixture.commands)).length, 4);
854 }).pipe(Effect.provide(fixture.layer));
855 }),
856 ),
857 );
858});