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