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

ThreadSettlementService.test.ts

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