Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadSettlementReactor.test.ts

1,090 lines40.7 KB

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, type GitBranchPullRequest } 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 };
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 };
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 };
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 closedAt: input.state === "closed" ? (input.updatedAt ?? NOW) : null,
131 mergedAt: input.state === "merged" ? (input.updatedAt ?? NOW) : null,
132 };
134​
135function makeBranchPullRequest(
136 state: GitBranchPullRequest["state"],
137 updatedAt: string | null = NOW,
138): GitBranchPullRequest {
139 return {
140 number: 42,
141 title: "Branch pull request",
142 url: "https://example.test/owner/repository/pull/42",
143 baseRef: "main",
144 headRef: "saved-feature",
145 repositoryKey: "example.test/owner/repository",
146 state,
147 updatedAt,
148 closedAt: state === "closed" ? updatedAt : null,
149 mergedAt: state === "merged" ? updatedAt : null,
150 };
152​
153interface HarnessOptions {
154 readonly snapshot: OrchestrationShellSnapshot;
155 readonly settings?: ServerSettings;
156 readonly branchPullRequest?: GitManager["Service"]["branchPullRequest"];
157 readonly pullRequestSummary?: PullRequestService["Service"]["summary"];
158 readonly existingWorktreePaths?: ReadonlyArray<string>;
159 readonly onDispatch?: (
160 command: AutoSettleCommand,
161 ) => Effect.Effect<void, OrchestrationCommandInvariantError>;
163​
164const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: HarnessOptions) {
165 const activation = yield* Deferred.make<void>();
166 const snapshots = yield* Ref.make(options.snapshot);
167 const snapshotReadCount = yield* Ref.make(0);
168 const snapshotReads = yield* Queue.unbounded<number>();
169 const settings = yield* Ref.make(options.settings ?? DEFAULT_SERVER_SETTINGS);
170 const settingsChanges = yield* PubSub.unbounded<ServerSettings>();
171 const mergedPullRequests = yield* PubSub.unbounded<PullRequestMergeEvent>();
172 const commands = yield* Ref.make<ReadonlyArray<AutoSettleCommand>>([]);
173 const branchCalls = yield* Ref.make<
174 ReadonlyArray<{ readonly cwd: string; readonly branch: string }>
175 >([]);
176 const summaryCalls = yield* Ref.make<
177 ReadonlyArray<{
178 readonly projectId: ProjectId;
179 readonly repository: string;
180 readonly number: number;
181 }>
182 >([]);
183 const summaryRecovery = yield* Ref.make<ReadonlyArray<boolean | undefined>>([]);
184 const invalidatedCwds = yield* Ref.make<ReadonlyArray<string>>([]);
185​
186 const updateSettings = (patch: ServerSettingsPatch) =>
187 Effect.gen(function* () {
188 const next = applyServerSettingsPatch(yield* Ref.get(settings), patch);
189 yield* Ref.set(settings, next);
190 yield* PubSub.publish(settingsChanges, next);
191 return next;
192 });
193​
194 const branchPullRequest: GitManager["Service"]["branchPullRequest"] = (input, readOptions) =>
195 Ref.update(branchCalls, (calls) => [...calls, input]).pipe(
196 Effect.andThen(options.branchPullRequest?.(input, readOptions) ?? Effect.succeed(null)),
197 );
198 const pullRequestSummary: PullRequestService["Service"]["summary"] = (input, readOptions) =>
199 Effect.gen(function* () {
200 yield* Ref.update(summaryCalls, (calls) => [...calls, input]);
201 yield* Ref.update(summaryRecovery, (values) => [
202 ...values,
203 readOptions?.recoverTransientFailure,
204 ]);
205 return yield* (
206 options.pullRequestSummary?.(input, readOptions) ??
207 Effect.succeed(
208 makePullRequestSummary({
209 ...input,
210 state: "open",
211 }),
212 )
213 );
214 });
215​
216 const dispatch: OrchestrationEngineShape["dispatch"] = (command) => {
217 if (command.type !== "thread.auto-settle") {
218 return Effect.die(new Error(`Unexpected command: ${command.type}`));
219 }
220 return Ref.update(commands, (recorded) => [...recorded, command]).pipe(
221 Effect.andThen(options.onDispatch?.(command) ?? Effect.void),
222 Effect.as({ sequence: 1 }),
223 );
224 };
225​
226 const serverSettings = ServerSettingsService.of({
227 start: Effect.void,
228 ready: Effect.void,
229 getSettings: Ref.get(settings),
230 updateSettings,
231 streamChanges: Stream.fromPubSub(settingsChanges),
232 subscribeChanges: PubSub.subscribe(settingsChanges).pipe(
233 Effect.map((subscription) => Stream.fromSubscription(subscription)),
234 ),
235 });
236​
237 const dependencies = Layer.mergeAll(
238 Layer.mock(ProjectionSnapshotQuery)({
239 getShellSnapshot: () =>
240 Ref.updateAndGet(snapshotReadCount, (count) => count + 1).pipe(
241 Effect.tap((count) => Queue.offer(snapshotReads, count)),
242 Effect.andThen(Ref.get(snapshots)),
243 ),
244 }),
245 Layer.mock(GitManager)({
246 branchPullRequest,
247 invalidateStatus: (cwd) => Ref.update(invalidatedCwds, (cwds) => [...cwds, cwd]),
248 }),
249 Layer.mock(PullRequestService)({
250 summary: pullRequestSummary,
251 subscribeMerges: PubSub.subscribe(mergedPullRequests).pipe(
252 Effect.map((subscription) => Stream.fromSubscription(subscription)),
253 ),
254 }),
255 Layer.mock(OrchestrationEngineService)({
256 readEvents: () => Stream.empty,
257 dispatch,
258 streamDomainEvents: Stream.empty,
259 latestSequence: Effect.succeed(0),
260 }),
261 Layer.succeed(ServerSettingsService, serverSettings),
262 Layer.succeed(ServerActivation, Deferred.await(activation)),
263 Layer.succeed(Crypto.Crypto, testCrypto),
264 FileSystem.layerNoop({
265 exists: (path) => Effect.succeed(options.existingWorktreePaths?.includes(path) ?? false),
266 }),
267 );
268​
269 return {
270 activation,
271 snapshots,
272 snapshotReadCount,
273 snapshotReads,
274 commands,
275 branchCalls,
276 summaryCalls,
277 summaryRecovery,
278 invalidatedCwds,
279 updateSettings,
280 publishMerge: PubSub.publish(mergedPullRequests, {
281 projectId: PROJECT_ID,
282 repository: "owner/repository",
283 number: 42,
284 mergedAt: NOW,
285 }),
286 layer: ThreadSettlementReactor.layer.pipe(Layer.provide(dependencies)),
287 };
288});
289​
290const startHarness = Effect.fn("startThreadSettlementHarness")(function* (
291 reactor: ThreadSettlementReactor.ThreadSettlementReactor["Service"],
292 activation: Deferred.Deferred<void>,
293 snapshotReads: Queue.Queue<number>,
294) {
295 yield* reactor.start();
296 yield* Deferred.succeed(activation, undefined);
297 yield* Queue.take(snapshotReads);
298 yield* reactor.drain;
299});
300​
301describe("ThreadSettlementReactor", () => {
302 it.effect("uses saved PRs without settling resumed threads or branches with newer PRs", () =>
303 Effect.scoped(
304 Effect.gen(function* () {
305 yield* TestClock.setTime(Date.parse(NOW));
306 const previous = {
307 projectId: PROJECT_ID,
308 repository: "owner/repository",
309 number: 1,
310 url: "https://example.test/owner/repository/pull/1",
311 };
312 const project = {
313 ...makeProject(),
314 repositoryIdentity: {
315 canonicalKey: "example.test/owner/repository",
316 rootPath: "/workspace/project",
317 displayName: "owner/repository",
318 locator: {
319 source: "git-remote" as const,
320 remoteName: "origin",
321 remoteUrl: "https://example.test/owner/repository.git",
322 },
323 },
324 };
325 const fixture = yield* makeHarness({
326 snapshot: makeSnapshot(
327 [
328 makeThread("retained-terminal", { branch: "main", branchPullRequest: previous }),
329 makeThread("reused-manual", { branch: "reused", linkedPullRequest: previous }),
330 makeThread("reused-detected", { branch: "reused", branchPullRequest: previous }),
331 makeThread("foreign-branch-pr", { branch: "foreign", linkedPullRequest: previous }),
332 makeThread("resumed-manual", {
333 branch: "main",
334 linkedPullRequest: previous,
335 latestUserMessageAt: "2026-08-28T00:00:00.000Z",
336 }),
337 makeThread("resumed-detected", {
338 branch: "main",
339 branchPullRequest: previous,
340 latestUserMessageAt: "2026-08-28T00:00:00.000Z",
341 }),
342 ],
343 [project],
344 ),
345 settings: {
346 ...DEFAULT_SERVER_SETTINGS,
347 sidebarAutoSettleAfterDays: null,
348 sidebarAutoSettleOnMerge: true,
349 },
350 branchPullRequest: ({ branch }, options) =>
351 Effect.succeed(
352 branch === "reused"
353 ? makeBranchPullRequest(options?.refresh ? "open" : "merged")
354 : branch === "foreign"
355 ? {
356 ...makeBranchPullRequest("open"),
357 repositoryKey: "example.test/another/repository",
358 }
359 : null,
360 ),
361 pullRequestSummary: (input) =>
362 Effect.succeed({
363 ...makePullRequestSummary({ ...input, state: "merged" }),
364 mergedAt: "2026-08-27T00:00:00.000Z",
365 }),
366 });
367 yield* Effect.gen(function* () {
368 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
369 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
370 assert.deepStrictEqual(
371 new Set((yield* Ref.get(fixture.commands)).map((command) => command.threadId)),
372 new Set([ThreadId.make("retained-terminal"), ThreadId.make("foreign-branch-pr")]),
373 );
374 }).pipe(Effect.provide(fixture.layer));
375 }),
376 ),
377 );
378​
379 it.effect("starts without clients and skips protected threads before pull request lookup", () =>
380 Effect.scoped(
381 Effect.gen(function* () {
382 yield* TestClock.setTime(Date.parse(NOW));
383 const linkedPullRequest = {
384 projectId: LINKED_PROJECT_ID,
385 repository: "owner/repository",
386 number: 42,
387 url: "https://example.test/owner/repository/pull/42",
388 } as const;
389 const skipped = [
390 makeThread("pending-approval", {
391 branch: "skip-approval",
392 hasPendingApprovals: true,
393 }),
394 makeThread("snoozed", {
395 branch: "skip-snoozed",
396 snoozedUntil: "2026-08-29T00:00:00.000Z",
397 }),
398 ];
399 const fixture = yield* makeHarness({
400 snapshot: makeSnapshot(
401 [
402 makeThread("inactive", { branch: "inactive-feature" }),
403 makeThread("closed-pr", {
404 linkedPullRequest,
405 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
406 }),
407 ...skipped,
408 ],
409 [makeProject(), makeProject(LINKED_PROJECT_ID, "/workspace/linked")],
410 ),
411 branchPullRequest: () => Effect.succeed(null),
412 pullRequestSummary: (input) =>
413 Effect.succeed(makePullRequestSummary({ ...input, state: "closed" })),
414 });
415​
416 yield* Effect.gen(function* () {
417 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
418 yield* reactor.start();
419 assert.strictEqual(yield* Ref.get(fixture.snapshotReadCount), 0);
420​
421 yield* Deferred.succeed(fixture.activation, undefined);
422 yield* Queue.take(fixture.snapshotReads);
423 yield* reactor.drain;
424​
425 const commands = yield* Ref.get(fixture.commands);
426 assert.deepStrictEqual(
427 commands
428 .map(({ threadId, snapshotSequence, settledAt }) => ({
429 threadId,
430 snapshotSequence,
431 settledAt,
432 }))
433 .sort((left, right) => left.threadId.localeCompare(right.threadId)),
434 [
435 {
436 threadId: ThreadId.make("closed-pr"),
437 snapshotSequence: 1,
438 settledAt: "2026-08-27T00:00:00.000Z",
439 },
440 {
441 threadId: ThreadId.make("inactive"),
442 snapshotSequence: 1,
443 settledAt: "2026-08-20T00:00:00.000Z",
444 },
445 ],
446 );
447 assert.deepStrictEqual(yield* Ref.get(fixture.branchCalls), []);
448 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), [
449 { projectId: LINKED_PROJECT_ID, repository: "owner/repository", number: 42 },
450 ]);
451 assert.deepStrictEqual(yield* Ref.get(fixture.summaryRecovery), [false]);
452 }).pipe(Effect.provide(fixture.layer));
453 }),
454 ),
455 );
456​
457 it.effect("reevaluates inactivity and pull request state once per minute", () =>
458 Effect.scoped(
459 Effect.gen(function* () {
460 yield* TestClock.setTime(Date.parse(NOW));
461 const pullRequest = yield* Ref.make<"open" | "merged">("open");
462 const fixture = yield* makeHarness({
463 snapshot: makeSnapshot([
464 makeThread("at-boundary", {
465 latestUserMessageAt: "2026-08-25T12:00:00.000Z",
466 }),
467 makeThread("open-pr", {
468 branch: "saved-feature",
469 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
470 }),
471 ]),
472 branchPullRequest: () =>
473 Ref.get(pullRequest).pipe(Effect.map((state) => makeBranchPullRequest(state))),
474 });
475​
476 yield* Effect.gen(function* () {
477 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
478 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
479 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
480​
481 yield* Ref.set(pullRequest, "merged");
482 yield* TestClock.adjust("1 minute");
483 yield* Queue.take(fixture.snapshotReads);
484 yield* reactor.drain;
485​
486 assert.deepStrictEqual(
487 (yield* Ref.get(fixture.commands))
488 .map((command) => command.threadId)
489 .sort((left, right) => left.localeCompare(right)),
490 [ThreadId.make("at-boundary"), ThreadId.make("open-pr")],
491 );
492 assert.strictEqual((yield* Ref.get(fixture.branchCalls)).length, 2);
493 }).pipe(Effect.provide(fixture.layer));
494 }),
495 ),
496 );
497​
498 it.effect("reevaluates immediately after a pull request merge", () =>
499 Effect.scoped(
500 Effect.gen(function* () {
501 yield* TestClock.setTime(Date.parse(NOW));
502 const periodicLookupStarted = yield* Deferred.make<void>();
503 const releasePeriodicLookup = yield* Deferred.make<void>();
504 const mergedThreadSettled = yield* Deferred.make<void>();
505 const branchLookupCount = yield* Ref.make(0);
506 const fixture = yield* makeHarness({
507 snapshot: makeSnapshot([
508 makeThread("merged-in-app", {
509 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
510 linkedPullRequest: {
511 projectId: PROJECT_ID,
512 repository: "owner/repository",
513 number: 42,
514 url: "https://example.test/owner/repository/pull/42",
515 },
516 }),
517 makeThread("slow-periodic-lookup", {
518 branch: "another-feature",
519 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
520 }),
521 ]),
522 branchPullRequest: () =>
523 Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
524 Effect.flatMap((count) =>
525 count === 1
526 ? Effect.succeed(makeBranchPullRequest("open"))
527 : Deferred.succeed(periodicLookupStarted, undefined).pipe(
528 Effect.andThen(Deferred.await(releasePeriodicLookup)),
529 Effect.as(makeBranchPullRequest("open")),
530 ),
531 ),
532 ),
533 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
534 });
535​
536 yield* Effect.gen(function* () {
537 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
538 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
539 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
540 yield* Deferred.await(periodicLookupStarted);
541​
542 yield* fixture.publishMerge;
543 yield* Deferred.await(mergedThreadSettled);
544​
545 assert.deepStrictEqual(
546 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
547 [ThreadId.make("merged-in-app")],
548 );
549 yield* Deferred.succeed(releasePeriodicLookup, undefined);
550 yield* reactor.drain;
551 }).pipe(Effect.provide(fixture.layer));
552 }),
553 ),
554 );
555​
556 it.effect(
557 "settles branch threads on a pull request merge without waiting for the next sweep",
558 () =>
559 Effect.scoped(
560 Effect.gen(function* () {
561 yield* TestClock.setTime(Date.parse(NOW));
562 const state = yield* Ref.make<"open" | "merged">("open");
563 const mergedThreadSettled = yield* Deferred.make<void>();
564 const fixture = yield* makeHarness({
565 snapshot: makeSnapshot([
566 makeThread("branch-thread", {
567 branch: "saved-feature",
568 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
569 }),
570 ]),
571 branchPullRequest: () =>
572 Ref.get(state).pipe(
573 Effect.map((pullRequestState) => makeBranchPullRequest(pullRequestState)),
574 ),
575 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
576 });
577​
578 yield* Effect.gen(function* () {
579 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
580 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
581 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
582 assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), []);
583​
584 yield* Ref.set(state, "merged");
585 yield* fixture.publishMerge;
586 yield* Deferred.await(mergedThreadSettled);
587​
588 assert.deepStrictEqual(
589 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
590 [ThreadId.make("branch-thread")],
591 );
592 assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), ["/workspace/project"]);
593 yield* reactor.drain;
594 }).pipe(Effect.provide(fixture.layer));
595 }),
596 ),
597 );
598​
599 it.effect("a merge does not settle threads linked to an unrelated pull request", () =>
600 Effect.scoped(
601 Effect.gen(function* () {
602 yield* TestClock.setTime(Date.parse(NOW));
603 const mergedThreadSettled = yield* Deferred.make<void>();
604 const mergeLookupStarted = yield* Deferred.make<void>();
605 const releaseMergeLookup = yield* Deferred.make<void>();
606 const lookupCount = yield* Ref.make(0);
607 const fixture = yield* makeHarness({
608 snapshot: makeSnapshot([
609 makeThread("merged-in-app", {
610 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
611 linkedPullRequest: {
612 projectId: PROJECT_ID,
613 repository: "owner/repository",
614 number: 42,
615 url: "https://example.test/owner/repository/pull/42",
616 },
617 }),
618 makeThread("unrelated-linked", {
619 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
620 linkedPullRequest: {
621 projectId: PROJECT_ID,
622 repository: "owner/repository",
623 number: 99,
624 url: "https://example.test/owner/repository/pull/99",
625 },
626 }),
627 ]),
628 pullRequestSummary: (input) =>
629 Ref.updateAndGet(lookupCount, (count) => count + 1).pipe(
630 // The initial sweep looks up both linked threads; the merge
631 // sweep only looks up the unrelated one, since the merged
632 // thread settles from the event itself.
633 Effect.tap((count) =>
634 count === 3 ? Deferred.succeed(mergeLookupStarted, undefined) : Effect.void,
635 ),
636 Effect.tap((count) =>
637 count === 3 ? Deferred.await(releaseMergeLookup) : Effect.void,
638 ),
639 Effect.map(() => makePullRequestSummary({ ...input, state: "open" })),
640 ),
641 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
642 });
643​
644 yield* Effect.gen(function* () {
645 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
646 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
647 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
648​
649 yield* fixture.publishMerge;
650 yield* Deferred.await(mergeLookupStarted);
651 yield* Deferred.await(mergedThreadSettled);
652 yield* Deferred.succeed(releaseMergeLookup, undefined);
653 yield* reactor.drain;
654​
655 assert.deepStrictEqual(
656 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
657 [ThreadId.make("merged-in-app")],
658 );
659 assert.deepStrictEqual(
660 (yield* Ref.get(fixture.summaryCalls))
661 .map((call) => call.number)
662 .toSorted((left, right) => left - right),
663 [42, 99, 99],
664 );
665 }).pipe(Effect.provide(fixture.layer));
666 }),
667 ),
668 );
669​
670 it.effect("uses fresh settlement settings after lookup and ignores unrelated changes", () =>
671 Effect.scoped(
672 Effect.gen(function* () {
673 yield* TestClock.setTime(Date.parse(NOW));
674 const state = yield* Ref.make<"merged" | "closed">("merged");
675 const firstLookupStarted = yield* Deferred.make<void>();
676 const releaseFirstLookup = yield* Deferred.make<void>();
677 const laterLookupStarted = yield* Deferred.make<void>();
678 const releaseLaterLookup = yield* Deferred.make<void>();
679 const lookupCount = yield* Ref.make(0);
680 const fixture = yield* makeHarness({
681 snapshot: makeSnapshot([
682 makeThread("settings-thread", {
683 branch: "saved-feature",
684 latestUserMessageAt: "2026-08-28T00:00:00.000Z",
685 }),
686 ]),
687 settings: {
688 ...DEFAULT_SERVER_SETTINGS,
689 sidebarAutoSettleAfterDays: null,
690 sidebarAutoSettleOnMerge: true,
691 },
692 branchPullRequest: () =>
693 Ref.updateAndGet(lookupCount, (count) => count + 1).pipe(
694 Effect.tap((count) =>
695 count === 1
696 ? Deferred.succeed(firstLookupStarted, undefined)
697 : count === 3
698 ? Deferred.succeed(laterLookupStarted, undefined)
699 : Effect.void,
700 ),
701 Effect.tap((count) =>
702 count === 1
703 ? Deferred.await(releaseFirstLookup)
704 : count === 3
705 ? Deferred.await(releaseLaterLookup)
706 : Effect.void,
707 ),
708 Effect.andThen(Ref.get(state)),
709 Effect.map((pullRequestState) => makeBranchPullRequest(pullRequestState)),
710 ),
711 });
712​
713 yield* Effect.gen(function* () {
714 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
715 yield* reactor.start();
716 yield* Deferred.succeed(fixture.activation, undefined);
717 yield* Queue.take(fixture.snapshotReads);
718 yield* Deferred.await(firstLookupStarted);
719​
720 yield* fixture.updateSettings({ sidebarAutoSettleOnMerge: false });
721 yield* Deferred.succeed(releaseFirstLookup, undefined);
722 yield* Queue.take(fixture.snapshotReads);
723 yield* reactor.drain;
724 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
725 assert.strictEqual(yield* Ref.get(fixture.snapshotReadCount), 2);
726​
727 yield* Ref.set(state, "closed");
728 yield* fixture.updateSettings({ enableAgentBrowserAccess: false });
729 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 1 });
730 yield* Deferred.await(laterLookupStarted);
731 yield* Deferred.succeed(releaseLaterLookup, undefined);
732 yield* reactor.drain;
733​
734 assert.strictEqual(yield* Ref.get(fixture.snapshotReadCount), 3);
735 assert.strictEqual(yield* Ref.get(lookupCount), 3);
736 assert.deepStrictEqual(
737 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
738 [ThreadId.make("settings-thread")],
739 );
740 }).pipe(Effect.provide(fixture.layer));
741 }),
742 ),
743 );
744​
745 it.effect("keeps an unknown pull request active and continues with other candidates", () =>
746 Effect.scoped(
747 Effect.gen(function* () {
748 yield* TestClock.setTime(Date.parse(NOW));
749 const fixture = yield* makeHarness({
750 snapshot: makeSnapshot(
751 [
752 makeThread("lookup-failed", {
753 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
754 linkedPullRequest: {
755 projectId: LINKED_PROJECT_ID,
756 repository: "owner/repository",
757 number: 9,
758 url: "https://example.test/owner/repository/pull/9",
759 },
760 }),
761 makeThread("inactive-without-pr"),
762 ],
763 [makeProject(), makeProject(LINKED_PROJECT_ID, "/workspace/linked")],
764 ),
765 pullRequestSummary: () =>
766 Effect.fail(
767 new PullRequestOperationError({
768 operation: "summary",
769 detail: "host unavailable",
770 }),
771 ),
772 });
773​
774 yield* Effect.gen(function* () {
775 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
776 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
777​
778 assert.deepStrictEqual(
779 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
780 [ThreadId.make("inactive-without-pr")],
781 );
782 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
783 }).pipe(Effect.provide(fixture.layer));
784 }),
785 ),
786 );
787​
788 it.effect("settles inactive linked and branch threads without reading an unavailable host", () =>
789 Effect.scoped(
790 Effect.gen(function* () {
791 yield* TestClock.setTime(Date.parse(NOW));
792 const fixture = yield* makeHarness({
793 snapshot: makeSnapshot([
794 makeThread("inactive-linked", {
795 linkedPullRequest: {
796 projectId: PROJECT_ID,
797 repository: "owner/repository",
798 number: 42,
799 url: "https://example.test/owner/repository/pull/42",
800 },
801 }),
802 makeThread("inactive-branch", {
803 branch: "saved-feature",
804 latestUserMessageAt: "2026-08-21T00:00:00.000Z",
805 }),
806 ]),
807 branchPullRequest: () => Effect.die(new Error("host unavailable")),
808 pullRequestSummary: () =>
809 Effect.fail(
810 new PullRequestOperationError({
811 operation: "summary",
812 detail: "host unavailable",
813 }),
814 ),
815 });
816​
817 yield* Effect.gen(function* () {
818 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
819 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
820​
821 assert.deepStrictEqual(
822 (yield* Ref.get(fixture.commands))
823 .map(({ threadId, snapshotSequence, settledAt }) => ({
824 threadId,
825 snapshotSequence,
826 settledAt,
827 }))
828 .sort((left, right) => left.threadId.localeCompare(right.threadId)),
829 [
830 {
831 threadId: ThreadId.make("inactive-branch"),
832 snapshotSequence: 1,
833 settledAt: "2026-08-21T00:00:00.000Z",
834 },
835 {
836 threadId: ThreadId.make("inactive-linked"),
837 snapshotSequence: 1,
838 settledAt: "2026-08-20T00:00:00.000Z",
839 },
840 ],
841 );
842 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
843 assert.deepStrictEqual(yield* Ref.get(fixture.branchCalls), []);
844 }).pipe(Effect.provide(fixture.layer));
845 }),
846 ),
847 );
848​
849 it.effect("settles an inactive thread before its shared pull request lookup completes", () =>
850 Effect.scoped(
851 Effect.gen(function* () {
852 yield* TestClock.setTime(Date.parse(NOW));
853 const lookupStarted = yield* Deferred.make<void>();
854 const releaseLookup = yield* Deferred.make<void>();
855 const linkedPullRequest = {
856 projectId: PROJECT_ID,
857 repository: "owner/repository",
858 number: 42,
859 url: "https://example.test/owner/repository/pull/42",
860 } as const;
861 const fixture = yield* makeHarness({
862 snapshot: makeSnapshot([
863 makeThread("recent-linked", {
864 linkedPullRequest,
865 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
866 }),
867 makeThread("inactive-linked", { linkedPullRequest }),
868 ]),
869 pullRequestSummary: () =>
870 Deferred.succeed(lookupStarted, undefined).pipe(
871 Effect.andThen(Deferred.await(releaseLookup)),
872 Effect.andThen(
873 Effect.fail(
874 new PullRequestOperationError({
875 operation: "summary",
876 detail: "host unavailable",
877 }),
878 ),
879 ),
880 ),
881 });
882​
883 yield* Effect.gen(function* () {
884 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
885 yield* reactor.start();
886 yield* Deferred.succeed(fixture.activation, undefined);
887 yield* Deferred.await(lookupStarted);
888​
889 assert.deepStrictEqual(
890 (yield* Ref.get(fixture.commands)).map(({ threadId }) => threadId),
891 [ThreadId.make("inactive-linked")],
892 );
893​
894 yield* Deferred.succeed(releaseLookup, undefined);
895 yield* reactor.drain;
896 assert.strictEqual((yield* Ref.get(fixture.commands)).length, 1);
897 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
898 }).pipe(Effect.provide(fixture.layer));
899 }),
900 ),
901 );
902​
903 it.effect("keeps threads active when their pull request project is unavailable", () =>
904 Effect.scoped(
905 Effect.gen(function* () {
906 yield* TestClock.setTime(Date.parse(NOW));
907 const linkedPullRequest = {
908 projectId: LINKED_PROJECT_ID,
909 repository: "owner/repository",
910 number: 10,
911 url: "https://example.test/owner/repository/pull/10",
912 } as const;
913 const fixture = yield* makeHarness({
914 snapshot: makeSnapshot(
915 [
916 makeThread("missing-own-project", {
917 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
918 linkedPullRequest,
919 }),
920 makeThread("missing-branch-project", {
921 branch: "saved-feature",
922 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
923 }),
924 ],
925 [makeProject(LINKED_PROJECT_ID, "/workspace/linked")],
926 ),
927 pullRequestSummary: (input) =>
928 Effect.succeed(makePullRequestSummary({ ...input, state: "open" })),
929 });
930​
931 yield* Effect.gen(function* () {
932 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
933 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
934​
935 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
936 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), [
937 { projectId: LINKED_PROJECT_ID, repository: "owner/repository", number: 10 },
938 ]);
939 assert.deepStrictEqual(yield* Ref.get(fixture.branchCalls), []);
940 }).pipe(Effect.provide(fixture.layer));
941 }),
942 ),
943 );
944​
945 it.effect("deduplicates saved-branch and linked pull request lookups within a sweep", () =>
946 Effect.scoped(
947 Effect.gen(function* () {
948 yield* TestClock.setTime(Date.parse(NOW));
949 const linkedPullRequest = {
950 projectId: LINKED_PROJECT_ID,
951 repository: "owner/repository",
952 number: 77,
953 url: "https://example.test/owner/repository/pull/77",
954 } as const;
955 const fixture = yield* makeHarness({
956 snapshot: makeSnapshot(
957 [
958 makeThread("branch-one", {
959 branch: "saved-feature",
960 worktreePath: "/deleted/worktree-one",
961 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
962 }),
963 makeThread("branch-two", {
964 branch: "saved-feature",
965 worktreePath: "/deleted/worktree-two",
966 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
967 }),
968 makeThread("linked-one", {
969 linkedPullRequest,
970 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
971 }),
972 makeThread("linked-two", {
973 linkedPullRequest,
974 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
975 }),
976 ],
977 [
978 makeProject(PROJECT_ID, "/workspace/project-root"),
979 makeProject(LINKED_PROJECT_ID, "/workspace/linked-root"),
980 ],
981 ),
982 branchPullRequest: () => Effect.succeed(makeBranchPullRequest("closed")),
983 pullRequestSummary: (input) =>
984 Effect.succeed(makePullRequestSummary({ ...input, state: "merged" })),
985 });
986​
987 yield* Effect.gen(function* () {
988 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
989 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
990​
991 assert.deepStrictEqual(yield* Ref.get(fixture.branchCalls), [
992 { cwd: "/workspace/project-root", branch: "saved-feature" },
993 ]);
994 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), [
995 { projectId: LINKED_PROJECT_ID, repository: "owner/repository", number: 77 },
996 ]);
997 assert.deepStrictEqual(
998 new Set((yield* Ref.get(fixture.commands)).map((command) => command.threadId)),
999 new Set([
1000 ThreadId.make("branch-one"),
1001 ThreadId.make("branch-two"),
1002 ThreadId.make("linked-one"),
1003 ThreadId.make("linked-two"),
1004 ]),
1005 );
1006 }).pipe(Effect.provide(fixture.layer));
1007 }),
1008 ),
1009 );
1010​
1011 it.effect("looks up the branch pull request from a thread's live worktree", () =>
1012 Effect.scoped(
1013 Effect.gen(function* () {
1014 yield* TestClock.setTime(Date.parse(NOW));
1015 const fixture = yield* makeHarness({
1016 snapshot: makeSnapshot(
1018 makeThread("live-worktree", {
1019 branch: "feature/live",
1020 worktreePath: "/workspace/project-root/.worktrees/live",
1021 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
1022 }),
1023 makeThread("deleted-worktree", {
1024 branch: "feature/deleted",
1025 worktreePath: "/workspace/project-root/.worktrees/deleted",
1026 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
1027 }),
1028 ],
1029 [makeProject(PROJECT_ID, "/workspace/project-root")],
1030 ),
1031 existingWorktreePaths: ["/workspace/project-root/.worktrees/live"],
1032 });
1033​
1034 yield* Effect.gen(function* () {
1035 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
1036 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1037​
1038 assert.deepStrictEqual(
1039 new Set(yield* Ref.get(fixture.branchCalls)),
1040 new Set([
1041 { cwd: "/workspace/project-root/.worktrees/live", branch: "feature/live" },
1042 { cwd: "/workspace/project-root", branch: "feature/deleted" },
1043 ]),
1044 );
1045 }).pipe(Effect.provide(fixture.layer));
1046 }),
1047 ),
1048 );
1049​
1050 it.effect("carries the snapshot guard and survives a stale dispatch rejection", () =>
1051 Effect.scoped(
1052 Effect.gen(function* () {
1053 yield* TestClock.setTime(Date.parse(NOW));
1054 const fixture = yield* makeHarness({
1055 snapshot: makeSnapshot([makeThread("stale"), makeThread("next-candidate")]),
1056 onDispatch: (command) =>
1057 command.threadId === ThreadId.make("stale")
1058 ? Effect.fail(
1059 new OrchestrationCommandInvariantError({
1060 commandType: command.type,
1061 detail: "thread changed after settlement evaluation",
1062 }),
1064 : Effect.void,
1065 });
1066​
1067 yield* Effect.gen(function* () {
1068 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
1069 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1070​
1071 const firstSweep = yield* Ref.get(fixture.commands);
1072 assert.strictEqual(
1073 firstSweep.find((command) => command.threadId === ThreadId.make("stale"))
1074 ?.snapshotSequence,
1075 1,
1076 );
1077 assert.strictEqual(
1078 firstSweep.some((command) => command.threadId === ThreadId.make("next-candidate")),
1079 true,
1080 );
1081​
1082 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
1083 yield* Queue.take(fixture.snapshotReads);
1084 yield* reactor.drain;
1085 assert.strictEqual((yield* Ref.get(fixture.commands)).length, 4);
1086 }).pipe(Effect.provide(fixture.layer));
1087 }),
1088 ),
1089 );
1090});