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

ThreadSettlementService.test.ts

1,079 lines39.6 KB

1import { assert, describe, expect, it } from "@effect/vitest";
2import * as DateTime from "effect/DateTime";
3import {
4 DEFAULT_SERVER_SETTINGS,
5 ProjectId,
6 EventId,
7 ProviderInstanceId,
8 ProviderSessionId,
9 ThreadId,
10 type OrchestrationProjectShell,
11 type OrchestrationV2AppThread,
12 type OrchestrationV2Command,
13 type OrchestrationV2DomainEvent,
14 type OrchestrationV2ShellSnapshot,
15 type OrchestrationV2ThreadShell,
16 type PullRequestSummary,
17 type ServerSettings as ContractServerSettings,
18 type ServerSettingsPatch,
19} from "@t3tools/contracts";
20import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
21import * as Crypto from "effect/Crypto";
22import * as Deferred from "effect/Deferred";
23import * as Effect from "effect/Effect";
24import * as FileSystem from "effect/FileSystem";
25import * as Layer from "effect/Layer";
26import * as PubSub from "effect/PubSub";
27import * as Queue from "effect/Queue";
28import * as Ref from "effect/Ref";
29import * as Stream from "effect/Stream";
30import { TestClock } from "effect/testing";
31​
32import * as GitManager from "../git/GitManager.ts";
33import * as PullRequestService from "../pullRequest/PullRequestService.ts";
34import * as ServerActivation from "../serverActivation.ts";
35import * as ServerSettings from "../serverSettings.ts";
36import * as TerminalManager from "../terminal/Manager.ts";
37import * as ProjectStore from "./ProjectStore.ts";
38import * as Orchestrator from "./Orchestrator.ts";
39import * as ProjectionStore from "./ProjectionStore.ts";
40import * as ThreadSettlementService from "./ThreadSettlementService.ts";
41​
42const NOW_MS = Date.parse("2026-06-10T12:00:00.000Z");
43const DAY_MS = 24 * 60 * 60 * 1_000;
44​
45function at(offsetMs: number): DateTime.Utc {
46 return DateTime.makeUnsafe(NOW_MS + offsetMs);
48​
49function shell(overrides: Partial<OrchestrationV2ThreadShell> = {}): OrchestrationV2ThreadShell {
50 return {
51 id: ThreadId.make("thread-1"),
52 projectId: ProjectId.make("project-1"),
53 title: "Thread",
54 providerInstanceId: ProviderInstanceId.make("codex"),
55 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
56 runtimeMode: "full-access",
57 interactionMode: "default",
58 worktreePath: null,
59 activeProviderThreadId: null,
60 lineage: {
61 rootThreadId: ThreadId.make("thread-1"),
62 parentThreadId: null,
63 relationshipToParent: null,
64 },
65 forkedFrom: null,
66 createdBy: "user",
67 creationSource: "web",
68 activeRunId: null,
69 latestVisibleMessage: null,
70 hasActionableProposedPlan: false,
71 itemCount: 0,
72 visibleItemCount: 0,
73 lastVisitedAt: null,
74 deletedAt: null,
75 branch: null,
76 linkedPullRequest: null,
77 status: "idle",
78 activityRunStatus: null,
79 pendingRuntimeRequest: null,
80 pendingBackgroundTasks: [],
81 latestRunId: null,
82 latestRunRequestedAt: null,
83 latestRunStartedAt: null,
84 latestRunCompletedAt: null,
85 latestUserMessageAt: null,
86 createdAt: at(-30 * DAY_MS),
87 updatedAt: at(-10 * DAY_MS),
88 archivedAt: null,
89 settledOverride: null,
90 settledAt: null,
91 snoozedUntil: null,
92 snoozedAt: null,
93 pinnedAt: null,
94 ...overrides,
95 };
97​
98describe("isAutoSettlementCandidate", () => {
99 it("excludes overridden, pinned, blocked, and working threads", () => {
100 expect(ThreadSettlementService.isAutoSettlementCandidate(shell(), NOW_MS)).toBe(true);
101 expect(
102 ThreadSettlementService.isAutoSettlementCandidate(shell({ archivedAt: at(-1) }), NOW_MS),
103 ).toBe(false);
104 expect(
105 ThreadSettlementService.isAutoSettlementCandidate(
106 shell({ settledOverride: "settled" }),
107 NOW_MS,
108 ),
109 ).toBe(false);
110 expect(
111 ThreadSettlementService.isAutoSettlementCandidate(
112 shell({ settledOverride: "active" }),
113 NOW_MS,
114 ),
115 ).toBe(false);
116 expect(
117 ThreadSettlementService.isAutoSettlementCandidate(shell({ pinnedAt: at(-1) }), NOW_MS),
118 ).toBe(false);
119 expect(
120 ThreadSettlementService.isAutoSettlementCandidate(
121 shell({ autoSettleDisabledAt: at(-1) }),
122 NOW_MS,
123 ),
124 ).toBe(false);
125 expect(
126 ThreadSettlementService.isAutoSettlementCandidate(
127 shell({ activityRunStatus: "running" }),
128 NOW_MS,
129 ),
130 ).toBe(false);
131 expect(
132 ThreadSettlementService.isAutoSettlementCandidate(
133 shell({
134 pendingRuntimeRequest: { kind: "approval" } as never,
135 }),
136 NOW_MS,
137 ),
138 ).toBe(false);
139 expect(
140 ThreadSettlementService.isAutoSettlementCandidate(
141 shell({ pendingBackgroundTasks: [{ label: "task" }] as never }),
142 NOW_MS,
143 ),
144 ).toBe(false);
145 });
146​
147 it("keeps snoozed threads parked until they wake early on error or completion", () => {
148 const snoozed = shell({
149 snoozedUntil: at(60 * 60 * 1_000),
150 snoozedAt: at(-60 * 60 * 1_000),
151 });
152 expect(ThreadSettlementService.isAutoSettlementCandidate(snoozed, NOW_MS)).toBe(false);
153 expect(
154 ThreadSettlementService.isAutoSettlementCandidate(
155 shell({ ...snoozed, status: "failed", latestRunCompletedAt: at(-30 * 60 * 1_000) }),
156 NOW_MS,
157 ),
158 ).toBe(true);
159 expect(
160 ThreadSettlementService.isAutoSettlementCandidate(
161 shell({ ...snoozed, latestRunCompletedAt: at(-30 * 60 * 1_000) }),
162 NOW_MS,
163 ),
164 ).toBe(true);
165 expect(
166 ThreadSettlementService.isAutoSettlementCandidate(
167 shell({ ...snoozed, status: "failed", latestRunCompletedAt: at(-2 * 60 * 60 * 1_000) }),
168 NOW_MS,
169 ),
170 ).toBe(false);
171 expect(
172 ThreadSettlementService.isAutoSettlementCandidate(
173 shell({ ...snoozed, status: "failed", latestRunCompletedAt: snoozed.snoozedAt }),
174 NOW_MS,
175 ),
176 ).toBe(false);
177 expect(
178 ThreadSettlementService.isAutoSettlementCandidate(
179 shell({ ...snoozed, status: "failed", latestRunCompletedAt: null }),
180 NOW_MS,
181 ),
182 ).toBe(false);
183 // Expired snooze is no longer a park.
184 expect(
185 ThreadSettlementService.isAutoSettlementCandidate(
186 shell({ ...snoozed, snoozedUntil: at(-1) }),
187 NOW_MS,
188 ),
189 ).toBe(true);
190 });
191});
192​
193describe("threadHasQueuedTurnStart", () => {
194 it("holds a fresh unadopted user message inside the grace window only", () => {
195 const fresh = shell({ latestUserMessageAt: at(-1_000) });
196 expect(ThreadSettlementService.threadHasQueuedTurnStart(fresh, NOW_MS)).toBe(true);
197 // Adoption stamps the run with the message time, clearing the hold.
198 expect(
199 ThreadSettlementService.threadHasQueuedTurnStart(
200 shell({
201 latestUserMessageAt: at(-1_000),
202 latestRunId: "run-1" as never,
203 latestRunRequestedAt: at(-500),
204 }),
205 NOW_MS,
206 ),
207 ).toBe(false);
208 // Outside the grace window the stale message no longer blocks.
209 expect(
210 ThreadSettlementService.threadHasQueuedTurnStart(
211 shell({ latestUserMessageAt: at(-ThreadSettlementService.QUEUED_TURN_START_GRACE_MS - 1) }),
212 NOW_MS,
213 ),
214 ).toBe(false);
215 // Client clocks ahead of the server must not extend the hold.
216 expect(
217 ThreadSettlementService.threadHasQueuedTurnStart(
218 shell({ latestUserMessageAt: at(ThreadSettlementService.QUEUED_TURN_START_GRACE_MS + 1) }),
219 NOW_MS,
220 ),
221 ).toBe(false);
222 // A failed start clears the hold immediately.
223 expect(
224 ThreadSettlementService.threadHasQueuedTurnStart(
225 shell({ latestUserMessageAt: at(-1_000), status: "failed" }),
226 NOW_MS,
227 ),
228 ).toBe(false);
229 });
230});
231​
232describe("resolveAutoSettlementAt", () => {
233 it("uses the latest activity time when the inactivity window elapses", () => {
234 const idle = shell({
235 latestUserMessageAt: at(-4 * DAY_MS),
236 latestRunRequestedAt: at(-4 * DAY_MS),
237 latestRunStartedAt: at(-4 * DAY_MS),
238 latestRunCompletedAt: at(-3 * DAY_MS),
239 });
240 const input = {
241 thread: idle,
242 pullRequest: null,
243 nowMs: NOW_MS,
244 autoSettleAfterDays: 2,
245 autoSettleOnMerge: true,
246 };
247 expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toEqual(at(-3 * DAY_MS));
248 expect(
249 ThreadSettlementService.resolveAutoSettlementAt({ ...input, autoSettleAfterDays: 5 }),
250 ).toBeNull();
251 expect(
252 ThreadSettlementService.resolveAutoSettlementAt({ ...input, autoSettleAfterDays: null }),
253 ).toBeNull();
254 expect(
255 ThreadSettlementService.resolveAutoSettlementAt({ ...input, thread: shell() }),
256 ).toBeNull();
257 });
258​
259 it("settles on merge only after the user's last action and preserves the activity time", () => {
260 const thread = shell({
261 latestUserMessageAt: at(-2 * 60 * 60 * 1_000),
262 latestRunCompletedAt: at(-90 * 60 * 1_000),
263 });
264 const input = {
265 thread,
266 pullRequest: {
267 state: "merged" as const,
268 mergedAt: DateTime.formatIso(at(-60 * 60 * 1_000)),
269 },
270 nowMs: NOW_MS,
271 autoSettleAfterDays: null,
272 autoSettleOnMerge: true,
273 };
274 expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toEqual(at(-90 * 60 * 1_000));
275 expect(
276 ThreadSettlementService.resolveAutoSettlementAt({ ...input, autoSettleOnMerge: false }),
277 ).toBeNull();
278 expect(
279 ThreadSettlementService.resolveAutoSettlementAt({
280 ...input,
281 pullRequest: { state: "merged", mergedAt: DateTime.formatIso(at(-3 * 60 * 60 * 1_000)) },
282 }),
283 ).toBeNull();
284 // A thread without messages still has a stable timestamp when its PR closes.
285 expect(
286 ThreadSettlementService.resolveAutoSettlementAt({
287 ...input,
288 thread: shell(),
289 pullRequest: { state: "closed", closedAt: DateTime.formatIso(at(-1)) },
290 autoSettleOnMerge: false,
291 }),
292 ).toEqual(shell().createdAt);
293 });
294​
295 it("settles inactive threads even when their pull request remains open", () => {
296 const input = {
297 thread: shell({ latestUserMessageAt: at(-30 * DAY_MS) }),
298 pullRequest: { state: "open" as const },
299 nowMs: NOW_MS,
300 autoSettleAfterDays: 2,
301 autoSettleOnMerge: true,
302 };
303 expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toEqual(at(-30 * DAY_MS));
304 expect(
305 ThreadSettlementService.resolveAutoSettlementAt({ ...input, autoSettleAfterDays: null }),
306 ).toBeNull();
307 expect(
308 ThreadSettlementService.resolveAutoSettlementAt({
309 ...input,
310 thread: shell({ latestUserMessageAt: at(-DAY_MS) }),
311 }),
312 ).toBeNull();
313 });
314});
315​
316const NOW = "2026-08-28T12:00:00.000Z";
317const PROJECT_ID = ProjectId.make("settlement-project");
318const LINKED_PROJECT_ID = ProjectId.make("linked-settlement-project");
319​
320describe("autoSettlementSettingsKey", () => {
321 it("distinguishes a project that inherits the threshold from one that disables it", () => {
322 const inherits = ThreadSettlementService.autoSettlementSettingsKey({
323 ...DEFAULT_SERVER_SETTINGS,
324 projectSettingsOverrides: { [PROJECT_ID]: { sidebarAutoSettleOnMerge: true } },
325 });
326 const never = ThreadSettlementService.autoSettlementSettingsKey({
327 ...DEFAULT_SERVER_SETTINGS,
328 projectSettingsOverrides: {
329 [PROJECT_ID]: { sidebarAutoSettleOnMerge: true, sidebarAutoSettleAfterDays: null },
330 },
331 });
332 assert.notStrictEqual(inherits, never);
333 });
334​
335 it("ignores project overrides that do not touch settlement", () => {
336 const base = ThreadSettlementService.autoSettlementSettingsKey({
337 ...DEFAULT_SERVER_SETTINGS,
338 projectSettingsOverrides: { [PROJECT_ID]: { sidebarAutoSettleOnMerge: false } },
339 });
340 const unrelated = ThreadSettlementService.autoSettlementSettingsKey({
341 ...DEFAULT_SERVER_SETTINGS,
342 projectSettingsOverrides: {
343 [LINKED_PROJECT_ID]: { defaultThreadEnvMode: "worktree" },
344 [PROJECT_ID]: { sidebarAutoSettleOnMerge: false, defaultAutoPull: true },
345 },
346 });
347 assert.strictEqual(base, unrelated);
348 });
349});
350​
351type AutoSettleCommand = Extract<OrchestrationV2Command, { readonly type: "thread.auto-settle" }>;
352​
353const testCrypto = Crypto.make({
354 randomBytes: (size) => new Uint8Array(size).fill(1),
355 digest: (_algorithm, data) => Effect.succeed(data),
356});
357​
358function makeProject(
359 id: ProjectId = PROJECT_ID,
360 workspaceRoot = "/workspace/project",
361): OrchestrationProjectShell {
362 return {
363 id,
364 title: `Project ${id}`,
365 workspaceRoot,
366 defaultModelSelection: null,
367 scripts: [],
368 createdAt: "2026-08-01T00:00:00.000Z",
369 updatedAt: NOW,
370 };
372​
373function makeThread(
374 id: string,
375 overrides: Partial<OrchestrationV2ThreadShell> = {},
376): OrchestrationV2ThreadShell {
377 return shell({
378 id: ThreadId.make(id),
379 projectId: PROJECT_ID,
380 title: id,
381 createdAt: DateTime.makeUnsafe("2026-08-01T00:00:00.000Z"),
382 updatedAt: DateTime.makeUnsafe("2026-08-20T00:00:00.000Z"),
383 latestUserMessageAt: DateTime.makeUnsafe("2026-08-20T00:00:00.000Z"),
384 ...overrides,
385 });
387​
388function makeSnapshot(
389 threads: ReadonlyArray<OrchestrationV2ThreadShell>,
390 projects: ReadonlyArray<OrchestrationProjectShell> = [makeProject()],
391): OrchestrationV2ShellSnapshot {
392 return {
393 schemaVersion: 1,
394 snapshotSequence: 1,
395 projects,
396 threads,
397 archivedThreads: [],
398 };
400​
401function makePullRequestSummary(input: {
402 readonly projectId: ProjectId;
403 readonly repository: string;
404 readonly number: number;
405 readonly state: "open" | "closed" | "merged";
406 readonly updatedAt?: string;
407}): PullRequestSummary {
408 return {
409 provider: "github",
410 projectId: input.projectId,
411 repository: input.repository,
412 number: input.number,
413 title: "Pull request",
414 url: `https://example.test/${input.repository}/pull/${input.number}`,
415 state: input.state,
416 headBranch: "feature",
417 baseBranch: "main",
418 updatedAt: input.updatedAt ?? NOW,
419 };
421​
422function makeBranchPullRequest(state: "open" | "closed" | "merged") {
423 return {
424 number: 42,
425 title: "Pull request",
426 url: "https://example.test/owner/repository/pull/42",
427 baseRef: "main",
428 headRef: "feature",
429 state,
430 repositoryKey: "example.test/owner/repository",
431 updatedAt: NOW,
432 closedAt: state === "closed" ? NOW : null,
433 mergedAt: state === "merged" ? NOW : null,
434 } satisfies GitManager.GitBranchPullRequest;
436​
437interface HarnessOptions {
438 readonly snapshot: OrchestrationV2ShellSnapshot;
439 readonly settings?: ContractServerSettings;
440 readonly branchPullRequest?: GitManager.GitManager["Service"]["branchPullRequest"];
441 readonly pullRequestSummary?: PullRequestService.PullRequestService["Service"]["summary"];
442 readonly existingWorktreePaths?: ReadonlyArray<string>;
443 readonly onDispatch?: (command: AutoSettleCommand) => Effect.Effect<void>;
444 /** Threads `getThread` returns when a `thread.settled` event is handled. */
445 readonly currentThreads?: ReadonlyArray<OrchestrationV2AppThread>;
447​
448const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: HarnessOptions) {
449 const activation = yield* Deferred.make<void>();
450 const snapshots = yield* Ref.make(options.snapshot);
451 const snapshotReadCount = yield* Ref.make(0);
452 const snapshotReads = yield* Queue.unbounded<number>();
453 const candidateReads = yield* Ref.make<ReadonlyArray<string | undefined>>([]);
454 const settings = yield* Ref.make(options.settings ?? DEFAULT_SERVER_SETTINGS);
455 const settingsChanges = yield* PubSub.unbounded<ContractServerSettings>();
456 const mergedPullRequests = yield* PubSub.unbounded<PullRequestService.PullRequestMergeEvent>();
457 const commands = yield* Ref.make<ReadonlyArray<AutoSettleCommand>>([]);
458 const branchCalls = yield* Ref.make<
459 ReadonlyArray<{ readonly cwd: string; readonly branch: string }>
460 >([]);
461 const summaryCalls = yield* Ref.make<
462 ReadonlyArray<{
463 readonly projectId: ProjectId;
464 readonly repository: string;
465 readonly number: number;
466 }>
467 >([]);
468 const summaryRecovery = yield* Ref.make<ReadonlyArray<boolean | undefined>>([]);
469 const invalidatedCwds = yield* Ref.make<ReadonlyArray<string>>([]);
470 const domainEvents = yield* PubSub.unbounded<OrchestrationV2DomainEvent>();
471 const closedIdle = yield* Queue.unbounded<{ readonly threadId: string }>();
472​
473 const updateSettings = (patch: ServerSettingsPatch) =>
474 Effect.gen(function* () {
475 const next = applyServerSettingsPatch(yield* Ref.get(settings), patch);
476 yield* Ref.set(settings, next);
477 yield* PubSub.publish(settingsChanges, next);
478 return next;
479 });
480​
481 const branchPullRequest: GitManager.GitManager["Service"]["branchPullRequest"] = (input) =>
482 Ref.update(branchCalls, (calls) => [...calls, input]).pipe(
483 Effect.andThen(options.branchPullRequest?.(input) ?? Effect.succeed(null)),
484 );
485 const pullRequestSummary: PullRequestService.PullRequestService["Service"]["summary"] = (
486 input,
487 readOptions,
488 ) =>
489 Effect.gen(function* () {
490 yield* Ref.update(summaryCalls, (calls) => [...calls, input]);
491 yield* Ref.update(summaryRecovery, (values) => [
492 ...values,
493 readOptions?.recoverTransientFailure,
494 ]);
495 return yield* (
496 options.pullRequestSummary?.(input, readOptions) ??
497 Effect.succeed(
498 makePullRequestSummary({
499 ...input,
500 state: "open",
501 }),
502 )
503 );
504 });
505​
506 const dispatch: Orchestrator.OrchestratorV2Shape["dispatch"] = (command) => {
507 if (command.type !== "thread.auto-settle") {
508 return Effect.die(new Error(`Unexpected command: ${command.type}`));
509 }
510 return Ref.update(commands, (recorded) => [...recorded, command]).pipe(
511 Effect.andThen(options.onDispatch?.(command) ?? Effect.void),
512 Effect.as({ sequence: 1, storedEvents: [] }),
513 );
514 };
515​
516 const serverSettings = ServerSettings.ServerSettingsService.of({
517 start: Effect.void,
518 ready: Effect.void,
519 getSettings: Ref.get(settings),
520 updateSettings,
521 updateProviderInstance: () => Effect.die("Unexpected provider mutation"),
522 withSettingsSnapshot: (use) => Ref.get(settings).pipe(Effect.flatMap(use)),
523 streamChanges: Stream.fromPubSub(settingsChanges),
524 subscribeChanges: PubSub.subscribe(settingsChanges).pipe(
525 Effect.map((subscription) => Stream.fromSubscription(subscription)),
526 ),
527 });
528​
529 const dependencies = Layer.mergeAll(
530 Layer.mock(ProjectStore.ProjectStoreV2)({
531 listShells: () => Ref.get(snapshots).pipe(Effect.map((snapshot) => snapshot.projects)),
532 }),
533 Layer.mock(ProjectionStore.ProjectionStoreV2)({
534 getSettlementCandidates: (threadId) =>
535 Ref.update(candidateReads, (reads) => [...reads, threadId]).pipe(
536 Effect.andThen(Ref.updateAndGet(snapshotReadCount, (count) => count + 1)),
537 Effect.tap((count) => Queue.offer(snapshotReads, count)),
538 Effect.andThen(Ref.get(snapshots)),
539 Effect.map((snapshot) =>
540 threadId === undefined
541 ? snapshot.threads
542 : snapshot.threads.filter((thread) => thread.id === threadId),
543 ),
544 ),
545 getThread: (threadId) => {
546 const thread = options.currentThreads?.find((candidate) => candidate.id === threadId);
547 return thread
548 ? Effect.succeed(thread)
549 : Effect.die(new Error(`Unexpected thread read: ${threadId}`));
550 },
551 }),
552 Layer.mock(Orchestrator.OrchestratorV2)({
553 streamDomainEvents: Stream.fromPubSub(domainEvents),
554 dispatch,
555 }),
556 Layer.mock(TerminalManager.TerminalManager)({
557 closeIdle: (input) => Queue.offer(closedIdle, input).pipe(Effect.asVoid),
558 }),
559 Layer.mock(GitManager.GitManager)({
560 branchPullRequest,
561 invalidateStatus: (cwd) => Ref.update(invalidatedCwds, (cwds) => [...cwds, cwd]),
562 }),
563 Layer.mock(PullRequestService.PullRequestService)({
564 summary: pullRequestSummary,
565 subscribeMerges: PubSub.subscribe(mergedPullRequests).pipe(
566 Effect.map((subscription) => Stream.fromSubscription(subscription)),
567 ),
568 }),
569 Layer.succeed(ServerSettings.ServerSettingsService, serverSettings),
570 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
571 Layer.succeed(Crypto.Crypto, testCrypto),
572 FileSystem.layerNoop({
573 exists: (path) => Effect.succeed(options.existingWorktreePaths?.includes(path) ?? false),
574 }),
575 );
576​
577 return {
578 activation,
579 snapshots,
580 snapshotReadCount,
581 snapshotReads,
582 candidateReads,
583 commands,
584 branchCalls,
585 summaryCalls,
586 summaryRecovery,
587 invalidatedCwds,
588 closedIdle,
589 publishEvent: (event: OrchestrationV2DomainEvent) => PubSub.publish(domainEvents, event),
590 updateSettings,
591 publishMerge: PubSub.publish(mergedPullRequests, {
592 projectId: PROJECT_ID,
593 repository: "owner/repository",
594 number: 42,
595 mergedAt: NOW,
596 }),
597 layer: ThreadSettlementService.layer.pipe(Layer.provide(dependencies)),
598 };
599});
600​
601const startHarness = Effect.fn("startThreadSettlementHarness")(function* (
602 reactor: ThreadSettlementService.ThreadSettlementServiceV2["Service"],
603 activation: Deferred.Deferred<void>,
604 snapshotReads: Queue.Queue<number>,
605) {
606 yield* reactor.start();
607 yield* Deferred.succeed(activation, undefined);
608 yield* Queue.take(snapshotReads);
609 yield* reactor.drain;
610});
611​
612describe("ThreadSettlementServiceV2 worker", () => {
613 it.effect("settles a merged pull request stored only in the thread links", () =>
614 Effect.scoped(
615 Effect.gen(function* () {
616 yield* TestClock.setTime(Date.parse(NOW));
617 const thread = makeThread("merged-link", {
618 pullRequests: [
619 {
620 host: "example.test",
621 repository: "owner/repository",
622 number: 42,
623 url: "https://example.test/owner/repository/pull/42",
624 source: "manual",
625 linkedAt: "2026-08-20T00:00:00.000Z",
626 snapshot: {
627 state: "merged",
628 title: "Pull request",
629 headBranch: "feature",
630 baseBranch: "main",
631 isDraft: false,
632 updatedAt: NOW,
633 syncedAt: NOW,
634 mergedAt: NOW,
635 },
636 stack: null,
637 },
638 ],
639 });
640 const fixture = yield* makeHarness({
641 snapshot: makeSnapshot([thread]),
642 settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: null },
643 });
644​
645 yield* Effect.gen(function* () {
646 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
647 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
648 expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
649 thread.id,
650 ]);
651 }).pipe(Effect.provide(fixture.layer));
652 }),
653 ),
654 );
655​
656 it.effect("settles only the project opted in while environment settlement is disabled", () =>
657 Effect.scoped(
658 Effect.gen(function* () {
659 yield* TestClock.setTime(Date.parse(NOW));
660 const thread = makeThread("project-opt-in", {
661 latestRunCompletedAt: DateTime.makeUnsafe("2026-08-25T00:00:00.000Z"),
662 });
663 const other = makeThread("environment-off", { projectId: ProjectId.make("other-project") });
664 const fixture = yield* makeHarness({
665 snapshot: makeSnapshot([thread, other]),
666 settings: {
667 ...DEFAULT_SERVER_SETTINGS,
668 sidebarAutoSettleAfterDays: null,
669 sidebarAutoSettleOnMerge: false,
670 projectSettingsOverrides: { [PROJECT_ID]: { sidebarAutoSettleAfterDays: 2 } },
671 },
672 });
673 yield* Effect.gen(function* () {
674 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
675 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
676 const commands = yield* Ref.get(fixture.commands);
677 expect(commands.map((command) => command.threadId)).toEqual([thread.id]);
678 }).pipe(Effect.provide(fixture.layer));
679 }),
680 ),
681 );
682​
683 it.effect("dispatches the last activity time with the v2 snapshot guard", () =>
684 Effect.scoped(
685 Effect.gen(function* () {
686 yield* TestClock.setTime(Date.parse(NOW));
687 const thread = makeThread("inactive-open-pr", {
688 branch: "feature",
689 latestRunCompletedAt: DateTime.makeUnsafe("2026-08-25T00:00:00.000Z"),
690 });
691 const fixture = yield* makeHarness({
692 snapshot: makeSnapshot([thread]),
693 settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 2 },
694 branchPullRequest: () => Effect.succeed(makeBranchPullRequest("open")),
695 });
696 yield* Effect.gen(function* () {
697 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
698 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
699 const commands = yield* Ref.get(fixture.commands);
700 expect(commands).toHaveLength(1);
701 expect(commands[0]?.settledAt).toEqual(thread.latestRunCompletedAt);
702 expect(commands[0]?.snapshotAt).toEqual(thread.updatedAt);
703 }).pipe(Effect.provide(fixture.layer));
704 }),
705 ),
706 );
707​
708 it.effect("skips the branch recheck when a terminal link would settle nothing", () =>
709 Effect.scoped(
710 Effect.gen(function* () {
711 yield* TestClock.setTime(Date.parse(NOW));
712 const previous = {
713 projectId: PROJECT_ID,
714 repository: "owner/repository",
715 number: 1,
716 url: "https://example.test/owner/repository/pull/1",
717 };
718 const fixture = yield* makeHarness({
719 snapshot: makeSnapshot(
720 [
721 makeThread("resumed-manual", {
722 branch: "main",
723 linkedPullRequest: previous,
724 latestUserMessageAt: DateTime.makeUnsafe("2026-08-28T00:00:00.000Z"),
725 }),
726 ],
727 [makeProject()],
728 ),
729 settings: {
730 ...DEFAULT_SERVER_SETTINGS,
731 sidebarAutoSettleAfterDays: null,
732 sidebarAutoSettleOnMerge: true,
733 },
734 branchPullRequest: () => Effect.succeed(makeBranchPullRequest("open")),
735 pullRequestSummary: (input) =>
736 Effect.succeed({
737 ...makePullRequestSummary({ ...input, state: "merged" }),
738 mergedAt: "2026-08-27T00:00:00.000Z",
739 }),
740 });
741 yield* Effect.gen(function* () {
742 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
743 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
744 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
745 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
746 assert.deepStrictEqual(yield* Ref.get(fixture.branchCalls), []);
747 }).pipe(Effect.provide(fixture.layer));
748 }),
749 ),
750 );
751​
752 it.effect("reevaluates immediately after a pull request merge", () =>
753 Effect.scoped(
754 Effect.gen(function* () {
755 yield* TestClock.setTime(Date.parse(NOW));
756 const periodicLookupStarted = yield* Deferred.make<void>();
757 const releasePeriodicLookup = yield* Deferred.make<void>();
758 const mergedThreadSettled = yield* Deferred.make<void>();
759 const branchLookupCount = yield* Ref.make(0);
760 const fixture = yield* makeHarness({
761 snapshot: makeSnapshot([
762 makeThread("merged-in-app", {
763 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
764 linkedPullRequest: {
765 projectId: PROJECT_ID,
766 repository: "Owner/Repository",
767 number: 42,
768 url: "https://example.test/owner/repository/pull/42",
769 },
770 }),
771 makeThread("slow-periodic-lookup", {
772 branch: "another-feature",
773 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
774 }),
775 ]),
776 branchPullRequest: () =>
777 Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
778 Effect.flatMap((count) =>
779 count === 1
780 ? Effect.succeed(makeBranchPullRequest("open"))
781 : Deferred.succeed(periodicLookupStarted, undefined).pipe(
782 Effect.andThen(Deferred.await(releasePeriodicLookup)),
783 Effect.as(makeBranchPullRequest("open")),
784 ),
785 ),
786 ),
787 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
788 });
789​
790 yield* Effect.gen(function* () {
791 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
792 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
793 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
794 yield* Deferred.await(periodicLookupStarted);
795​
796 yield* fixture.publishMerge;
797 yield* Deferred.await(mergedThreadSettled);
798​
799 assert.deepStrictEqual(
800 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
801 [ThreadId.make("merged-in-app")],
802 );
803 yield* Deferred.succeed(releasePeriodicLookup, undefined);
804 yield* reactor.drain;
805 }).pipe(Effect.provide(fixture.layer));
806 }),
807 ),
808 );
809​
810 it.effect(
811 "settles branch threads on a pull request merge without waiting for the next sweep",
812 () =>
813 Effect.scoped(
814 Effect.gen(function* () {
815 yield* TestClock.setTime(Date.parse(NOW));
816 const state = yield* Ref.make<"open" | "merged">("open");
817 const mergedThreadSettled = yield* Deferred.make<void>();
818 const fixture = yield* makeHarness({
819 snapshot: makeSnapshot([
820 makeThread("branch-thread", {
821 branch: "saved-feature",
822 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
823 }),
824 ]),
825 branchPullRequest: () => Ref.get(state).pipe(Effect.map(makeBranchPullRequest)),
826 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
827 });
828​
829 yield* Effect.gen(function* () {
830 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
831 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
832 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
833 assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), []);
834​
835 yield* Ref.set(state, "merged");
836 yield* fixture.publishMerge;
837 yield* Deferred.await(mergedThreadSettled);
838​
839 assert.deepStrictEqual(
840 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
841 [ThreadId.make("branch-thread")],
842 );
843 assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), ["/workspace/project"]);
844 yield* reactor.drain;
845 }).pipe(Effect.provide(fixture.layer));
846 }),
847 ),
848 );
849​
850 it.effect("a merge does not settle threads linked to an unrelated pull request", () =>
851 Effect.scoped(
852 Effect.gen(function* () {
853 yield* TestClock.setTime(Date.parse(NOW));
854 const mergedThreadSettled = yield* Deferred.make<void>();
855 const mergeLookupStarted = yield* Deferred.make<void>();
856 const releaseMergeLookup = yield* Deferred.make<void>();
857 const lookupCount = yield* Ref.make(0);
858 const fixture = yield* makeHarness({
859 snapshot: makeSnapshot([
860 makeThread("merged-in-app", {
861 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
862 linkedPullRequest: {
863 projectId: PROJECT_ID,
864 repository: "owner/repository",
865 number: 42,
866 url: "https://example.test/owner/repository/pull/42",
867 },
868 }),
869 makeThread("unrelated-linked", {
870 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
871 linkedPullRequest: {
872 projectId: PROJECT_ID,
873 repository: "owner/repository",
874 number: 99,
875 url: "https://example.test/owner/repository/pull/99",
876 },
877 }),
878 ]),
879 pullRequestSummary: (input) =>
880 Ref.updateAndGet(lookupCount, (count) => count + 1).pipe(
881 // The initial sweep looks up both linked threads; the merge
882 // sweep only looks up the unrelated one, since the merged
883 // thread settles from the event itself.
884 Effect.tap((count) =>
885 count === 3 ? Deferred.succeed(mergeLookupStarted, undefined) : Effect.void,
886 ),
887 Effect.tap((count) =>
888 count === 3 ? Deferred.await(releaseMergeLookup) : Effect.void,
889 ),
890 Effect.map(() => makePullRequestSummary({ ...input, state: "open" })),
891 ),
892 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
893 });
894​
895 yield* Effect.gen(function* () {
896 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
897 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
898 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
899​
900 yield* fixture.publishMerge;
901 yield* Deferred.await(mergeLookupStarted);
902 yield* Deferred.await(mergedThreadSettled);
903 yield* Deferred.succeed(releaseMergeLookup, undefined);
904 yield* reactor.drain;
905​
906 assert.deepStrictEqual(
907 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
908 [ThreadId.make("merged-in-app")],
909 );
910 assert.deepStrictEqual(
911 (yield* Ref.get(fixture.summaryCalls))
912 .map((call) => call.number)
913 .toSorted((left, right) => left - right),
914 [42, 99, 99],
915 );
916 }).pipe(Effect.provide(fixture.layer));
917 }),
918 ),
919 );
920​
921 it.effect("looks up the branch pull request from a thread's live worktree", () =>
922 Effect.scoped(
923 Effect.gen(function* () {
924 yield* TestClock.setTime(Date.parse(NOW));
925 const fixture = yield* makeHarness({
926 snapshot: makeSnapshot(
927 [
928 makeThread("live-worktree", {
929 branch: "feature/live",
930 worktreePath: "/workspace/project-root/.worktrees/live",
931 }),
932 makeThread("deleted-worktree", {
933 branch: "feature/deleted",
934 worktreePath: "/workspace/project-root/.worktrees/deleted",
935 }),
936 ],
937 [makeProject(PROJECT_ID, "/workspace/project-root")],
938 ),
939 existingWorktreePaths: ["/workspace/project-root/.worktrees/live"],
940 settings: {
941 ...DEFAULT_SERVER_SETTINGS,
942 sidebarAutoSettleAfterDays: null,
943 sidebarAutoSettleOnMerge: true,
944 },
945 });
946​
947 yield* Effect.gen(function* () {
948 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
949 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
950​
951 assert.deepStrictEqual(
952 new Set(yield* Ref.get(fixture.branchCalls)),
953 new Set([
954 { cwd: "/workspace/project-root/.worktrees/live", branch: "feature/live" },
955 { cwd: "/workspace/project-root", branch: "feature/deleted" },
956 ]),
957 );
958 }).pipe(Effect.provide(fixture.layer));
959 }),
960 ),
961 );
962});
963​
964describe("ThreadSettlementServiceV2 terminals", () => {
965 const appThread = (
966 id: string,
967 settledOverride: OrchestrationV2AppThread["settledOverride"],
968 ): OrchestrationV2AppThread => {
969 const threadId = ThreadId.make(id);
970 return {
971 createdBy: "user",
972 creationSource: "web",
973 id: threadId,
974 projectId: PROJECT_ID,
975 title: id,
976 providerInstanceId: ProviderInstanceId.make("codex"),
977 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
978 runtimeMode: "full-access",
979 interactionMode: "default",
980 branch: null,
981 worktreePath: null,
982 activeProviderThreadId: null,
983 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
984 forkedFrom: null,
985 createdAt: DateTime.makeUnsafe(NOW),
986 updatedAt: DateTime.makeUnsafe(NOW),
987 archivedAt: null,
988 settledOverride,
989 settledAt: settledOverride === "settled" ? DateTime.makeUnsafe(NOW) : null,
990 lastVisitedAt: null,
991 deletedAt: null,
992 };
993 };
994 const settledEvent = (thread: OrchestrationV2AppThread): OrchestrationV2DomainEvent => ({
995 type: "thread.settled",
996 id: EventId.make(`event:settled:${thread.id}`),
997 threadId: thread.id,
998 occurredAt: DateTime.makeUnsafe(NOW),
999 payload: thread,
1000 });
1001​
1002 it.effect("closes the thread's idle terminals when it settles", () =>
1003 Effect.scoped(
1004 Effect.gen(function* () {
1005 const thread = appThread("settled-thread", "settled");
1006 const fixture = yield* makeHarness({
1007 snapshot: makeSnapshot([]),
1008 currentThreads: [thread],
1009 });
1010​
1011 yield* Effect.gen(function* () {
1012 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1013 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1014 yield* fixture.publishEvent(settledEvent(thread));
1015 assert.deepStrictEqual(yield* Queue.take(fixture.closedIdle), { threadId: thread.id });
1016 }).pipe(Effect.provide(fixture.layer));
1017 }),
1018 ),
1019 );
1020​
1021 it.effect("keeps the terminals of a thread re-engaged before the event ran", () =>
1022 Effect.scoped(
1023 Effect.gen(function* () {
1024 const settled = appThread("reengaged-thread", "settled");
1025 const reengaged = appThread("reengaged-thread", "active");
1026 const marker = appThread("marker-thread", "settled");
1027 const fixture = yield* makeHarness({
1028 snapshot: makeSnapshot([]),
1029 currentThreads: [reengaged, marker],
1030 });
1031​
1032 yield* Effect.gen(function* () {
1033 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1034 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1035 yield* fixture.publishEvent(settledEvent(settled));
1036 // Events run in order, so the first close belongs to the later
1037 // event only if the re-engaged thread was skipped.
1038 yield* fixture.publishEvent(settledEvent(marker));
1039 assert.deepStrictEqual(yield* Queue.take(fixture.closedIdle), { threadId: marker.id });
1040 }).pipe(Effect.provide(fixture.layer));
1041 }),
1042 ),
1043 );
1044});
1045​
1046describe("ThreadSettlementServiceV2 single-thread sweeps", () => {
1047 it.effect("a finished run reads only its own thread's settlement candidate", () =>
1048 Effect.scoped(
1049 Effect.gen(function* () {
1050 yield* TestClock.setTime(Date.parse(NOW));
1051 const finished = makeThread("finished-run");
1052 const other = makeThread("other-thread");
1053 const fixture = yield* makeHarness({
1054 snapshot: makeSnapshot([finished, other]),
1055 settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 3 },
1056 });
1057​
1058 yield* Effect.gen(function* () {
1059 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1060 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1061 yield* Ref.set(fixture.candidateReads, []);
1062 yield* fixture.publishEvent({
1063 type: "provider-session.detached",
1064 id: EventId.make("event:detached"),
1065 threadId: finished.id,
1066 occurredAt: DateTime.makeUnsafe(NOW),
1067 payload: {
1068 providerSessionId: ProviderSessionId.make("provider-session:finished"),
1069 detachedAt: DateTime.makeUnsafe(NOW),
1070 },
1071 });
1072 yield* Queue.take(fixture.snapshotReads);
1073 yield* service.drain;
1074 assert.deepStrictEqual(yield* Ref.get(fixture.candidateReads), [finished.id]);
1075 }).pipe(Effect.provide(fixture.layer));
1076 }),
1077 ),
1078 );
1079});