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

ThreadSettlementService.test.ts

1,454 lines54.2 KB

1import { SourceControlProviderKind } from "@t3tools/contracts";
2import { assert, describe, expect, it } from "@effect/vitest";
3import * as DateTime from "effect/DateTime";
4import {
5 DEFAULT_SERVER_SETTINGS,
6 ProjectId,
7 EventId,
8 ProviderInstanceId,
9 RunId,
10 ThreadId,
11 TurnItemId,
12 type OrchestrationProjectShell,
13 type OrchestrationV2AppThread,
14 type OrchestrationV2Command,
15 type OrchestrationV2DomainEvent,
16 type OrchestrationV2ShellSnapshot,
17 type OrchestrationV2ThreadShell,
18 type PullRequestSummary,
19 type ServerSettings as ContractServerSettings,
20 type ServerSettingsPatch,
21} from "@t3tools/contracts";
22import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
23import * as Crypto from "effect/Crypto";
24import * as Deferred from "effect/Deferred";
25import * as Effect from "effect/Effect";
26import * as FileSystem from "effect/FileSystem";
27import * as Layer from "effect/Layer";
28import * as PubSub from "effect/PubSub";
29import * as Queue from "effect/Queue";
30import * as Ref from "effect/Ref";
31import * as Stream from "effect/Stream";
32import { TestClock } from "effect/testing";
33​
34import * as GitManager from "../git/GitManager.ts";
35import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
36import * as PullRequestService from "../pullRequest/PullRequestService.ts";
37import * as ServerActivation from "../serverActivation.ts";
38import * as ServerSettings from "../serverSettings.ts";
39import * as TerminalManager from "../terminal/Manager.ts";
40import * as ProjectStore from "./ProjectStore.ts";
41import * as Orchestrator from "./Orchestrator.ts";
42import * as ProjectionStore from "./ProjectionStore.ts";
43import * as ThreadSettlementService from "./ThreadSettlementService.ts";
44​
45const NOW_MS = Date.parse("2026-06-10T12:00:00.000Z");
46const DAY_MS = 24 * 60 * 60 * 1_000;
47​
48function at(offsetMs: number): DateTime.Utc {
49 return DateTime.makeUnsafe(NOW_MS + offsetMs);
51​
52type SettlementShell = OrchestrationV2ThreadShell &
53 Pick<ProjectionStore.ProjectionSettlementCandidate, "latestUserAuthoredMessageAt">;
54​
55function shell(overrides: Partial<SettlementShell> = {}): SettlementShell {
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 latestUserAuthoredMessageAt: overrides.latestUserMessageAt ?? null,
93 createdAt: at(-30 * DAY_MS),
94 updatedAt: at(-10 * DAY_MS),
95 archivedAt: null,
96 settledOverride: null,
97 settledAt: null,
98 snoozedUntil: null,
99 snoozedAt: null,
100 pinnedAt: null,
101 ...overrides,
102 };
104​
105function persistedLink(
106 state: "open" | null,
107 linkedAt: DateTime.Utc,
108): NonNullable<SettlementShell["pullRequests"]>[number] {
109 return {
110 host: "example.test",
111 repository: "owner/repository",
112 number: 42,
113 url: "https://example.test/owner/repository/pull/42",
114 source: "manual",
115 linkedAt: DateTime.formatIso(linkedAt),
116 snapshot:
117 state === null
118 ? null
119 : {
120 state,
121 title: "Pull request",
122 headBranch: "feature",
123 baseBranch: "main",
124 isDraft: false,
125 updatedAt: DateTime.formatIso(linkedAt),
126 syncedAt: DateTime.formatIso(linkedAt),
127 },
128 stack: null,
129 };
131​
132describe("isAutoSettlementCandidate", () => {
133 it("settles a thread whose only background work is a command left running", () => {
134 expect(
135 ThreadSettlementService.isAutoSettlementCandidate(
136 shell({
137 pendingBackgroundTasks: [
138 { taskId: "dev", kind: "command", description: "vp run dev --share" },
139 ],
140 }),
141 NOW_MS,
142 ),
143 ).toBe(true);
144 });
145​
146 it("never settles, or keeps snoozed, a thread whose guest is waiting on the owner", () => {
147 expect(
148 ThreadSettlementService.isAutoSettlementCandidate(
149 shell({ pendingGuestMessageCount: 1 }),
150 NOW_MS,
151 ),
152 ).toBe(false);
153 const snoozed = shell({
154 snoozedUntil: at(60 * 60 * 1_000),
155 snoozedAt: at(-60 * 60 * 1_000),
156 pendingGuestMessageCount: 1,
157 });
158 expect(ThreadSettlementService.isSnoozed(snoozed, NOW_MS)).toBe(false);
159 });
160​
161 it("keeps snoozed threads parked until a fresh failure or timer wake", () => {
162 const snoozed = shell({
163 snoozedUntil: at(60 * 60 * 1_000),
164 snoozedAt: at(-60 * 60 * 1_000),
165 });
166 expect(ThreadSettlementService.isAutoSettlementCandidate(snoozed, NOW_MS)).toBe(false);
167 expect(
168 ThreadSettlementService.isAutoSettlementCandidate(
169 shell({ ...snoozed, status: "failed", latestRunCompletedAt: at(-30 * 60 * 1_000) }),
170 NOW_MS,
171 ),
172 ).toBe(true);
173 expect(
174 ThreadSettlementService.isAutoSettlementCandidate(
175 shell({ ...snoozed, status: "failed", latestRunCompletedAt: at(-2 * 60 * 60 * 1_000) }),
176 NOW_MS,
177 ),
178 ).toBe(false);
179 expect(
180 ThreadSettlementService.isAutoSettlementCandidate(
181 shell({ ...snoozed, status: "failed", latestRunCompletedAt: snoozed.snoozedAt }),
182 NOW_MS,
183 ),
184 ).toBe(false);
185 expect(
186 ThreadSettlementService.isAutoSettlementCandidate(
187 shell({ ...snoozed, status: "failed", latestRunCompletedAt: null }),
188 NOW_MS,
189 ),
190 ).toBe(false);
191 expect(
192 ThreadSettlementService.isAutoSettlementCandidate(
193 shell({ ...snoozed, snoozedUntil: at(-1) }),
194 NOW_MS,
195 ),
196 ).toBe(true);
197 });
198});
199​
200describe("resolveAutoSettlementAt", () => {
201 it("keeps threads with a PR from inactivity settlement only when asked", () => {
202 const input = {
203 thread: shell({
204 latestUserMessageAt: at(-4 * DAY_MS),
205 linkedPullRequest: {
206 projectId: ProjectId.make("project-1"),
207 repository: "owner/repo",
208 number: 1,
209 url: "https://example.test/owner/repo/pull/1",
210 },
211 }),
212 pullRequest: null,
213 nowMs: NOW_MS,
214 autoSettleAfterDays: 3,
215 autoSettleOnMerge: true,
216 autoSettleKeepPullRequests: true,
217 };
218 expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toBeNull();
219 expect(
220 ThreadSettlementService.resolveAutoSettlementAt({
221 ...input,
222 autoSettleKeepPullRequests: false,
223 }),
224 ).toEqual(at(-4 * DAY_MS));
225 expect(
226 ThreadSettlementService.resolveAutoSettlementAt({
227 ...input,
228 pullRequest: { state: "merged", mergedAt: DateTime.formatIso(at(-1)) },
229 }),
230 ).toEqual(at(-4 * DAY_MS));
231 });
232​
233 it("settles an idle thread with an open persisted link only while retention is off", () => {
234 const input = {
235 thread: shell({
236 latestUserMessageAt: at(-4 * DAY_MS),
237 pullRequests: [persistedLink("open", at(-5 * DAY_MS))],
238 }),
239 pullRequest: null,
240 nowMs: NOW_MS,
241 autoSettleAfterDays: 3,
242 autoSettleOnMerge: true,
243 autoSettleKeepPullRequests: false,
244 };
245 expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toEqual(at(-4 * DAY_MS));
246 expect(
247 ThreadSettlementService.resolveAutoSettlementAt({
248 ...input,
249 autoSettleKeepPullRequests: true,
250 }),
251 ).toBeNull();
252 // The open link outranks a merged lookup, so only inactivity can settle it.
253 expect(
254 ThreadSettlementService.resolveAutoSettlementAt({
255 ...input,
256 pullRequest: { state: "merged", mergedAt: DateTime.formatIso(at(-1)) },
257 autoSettleAfterDays: null,
258 }),
259 ).toBeNull();
260 });
261​
262 it("keeps an idle thread whose persisted link was never synced", () => {
263 expect(
264 ThreadSettlementService.resolveAutoSettlementAt({
265 thread: shell({
266 latestUserMessageAt: at(-4 * DAY_MS),
267 pullRequests: [persistedLink(null, at(-5 * DAY_MS))],
268 }),
269 pullRequest: null,
270 nowMs: NOW_MS,
271 autoSettleAfterDays: 3,
272 autoSettleOnMerge: true,
273 autoSettleKeepPullRequests: false,
274 }),
275 ).toBeNull();
276 });
277​
278 it("uses the latest activity time when the inactivity window elapses", () => {
279 const idle = shell({
280 latestUserMessageAt: at(-4 * DAY_MS),
281 latestRunRequestedAt: at(-4 * DAY_MS),
282 latestRunStartedAt: at(-4 * DAY_MS),
283 latestRunCompletedAt: at(-3 * DAY_MS),
284 });
285 const input = {
286 thread: idle,
287 pullRequest: null,
288 nowMs: NOW_MS,
289 autoSettleAfterDays: 2,
290 autoSettleOnMerge: true,
291 };
292 expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toEqual(at(-3 * DAY_MS));
293 expect(
294 ThreadSettlementService.resolveAutoSettlementAt({ ...input, autoSettleAfterDays: 5 }),
295 ).toBeNull();
296 expect(
297 ThreadSettlementService.resolveAutoSettlementAt({ ...input, autoSettleAfterDays: null }),
298 ).toBeNull();
299 });
300​
301 it("anchors an empty thread's inactivity at its creation time", () => {
302 const input = {
303 thread: shell({ createdAt: at(-3 * DAY_MS) }),
304 pullRequest: null,
305 nowMs: NOW_MS,
306 autoSettleAfterDays: 2,
307 autoSettleOnMerge: false,
308 };
309 expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toEqual(at(-3 * DAY_MS));
310 expect(
311 ThreadSettlementService.resolveAutoSettlementAt({
312 ...input,
313 thread: shell({ createdAt: at(-DAY_MS) }),
314 }),
315 ).toBeNull();
316 expect(
317 ThreadSettlementService.resolveAutoSettlementAt({
318 ...input,
319 thread: { ...input.thread, lastSnoozeWakeAt: at(-DAY_MS) },
320 }),
321 ).toBeNull();
322 });
323​
324 it.each(["manual", "timer"])("restarts inactivity on a %s snooze wake", (wake) => {
325 const thread = {
326 ...shell({ latestRunCompletedAt: at(-4 * DAY_MS) }),
327 ...(wake === "manual"
328 ? { lastSnoozeWakeAt: at(-1_000) }
329 : { snoozedAt: at(-3 * DAY_MS), snoozedUntil: at(-1_000) }),
330 };
331 const input = {
332 thread,
333 pullRequest: null,
334 nowMs: NOW_MS,
335 autoSettleAfterDays: 1,
336 autoSettleOnMerge: false,
337 };
338 expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toBeNull();
339 expect(
340 ThreadSettlementService.resolveAutoSettlementAt({ ...input, nowMs: NOW_MS + DAY_MS }),
341 ).toEqual(at(-1_000));
342 });
343​
344 it("settles on merge only after the user's last action and preserves the activity time", () => {
345 const thread = shell({
346 latestUserMessageAt: at(-2 * 60 * 60 * 1_000),
347 latestRunCompletedAt: at(-90 * 60 * 1_000),
348 });
349 const input = {
350 thread,
351 pullRequest: {
352 state: "merged" as const,
353 mergedAt: DateTime.formatIso(at(-60 * 60 * 1_000)),
354 },
355 nowMs: NOW_MS,
356 autoSettleAfterDays: null,
357 autoSettleOnMerge: true,
358 };
359 expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toEqual(at(-90 * 60 * 1_000));
360 expect(
361 ThreadSettlementService.resolveAutoSettlementAt({ ...input, autoSettleOnMerge: false }),
362 ).toBeNull();
363 expect(
364 ThreadSettlementService.resolveAutoSettlementAt({
365 ...input,
366 pullRequest: { state: "merged", mergedAt: DateTime.formatIso(at(-3 * 60 * 60 * 1_000)) },
367 }),
368 ).toBeNull();
369 expect(
370 ThreadSettlementService.resolveAutoSettlementAt({
371 ...input,
372 thread: shell(),
373 pullRequest: { state: "closed", closedAt: DateTime.formatIso(at(-1)) },
374 autoSettleOnMerge: false,
375 }),
376 ).toEqual(shell().createdAt);
377 });
378​
379 it("settles on merge after agent-started runs, but not after the user writes again", () => {
380 const woken = shell({
381 latestUserMessageAt: at(-30 * 60 * 1_000),
382 latestUserAuthoredMessageAt: at(-2 * 60 * 60 * 1_000),
383 latestRunRequestedAt: at(-30 * 60 * 1_000),
384 latestRunCompletedAt: at(-29 * 60 * 1_000),
385 });
386 const input = {
387 thread: woken,
388 pullRequest: { state: "merged" as const, mergedAt: DateTime.formatIso(at(-60 * 60 * 1_000)) },
389 nowMs: NOW_MS,
390 autoSettleAfterDays: null,
391 autoSettleOnMerge: true,
392 };
393 expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toEqual(at(-29 * 60 * 1_000));
394 expect(
395 ThreadSettlementService.resolveAutoSettlementAt({
396 ...input,
397 thread: { ...woken, latestUserAuthoredMessageAt: at(-30 * 60 * 1_000) },
398 }),
399 ).toBeNull();
400 });
401​
402 it("does not settle on pull requests that were already merged when linked", () => {
403 const link = (number: number, linkedAt: DateTime.Utc, mergedAt: DateTime.Utc) => ({
404 host: "example.test",
405 repository: "owner/repository",
406 number,
407 url: `https://example.test/owner/repository/pull/${number}`,
408 source: "agent" as const,
409 linkedAt: DateTime.formatIso(linkedAt),
410 snapshot: {
411 state: "merged" as const,
412 title: "Pull request",
413 headBranch: `feature-${number}`,
414 baseBranch: "main",
415 isDraft: false,
416 updatedAt: DateTime.formatIso(mergedAt),
417 syncedAt: DateTime.formatIso(linkedAt),
418 mergedAt: DateTime.formatIso(mergedAt),
419 },
420 stack: null,
421 });
422 const recorded = link(1, at(-50 * 60 * 1_000), at(-55 * 60 * 1_000));
423 const input = {
424 thread: shell({
425 latestUserMessageAt: at(-2 * 60 * 60 * 1_000),
426 latestRunCompletedAt: at(-45 * 60 * 1_000),
427 pullRequests: [recorded],
428 }),
429 pullRequest: null,
430 nowMs: NOW_MS,
431 autoSettleAfterDays: null,
432 autoSettleOnMerge: true,
433 };
434 expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toBeNull();
435 expect(
436 ThreadSettlementService.resolveAutoSettlementAt({
437 ...input,
438 thread: {
439 ...input.thread,
440 pullRequests: [recorded, link(2, at(-90 * 60 * 1_000), at(-40 * 60 * 1_000))],
441 },
442 }),
443 ).toEqual(at(-45 * 60 * 1_000));
444 });
445});
446​
447const NOW = "2026-08-28T12:00:00.000Z";
448const PROJECT_ID = ProjectId.make("settlement-project");
449​
450describe("autoSettlementSettingsKey", () => {
451 it("distinguishes a project that inherits the threshold from one that disables it", () => {
452 const inherits = ThreadSettlementService.autoSettlementSettingsKey({
453 ...DEFAULT_SERVER_SETTINGS,
454 projectSettingsOverrides: { [PROJECT_ID]: { sidebarAutoSettleOnMerge: true } },
455 });
456 const never = ThreadSettlementService.autoSettlementSettingsKey({
457 ...DEFAULT_SERVER_SETTINGS,
458 projectSettingsOverrides: {
459 [PROJECT_ID]: { sidebarAutoSettleOnMerge: true, sidebarAutoSettleAfterDays: null },
460 },
461 });
462 assert.notStrictEqual(inherits, never);
463 });
464});
465​
466type AutoSettleCommand = Extract<OrchestrationV2Command, { readonly type: "thread.auto-settle" }>;
467​
468const testCrypto = Crypto.make({
469 randomBytes: (size) => new Uint8Array(size).fill(1),
470 digest: (_algorithm, data) => Effect.succeed(data),
471});
472​
473function makeProject(
474 id: ProjectId = PROJECT_ID,
475 workspaceRoot = "/workspace/project",
476): OrchestrationProjectShell {
477 return {
478 id,
479 title: `Project ${id}`,
480 workspaceRoot,
481 defaultModelSelection: null,
482 scripts: [],
483 createdAt: "2026-08-01T00:00:00.000Z",
484 updatedAt: NOW,
485 };
487​
488function makeThread(id: string, overrides: Partial<SettlementShell> = {}): SettlementShell {
489 return shell({
490 id: ThreadId.make(id),
491 projectId: PROJECT_ID,
492 title: id,
493 createdAt: DateTime.makeUnsafe("2026-08-01T00:00:00.000Z"),
494 updatedAt: DateTime.makeUnsafe("2026-08-20T00:00:00.000Z"),
495 latestUserMessageAt: DateTime.makeUnsafe("2026-08-20T00:00:00.000Z"),
496 ...overrides,
497 });
499​
500type SettlementSnapshot = Omit<OrchestrationV2ShellSnapshot, "threads"> & {
501 readonly threads: ReadonlyArray<SettlementShell>;
502};
503​
504function makeSnapshot(
505 threads: ReadonlyArray<SettlementShell>,
506 projects: ReadonlyArray<OrchestrationProjectShell> = [makeProject()],
507): SettlementSnapshot {
508 return {
509 schemaVersion: 1,
510 snapshotSequence: 1,
511 projects,
512 threads,
513 archivedThreads: [],
514 };
516​
517function makePullRequestSummary(input: {
518 readonly projectId: ProjectId;
519 readonly repository: string;
520 readonly number: number;
521 readonly state: "open" | "closed" | "merged";
522 readonly updatedAt?: string;
523}): PullRequestSummary {
524 return {
525 provider: SourceControlProviderKind.make("github"),
526 projectId: input.projectId,
527 repository: input.repository,
528 number: input.number,
529 title: "Pull request",
530 url: `https://example.test/${input.repository}/pull/${input.number}`,
531 state: input.state,
532 headBranch: "feature",
533 baseBranch: "main",
534 updatedAt: input.updatedAt ?? NOW,
535 };
537​
538function makeBranchPullRequest(state: "open" | "closed" | "merged") {
539 return {
540 number: 42,
541 title: "Pull request",
542 url: "https://example.test/owner/repository/pull/42",
543 baseRef: "main",
544 headRef: "feature",
545 state,
546 repositoryKey: "example.test/owner/repository",
547 updatedAt: NOW,
548 closedAt: state === "closed" ? NOW : null,
549 mergedAt: state === "merged" ? NOW : null,
550 } satisfies GitManager.GitBranchPullRequest;
552​
553interface HarnessOptions {
554 readonly snapshot: SettlementSnapshot;
555 readonly settings?: ContractServerSettings;
556 readonly branchPullRequest?: GitManager.GitManager["Service"]["branchPullRequest"];
557 readonly pullRequestSummary?: PullRequestService.PullRequestService["Service"]["summary"];
558 readonly existingWorktreePaths?: ReadonlyArray<string>;
559 readonly onDispatch?: (command: AutoSettleCommand) => Effect.Effect<void>;
560 readonly onScriptRun?: (
561 input: ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput,
562 ) => Effect.Effect<void>;
563 readonly onCloseIdle?: () => Effect.Effect<void>;
564 readonly currentThreads?: ReadonlyArray<OrchestrationV2AppThread>;
566​
567const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: HarnessOptions) {
568 const activation = yield* Deferred.make<void>();
569 const snapshots = yield* Ref.make(options.snapshot);
570 const snapshotReadCount = yield* Ref.make(0);
571 const snapshotReads = yield* Queue.unbounded<number>();
572 const candidateReads = yield* Ref.make<ReadonlyArray<string | undefined>>([]);
573 const settings = yield* Ref.make(options.settings ?? DEFAULT_SERVER_SETTINGS);
574 const settingsChanges = yield* PubSub.unbounded<ContractServerSettings>();
575 const mergedPullRequests = yield* PubSub.unbounded<PullRequestService.PullRequestMergeEvent>();
576 const commands = yield* Ref.make<ReadonlyArray<AutoSettleCommand>>([]);
577 const branchCalls = yield* Ref.make<
578 ReadonlyArray<{ readonly cwd: string; readonly branch: string }>
579 >([]);
580 const summaryCalls = yield* Ref.make<
581 ReadonlyArray<{
582 readonly projectId: ProjectId;
583 readonly repository: string;
584 readonly number: number;
585 }>
586 >([]);
587 const summaryRecovery = yield* Ref.make<ReadonlyArray<boolean | undefined>>([]);
588 const invalidatedCwds = yield* Ref.make<ReadonlyArray<string>>([]);
589 const domainEvents = yield* PubSub.unbounded<OrchestrationV2DomainEvent>();
590 const closedIdle = yield* Queue.unbounded<{ readonly threadId: string }>();
591 const scriptRuns =
592 yield* Queue.unbounded<ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput>();
593​
594 const updateSettings = (patch: ServerSettingsPatch) =>
595 Effect.gen(function* () {
596 const next = applyServerSettingsPatch(yield* Ref.get(settings), patch);
597 yield* Ref.set(settings, next);
598 yield* PubSub.publish(settingsChanges, next);
599 return next;
600 });
601​
602 const branchPullRequest: GitManager.GitManager["Service"]["branchPullRequest"] = (
603 input,
604 lookupOptions,
605 ) =>
606 Ref.update(branchCalls, (calls) => [...calls, input]).pipe(
607 Effect.andThen(options.branchPullRequest?.(input, lookupOptions) ?? Effect.succeed(null)),
608 );
609 const pullRequestSummary: PullRequestService.PullRequestService["Service"]["summary"] = (
610 input,
611 readOptions,
612 ) =>
613 Effect.gen(function* () {
614 yield* Ref.update(summaryCalls, (calls) => [...calls, input]);
615 yield* Ref.update(summaryRecovery, (values) => [
616 ...values,
617 readOptions?.recoverTransientFailure,
618 ]);
619 return yield* (
620 options.pullRequestSummary?.(input, readOptions) ??
621 Effect.succeed(
622 makePullRequestSummary({
623 ...input,
624 state: "open",
625 }),
626 )
627 );
628 });
629​
630 const dispatch: Orchestrator.OrchestratorV2Shape["dispatch"] = (command) => {
631 if (command.type !== "thread.auto-settle") {
632 return Effect.die(new Error(`Unexpected command: ${command.type}`));
633 }
634 return Ref.update(commands, (recorded) => [...recorded, command]).pipe(
635 Effect.andThen(options.onDispatch?.(command) ?? Effect.void),
636 Effect.as({ sequence: 1, storedEvents: [] }),
637 );
638 };
639​
640 const serverSettings = ServerSettings.ServerSettingsService.of({
641 start: Effect.void,
642 ready: Effect.void,
643 getSettings: Ref.get(settings),
644 updateSettings,
645 updateProviderInstance: () => Effect.die("Unexpected provider mutation"),
646 withSettingsSnapshot: (use) => Ref.get(settings).pipe(Effect.flatMap(use)),
647 streamChanges: Stream.fromPubSub(settingsChanges),
648 subscribeChanges: PubSub.subscribe(settingsChanges).pipe(
649 Effect.map((subscription) => Stream.fromSubscription(subscription)),
650 ),
651 });
652​
653 const layerDependencies = Layer.mergeAll(
654 Layer.mock(ProjectStore.ProjectStoreV2)({
655 listShells: () => Ref.get(snapshots).pipe(Effect.map((snapshot) => snapshot.projects)),
656 }),
657 Layer.mock(ProjectionStore.ProjectionStoreV2)({
658 getSettlementCandidates: (threadId) =>
659 Ref.update(candidateReads, (reads) => [...reads, threadId]).pipe(
660 Effect.andThen(Ref.updateAndGet(snapshotReadCount, (count) => count + 1)),
661 Effect.tap((count) => Queue.offer(snapshotReads, count)),
662 Effect.andThen(Ref.get(snapshots)),
663 Effect.map((snapshot) =>
664 threadId === undefined
665 ? snapshot.threads
666 : snapshot.threads.filter((thread) => thread.id === threadId),
667 ),
668 ),
669 getThread: (threadId) => {
670 const thread = options.currentThreads?.find((candidate) => candidate.id === threadId);
671 return thread
672 ? Effect.succeed(thread)
673 : Effect.die(new Error(`Unexpected thread read: ${threadId}`));
674 },
675 }),
676 Layer.mock(Orchestrator.OrchestratorV2)({
677 streamDomainEvents: Stream.fromPubSub(domainEvents),
678 dispatch,
679 }),
680 Layer.mock(TerminalManager.TerminalManager)({
681 closeIdle: (input) =>
682 Queue.offer(closedIdle, input).pipe(Effect.andThen(options.onCloseIdle?.() ?? Effect.void)),
683 }),
684 Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({
685 runForThread: (input) =>
686 Queue.offer(scriptRuns, input).pipe(
687 Effect.andThen(options.onScriptRun?.(input) ?? Effect.void),
688 Effect.as({ status: "no-script" } as const),
689 ),
690 }),
691 Layer.mock(GitManager.GitManager)({
692 branchPullRequest,
693 invalidateStatus: (cwd) => Ref.update(invalidatedCwds, (cwds) => [...cwds, cwd]),
694 }),
695 Layer.mock(PullRequestService.PullRequestService)({
696 summary: pullRequestSummary,
697 subscribeMerges: PubSub.subscribe(mergedPullRequests).pipe(
698 Effect.map((subscription) => Stream.fromSubscription(subscription)),
699 ),
700 }),
701 Layer.succeed(ServerSettings.ServerSettingsService, serverSettings),
702 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
703 Layer.succeed(Crypto.Crypto, testCrypto),
704 FileSystem.layerNoop({
705 exists: (path) => Effect.succeed(options.existingWorktreePaths?.includes(path) ?? false),
706 }),
707 );
708​
709 return {
710 activation,
711 snapshots,
712 snapshotReadCount,
713 snapshotReads,
714 candidateReads,
715 commands,
716 branchCalls,
717 summaryCalls,
718 summaryRecovery,
719 invalidatedCwds,
720 closedIdle,
721 scriptRuns,
722 publishEvent: (event: OrchestrationV2DomainEvent) => PubSub.publish(domainEvents, event),
723 updateSettings,
724 publishMerge: PubSub.publish(mergedPullRequests, {
725 projectId: PROJECT_ID,
726 repository: "owner/repository",
727 number: 42,
728 mergedAt: NOW,
729 }),
730 layer: Layer.effect(
731 ThreadSettlementService.ThreadSettlementServiceV2,
732 ThreadSettlementService.make,
733 ).pipe(Layer.provide(layerDependencies)),
734 };
735});
736​
737const startHarness = Effect.fn("startThreadSettlementHarness")(function* (
738 reactor: ThreadSettlementService.ThreadSettlementServiceV2["Service"],
739 activation: Deferred.Deferred<void>,
740 snapshotReads: Queue.Queue<number>,
741) {
742 yield* reactor.start();
743 yield* Deferred.succeed(activation, undefined);
744 yield* Queue.take(snapshotReads);
745 yield* reactor.drain;
746});
747​
748describe("ThreadSettlementServiceV2 worker", () => {
749 it.effect("settles a merged pull request stored only in the thread links", () =>
750 Effect.scoped(
751 Effect.gen(function* () {
752 yield* TestClock.setTime(Date.parse(NOW));
753 const thread = makeThread("merged-link", {
754 pullRequests: [
755 {
756 host: "example.test",
757 repository: "owner/repository",
758 number: 42,
759 url: "https://example.test/owner/repository/pull/42",
760 source: "manual",
761 linkedAt: "2026-08-20T00:00:00.000Z",
762 snapshot: {
763 state: "merged",
764 title: "Pull request",
765 headBranch: "feature",
766 baseBranch: "main",
767 isDraft: false,
768 updatedAt: NOW,
769 syncedAt: NOW,
770 mergedAt: NOW,
771 },
772 stack: null,
773 },
774 ],
775 });
776 const fixture = yield* makeHarness({
777 snapshot: makeSnapshot([thread]),
778 settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: null },
779 });
780​
781 yield* Effect.gen(function* () {
782 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
783 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
784 expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
785 thread.id,
786 ]);
787 }).pipe(Effect.provide(fixture.layer));
788 }),
789 ),
790 );
791​
792 it.effect("settles an idle thread with an open persisted link on the inactivity sweep", () =>
793 Effect.scoped(
794 Effect.gen(function* () {
795 yield* TestClock.setTime(Date.parse(NOW));
796 const thread = makeThread("open-link", {
797 pullRequests: [persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z"))],
798 });
799 const fixture = yield* makeHarness({
800 snapshot: makeSnapshot([thread]),
801 settings: {
802 ...DEFAULT_SERVER_SETTINGS,
803 sidebarAutoSettleAfterDays: 3,
804 sidebarAutoSettleKeepPullRequests: false,
805 },
806 });
807 yield* Effect.gen(function* () {
808 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
809 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
810 expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
811 thread.id,
812 ]);
813 }).pipe(Effect.provide(fixture.layer));
814 }),
815 ),
816 );
817​
818 it.effect("settles only the project opted in while environment settlement is disabled", () =>
819 Effect.scoped(
820 Effect.gen(function* () {
821 yield* TestClock.setTime(Date.parse(NOW));
822 const thread = makeThread("project-opt-in", {
823 latestRunCompletedAt: DateTime.makeUnsafe("2026-08-25T00:00:00.000Z"),
824 });
825 const other = makeThread("environment-off", { projectId: ProjectId.make("other-project") });
826 const fixture = yield* makeHarness({
827 snapshot: makeSnapshot([thread, other]),
828 settings: {
829 ...DEFAULT_SERVER_SETTINGS,
830 sidebarAutoSettleAfterDays: null,
831 sidebarAutoSettleOnMerge: false,
832 projectSettingsOverrides: { [PROJECT_ID]: { sidebarAutoSettleAfterDays: 2 } },
833 },
834 });
835 yield* Effect.gen(function* () {
836 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
837 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
838 const commands = yield* Ref.get(fixture.commands);
839 expect(commands.map((command) => command.threadId)).toEqual([thread.id]);
840 }).pipe(Effect.provide(fixture.layer));
841 }),
842 ),
843 );
844​
845 it.effect("stops settling the rest of a sweep once auto-settlement is turned off", () =>
846 Effect.scoped(
847 Effect.gen(function* () {
848 yield* TestClock.setTime(Date.parse(NOW));
849 // Sweeps settle 8 threads at a time, so the ninth starts after a dispatch turned it off.
850 const threads = Array.from({ length: 9 }, (_, index) => makeThread(`idle-${index}`));
851 let disable: Effect.Effect<unknown> = Effect.void;
852 const fixture = yield* makeHarness({
853 snapshot: makeSnapshot(threads),
854 settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 3 },
855 onDispatch: () => disable,
856 });
857 disable = fixture.updateSettings({ sidebarAutoSettleAfterDays: null });
858 yield* Effect.gen(function* () {
859 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
860 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
861 const settled = (yield* Ref.get(fixture.commands)).map((command) => command.threadId);
862 expect(settled).not.toContain(threads[8]!.id);
863 }).pipe(Effect.provide(fixture.layer));
864 }),
865 ),
866 );
867​
868 it.effect("reevaluates immediately after a pull request merge", () =>
869 Effect.scoped(
870 Effect.gen(function* () {
871 yield* TestClock.setTime(Date.parse(NOW));
872 const periodicLookupStarted = yield* Deferred.make<void>();
873 const releasePeriodicLookup = yield* Deferred.make<void>();
874 const mergedThreadSettled = yield* Deferred.make<void>();
875 const branchLookupCount = yield* Ref.make(0);
876 const fixture = yield* makeHarness({
877 snapshot: makeSnapshot([
878 makeThread("merged-in-app", {
879 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
880 linkedPullRequest: {
881 projectId: PROJECT_ID,
882 repository: "Owner/Repository",
883 number: 42,
884 url: "https://example.test/owner/repository/pull/42",
885 },
886 }),
887 makeThread("slow-periodic-lookup", {
888 branch: "another-feature",
889 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
890 }),
891 ]),
892 branchPullRequest: () =>
893 Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
894 Effect.flatMap((count) =>
895 count === 1
896 ? Effect.succeed(makeBranchPullRequest("open"))
897 : Deferred.succeed(periodicLookupStarted, undefined).pipe(
898 Effect.andThen(Deferred.await(releasePeriodicLookup)),
899 Effect.as(makeBranchPullRequest("open")),
900 ),
901 ),
902 ),
903 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
904 });
905​
906 yield* Effect.gen(function* () {
907 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
908 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
909 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
910 yield* Deferred.await(periodicLookupStarted);
911​
912 yield* fixture.publishMerge;
913 yield* Deferred.await(mergedThreadSettled);
914​
915 assert.deepStrictEqual(
916 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
917 [ThreadId.make("merged-in-app")],
918 );
919 yield* Deferred.succeed(releasePeriodicLookup, undefined);
920 yield* reactor.drain;
921 }).pipe(Effect.provide(fixture.layer));
922 }),
923 ),
924 );
925​
926 it.effect("settles a merged thread when its background work ends, during a slow full sweep", () =>
927 Effect.scoped(
928 Effect.gen(function* () {
929 yield* TestClock.setTime(Date.parse(NOW));
930 const periodicLookupStarted = yield* Deferred.make<void>();
931 const releasePeriodicLookup = yield* Deferred.make<void>();
932 const settled = yield* Deferred.make<void>();
933 const branchLookupCount = yield* Ref.make(0);
934 const mergedLink: NonNullable<SettlementShell["pullRequests"]>[number] = {
935 ...persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z")),
936 snapshot: {
937 state: "merged",
938 title: "Pull request",
939 headBranch: "feature",
940 baseBranch: "main",
941 isDraft: false,
942 updatedAt: NOW,
943 syncedAt: NOW,
944 mergedAt: NOW,
945 },
946 };
947 const waiting = makeThread("waiting-on-subagent", {
948 pullRequests: [mergedLink],
949 pendingBackgroundTasks: [{ taskId: "child", kind: "subagent", description: "Review" }],
950 });
951 const slow = makeThread("slow-periodic-lookup", {
952 branch: "another-feature",
953 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
954 });
955 const fixture = yield* makeHarness({
956 snapshot: makeSnapshot([waiting, slow]),
957 branchPullRequest: () =>
958 Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
959 Effect.flatMap((count) =>
960 count === 1
961 ? Effect.succeed(makeBranchPullRequest("open"))
962 : Deferred.succeed(periodicLookupStarted, undefined).pipe(
963 Effect.andThen(Deferred.await(releasePeriodicLookup)),
964 Effect.as(makeBranchPullRequest("open")),
965 ),
966 ),
967 ),
968 onDispatch: () => Deferred.succeed(settled, undefined),
969 });
970​
971 yield* Effect.gen(function* () {
972 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
973 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
974 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
975 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
976 yield* Deferred.await(periodicLookupStarted);
977​
978 yield* Ref.set(
979 fixture.snapshots,
980 makeSnapshot([{ ...waiting, pendingBackgroundTasks: [] }, slow]),
981 );
982 yield* fixture.publishEvent({
983 type: "run.background-work-cancelled",
984 id: EventId.make("event:background-ended"),
985 threadId: waiting.id,
986 occurredAt: DateTime.makeUnsafe(NOW),
987 payload: { runId: RunId.make("run:waiting"), restartCancelledBackgroundWork: [] },
988 });
989 yield* Deferred.await(settled);
990​
991 assert.deepStrictEqual(
992 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
993 [waiting.id],
994 );
995 yield* Deferred.succeed(releasePeriodicLookup, undefined);
996 yield* reactor.drain;
997 }).pipe(Effect.provide(fixture.layer));
998 }),
999 ),
1000 );
1001​
1002 it.effect("settles a stopped thread while another thread's lookup is slow", () =>
1003 Effect.scoped(
1004 Effect.gen(function* () {
1005 yield* TestClock.setTime(Date.parse(NOW));
1006 const slowLookupStarted = yield* Deferred.make<void>();
1007 const releaseSlowLookup = yield* Deferred.make<void>();
1008 const settled = yield* Deferred.make<void>();
1009 const branchLookupCount = yield* Ref.make(0);
1010 const recent = DateTime.makeUnsafe("2026-08-27T00:00:00.000Z");
1011 const slow = makeThread("slow-lookup", { branch: "feature", latestUserMessageAt: recent });
1012 const merged = makeThread("merged", {
1013 latestUserMessageAt: recent,
1014 pullRequests: [
1016 ...persistedLink("open", recent),
1017 snapshot: {
1018 state: "merged",
1019 title: "Pull request",
1020 headBranch: "feature",
1021 baseBranch: "main",
1022 isDraft: false,
1023 updatedAt: NOW,
1024 syncedAt: NOW,
1025 mergedAt: NOW,
1026 },
1027 },
1028 ],
1029 pendingBackgroundTasks: [{ taskId: "child", kind: "subagent", description: "Review" }],
1030 });
1031 const fixture = yield* makeHarness({
1032 snapshot: makeSnapshot([slow, merged]),
1033 branchPullRequest: () =>
1034 Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
1035 Effect.flatMap((count) =>
1036 count === 1
1037 ? Effect.succeed(makeBranchPullRequest("open"))
1038 : Deferred.succeed(slowLookupStarted, undefined).pipe(
1039 Effect.andThen(Deferred.await(releaseSlowLookup)),
1040 Effect.as(makeBranchPullRequest("open")),
1041 ),
1042 ),
1043 ),
1044 onDispatch: () => Deferred.succeed(settled, undefined),
1045 });
1046 const backgroundEnded = (threadId: ThreadId): OrchestrationV2DomainEvent => ({
1047 type: "run.background-work-cancelled",
1048 id: EventId.make(`event:background-ended:${threadId}`),
1049 threadId,
1050 occurredAt: DateTime.makeUnsafe(NOW),
1051 payload: { runId: RunId.make(`run:${threadId}`), restartCancelledBackgroundWork: [] },
1052 });
1053​
1054 yield* Effect.gen(function* () {
1055 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1056 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1057 yield* fixture.publishEvent(backgroundEnded(slow.id));
1058 yield* Deferred.await(slowLookupStarted);
1059 // More events for the slow thread coalesce into one more pass, not more sweeps.
1060 for (let index = 0; index < 9; index++) {
1061 yield* fixture.publishEvent(backgroundEnded(slow.id));
1063​
1064 yield* Ref.set(
1065 fixture.snapshots,
1066 makeSnapshot([slow, { ...merged, pendingBackgroundTasks: [] }]),
1067 );
1068 yield* fixture.publishEvent(backgroundEnded(merged.id));
1069 yield* Deferred.await(settled);
1070​
1071 assert.deepStrictEqual(
1072 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1073 [merged.id],
1074 );
1075 yield* Deferred.succeed(releaseSlowLookup, undefined);
1076 yield* reactor.drain;
1077 // The startup sweep, the first per-thread sweep, and one coalesced rerun.
1078 assert.strictEqual(yield* Ref.get(branchLookupCount), 3);
1079 }).pipe(Effect.provide(fixture.layer));
1080 }),
1081 ),
1082 );
1083​
1084 it.effect("settles an unlinked branch thread its agent merged from a shell, past the cache", () =>
1085 Effect.scoped(
1086 Effect.gen(function* () {
1087 yield* TestClock.setTime(Date.parse(NOW));
1088 const settled = yield* Deferred.make<void>();
1089 const thread = makeThread("shell-merged", {
1090 branch: "saved-feature",
1091 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1092 });
1093 const fixture = yield* makeHarness({
1094 snapshot: makeSnapshot([thread]),
1095 // The host already merged it; only a fresh read sees that past the cached open lookup.
1096 branchPullRequest: (_input, lookupOptions) =>
1097 Effect.succeed(makeBranchPullRequest(lookupOptions?.refresh ? "merged" : "open")),
1098 onDispatch: () => Deferred.succeed(settled, undefined),
1099 });
1100 const at = DateTime.makeUnsafe(NOW);
1101 const runId = RunId.make("run:shell-merged");
1102 const runEnded: OrchestrationV2DomainEvent = {
1103 type: "run.background-work-cancelled",
1104 id: EventId.make("event:shell-merged:run-ended"),
1105 threadId: thread.id,
1106 occurredAt: at,
1107 payload: { runId, restartCancelledBackgroundWork: [] },
1108 };
1109​
1110 yield* Effect.gen(function* () {
1111 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1112 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1113 yield* fixture.publishEvent(runEnded);
1114 yield* Queue.take(fixture.snapshotReads);
1115 yield* reactor.drain;
1116 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1117​
1118 yield* fixture.publishEvent({
1119 type: "turn-item.updated",
1120 id: EventId.make("event:shell-merged:command"),
1121 threadId: thread.id,
1122 runId,
1123 occurredAt: at,
1124 payload: {
1125 id: TurnItemId.make("item:shell-merged:command"),
1126 threadId: thread.id,
1127 runId,
1128 nodeId: null,
1129 providerThreadId: null,
1130 providerTurnId: null,
1131 nativeItemRef: null,
1132 parentItemId: null,
1133 ordinal: 1,
1134 status: "completed",
1135 title: null,
1136 startedAt: at,
1137 completedAt: at,
1138 updatedAt: at,
1139 type: "command_execution",
1140 input: "gh pr merge 42 --squash",
1141 },
1142 });
1143 yield* Deferred.await(settled);
1144 assert.deepStrictEqual(
1145 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1146 [thread.id],
1147 );
1148 }).pipe(Effect.provide(fixture.layer));
1149 }),
1150 ),
1151 );
1152​
1153 it.effect(
1154 "settles branch threads on a pull request merge without waiting for the next sweep",
1155 () =>
1156 Effect.scoped(
1157 Effect.gen(function* () {
1158 yield* TestClock.setTime(Date.parse(NOW));
1159 const state = yield* Ref.make<"open" | "merged">("open");
1160 const mergedThreadSettled = yield* Deferred.make<void>();
1161 const fixture = yield* makeHarness({
1162 snapshot: makeSnapshot([
1163 makeThread("branch-thread", {
1164 branch: "saved-feature",
1165 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1166 }),
1167 ]),
1168 branchPullRequest: () => Ref.get(state).pipe(Effect.map(makeBranchPullRequest)),
1169 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
1170 });
1171​
1172 yield* Effect.gen(function* () {
1173 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1174 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1175 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1176 assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), []);
1177​
1178 yield* Ref.set(state, "merged");
1179 yield* fixture.publishMerge;
1180 yield* Deferred.await(mergedThreadSettled);
1181​
1182 assert.deepStrictEqual(
1183 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1184 [ThreadId.make("branch-thread")],
1185 );
1186 assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), ["/workspace/project"]);
1187 yield* reactor.drain;
1188 }).pipe(Effect.provide(fixture.layer));
1189 }),
1190 ),
1191 );
1192​
1193 it.effect("a merge does not settle threads linked to an unrelated pull request", () =>
1194 Effect.scoped(
1195 Effect.gen(function* () {
1196 yield* TestClock.setTime(Date.parse(NOW));
1197 const mergedThreadSettled = yield* Deferred.make<void>();
1198 const mergeLookupStarted = yield* Deferred.make<void>();
1199 const releaseMergeLookup = yield* Deferred.make<void>();
1200 const lookupCount = yield* Ref.make(0);
1201 const fixture = yield* makeHarness({
1202 snapshot: makeSnapshot([
1203 makeThread("merged-in-app", {
1204 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1205 linkedPullRequest: {
1206 projectId: PROJECT_ID,
1207 repository: "owner/repository",
1208 number: 42,
1209 url: "https://example.test/owner/repository/pull/42",
1210 },
1211 }),
1212 makeThread("unrelated-linked", {
1213 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1214 linkedPullRequest: {
1215 projectId: PROJECT_ID,
1216 repository: "owner/repository",
1217 number: 99,
1218 url: "https://example.test/owner/repository/pull/99",
1219 },
1220 }),
1221 ]),
1222 pullRequestSummary: (input) =>
1223 Ref.updateAndGet(lookupCount, (count) => count + 1).pipe(
1224 Effect.tap((count) =>
1225 count === 3 ? Deferred.succeed(mergeLookupStarted, undefined) : Effect.void,
1226 ),
1227 Effect.tap((count) =>
1228 count === 3 ? Deferred.await(releaseMergeLookup) : Effect.void,
1229 ),
1230 Effect.map(() => makePullRequestSummary({ ...input, state: "open" })),
1231 ),
1232 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
1233 });
1234​
1235 yield* Effect.gen(function* () {
1236 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1237 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1238 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1239​
1240 yield* fixture.publishMerge;
1241 yield* Deferred.await(mergeLookupStarted);
1242 yield* Deferred.await(mergedThreadSettled);
1243 yield* Deferred.succeed(releaseMergeLookup, undefined);
1244 yield* reactor.drain;
1245​
1246 assert.deepStrictEqual(
1247 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1248 [ThreadId.make("merged-in-app")],
1249 );
1250 assert.deepStrictEqual(
1251 (yield* Ref.get(fixture.summaryCalls))
1252 .map((call) => call.number)
1253 .toSorted((left, right) => left - right),
1254 [42, 99, 99],
1255 );
1256 }).pipe(Effect.provide(fixture.layer));
1257 }),
1258 ),
1259 );
1260});
1261​
1262describe("ThreadSettlementServiceV2 terminals", () => {
1263 const appThread = (
1264 id: string,
1265 settledOverride: OrchestrationV2AppThread["settledOverride"],
1266 worktreePath: string | null = null,
1267 ): OrchestrationV2AppThread => {
1268 const threadId = ThreadId.make(id);
1269 return {
1270 createdBy: "user",
1271 creationSource: "web",
1272 id: threadId,
1273 projectId: PROJECT_ID,
1274 title: id,
1275 providerInstanceId: ProviderInstanceId.make("codex"),
1276 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
1277 runtimeMode: "full-access",
1278 interactionMode: "default",
1279 branch: null,
1280 worktreePath,
1281 activeProviderThreadId: null,
1282 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
1283 forkedFrom: null,
1284 createdAt: DateTime.makeUnsafe(NOW),
1285 updatedAt: DateTime.makeUnsafe(NOW),
1286 archivedAt: null,
1287 settledOverride,
1288 settledAt: settledOverride === "settled" ? DateTime.makeUnsafe(NOW) : null,
1289 lastVisitedAt: null,
1290 deletedAt: null,
1291 };
1292 };
1293 const settledEvent = (thread: OrchestrationV2AppThread): OrchestrationV2DomainEvent => ({
1294 type: "thread.settled",
1295 id: EventId.make(`event:settled:${thread.id}`),
1296 threadId: thread.id,
1297 occurredAt: DateTime.makeUnsafe(NOW),
1298 payload: thread,
1299 });
1300​
1301 it.effect("keeps the terminals of a thread re-engaged before the event ran", () =>
1302 Effect.scoped(
1303 Effect.gen(function* () {
1304 const settled = appThread("reengaged-thread", "settled");
1305 const reengaged = appThread("reengaged-thread", "active");
1306 const marker = appThread("marker-thread", "settled");
1307 const fixture = yield* makeHarness({
1308 snapshot: makeSnapshot([]),
1309 currentThreads: [reengaged, marker],
1310 });
1311​
1312 yield* Effect.gen(function* () {
1313 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1314 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1315 yield* fixture.publishEvent(settledEvent(settled));
1316 yield* fixture.publishEvent(settledEvent(marker));
1317 assert.deepStrictEqual(yield* Queue.take(fixture.closedIdle), { threadId: marker.id });
1318 }).pipe(Effect.provide(fixture.layer));
1319 }),
1320 ),
1321 );
1322​
1323 it.effect("runs the settle script in the thread's own worktree", () =>
1324 Effect.scoped(
1325 Effect.gen(function* () {
1326 const shared = appThread("shared-checkout-thread", "settled");
1327 const missing = appThread("removed-worktree-thread", "settled", "/worktrees/removed");
1328 const worktree = appThread("worktree-thread", "settled", "/worktrees/thread");
1329 const fixture = yield* makeHarness({
1330 snapshot: makeSnapshot([]),
1331 currentThreads: [shared, missing, worktree],
1332 existingWorktreePaths: ["/worktrees/thread"],
1333 });
1334​
1335 yield* Effect.gen(function* () {
1336 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1337 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1338 yield* fixture.publishEvent(settledEvent(shared));
1339 yield* fixture.publishEvent(settledEvent(missing));
1340 yield* fixture.publishEvent(settledEvent(worktree));
1341 const run = yield* Queue.take(fixture.scriptRuns);
1342 assert.strictEqual(run.threadId, worktree.id);
1343 assert.strictEqual(run.worktreePath, "/worktrees/thread");
1344 assert.strictEqual(run.trigger, "settle");
1345 }).pipe(Effect.provide(fixture.layer));
1346 }),
1347 ),
1348 );
1349​
1350 it.effect("skips the settle script for a thread re-engaged while its shells close", () =>
1351 Effect.scoped(
1352 Effect.gen(function* () {
1353 const settled = appThread("reengaging-thread", "settled", "/worktrees/reengaging");
1354 const marker = appThread("marker-thread", "settled", "/worktrees/marker");
1355 const currentThreads = [settled, marker];
1356 const fixture = yield* makeHarness({
1357 snapshot: makeSnapshot([]),
1358 currentThreads,
1359 existingWorktreePaths: ["/worktrees/reengaging", "/worktrees/marker"],
1360 onCloseIdle: () =>
1361 Effect.sync(() => {
1362 currentThreads[0] = { ...settled, settledOverride: "active" };
1363 }),
1364 });
1365​
1366 yield* Effect.gen(function* () {
1367 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1368 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1369 yield* fixture.publishEvent(settledEvent(settled));
1370 yield* fixture.publishEvent(settledEvent(marker));
1371 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, marker.id);
1372 }).pipe(Effect.provide(fixture.layer));
1373 }),
1374 ),
1375 );
1376​
1377 it.effect("runs the settle script once when a settlement is re-emitted", () =>
1378 Effect.scoped(
1379 Effect.gen(function* () {
1380 const repeated = appThread("repeated-thread", "settled", "/worktrees/repeated");
1381 const marker = appThread("marker-thread", "settled", "/worktrees/marker");
1382 const fixture = yield* makeHarness({
1383 snapshot: makeSnapshot([]),
1384 currentThreads: [repeated, marker],
1385 existingWorktreePaths: ["/worktrees/repeated", "/worktrees/marker"],
1386 });
1387​
1388 yield* Effect.gen(function* () {
1389 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1390 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1391 yield* fixture.publishEvent(settledEvent(repeated));
1392 yield* fixture.publishEvent(settledEvent(repeated));
1393 yield* fixture.publishEvent(settledEvent(marker));
1394 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, repeated.id);
1395 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, marker.id);
1396 }).pipe(Effect.provide(fixture.layer));
1397 }),
1398 ),
1399 );
1400​
1401 it.effect("retries the settle script on a re-emitted settlement after a failed start", () =>
1402 Effect.scoped(
1403 Effect.gen(function* () {
1404 const thread = appThread("failed-start-thread", "settled", "/worktrees/failed-start");
1405 const starts = yield* Ref.make(0);
1406 const fixture = yield* makeHarness({
1407 snapshot: makeSnapshot([]),
1408 currentThreads: [thread],
1409 existingWorktreePaths: ["/worktrees/failed-start"],
1410 onScriptRun: () =>
1411 Ref.updateAndGet(starts, (count) => count + 1).pipe(
1412 Effect.flatMap((count) =>
1413 count === 1 ? Effect.die(new Error("terminal failed to open")) : Effect.void,
1414 ),
1415 ),
1416 });
1417​
1418 yield* Effect.gen(function* () {
1419 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1420 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1421 yield* fixture.publishEvent(settledEvent(thread));
1422 yield* fixture.publishEvent(settledEvent(thread));
1423 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, thread.id);
1424 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, thread.id);
1425 }).pipe(Effect.provide(fixture.layer));
1426 }),
1427 ),
1428 );
1429});
1430​
1431describe("isSnoozed", () => {
1432 const snoozed = { snoozedAt: at(-2 * DAY_MS), snoozedUntil: at(DAY_MS) };
1433 it("keeps a run requested and completed after snoozing parked until the timer", () => {
1434 const thread = shell({
1435 ...snoozed,
1436 status: "completed",
1437 latestRunRequestedAt: at(-2 * DAY_MS + 1),
1438 latestRunStartedAt: at(-DAY_MS - 1),
1439 latestRunCompletedAt: at(-DAY_MS),
1440 });
1441​
1442 expect(ThreadSettlementService.isSnoozed(thread, NOW_MS)).toBe(true);
1443 expect(ThreadSettlementService.isAutoSettlementCandidate(thread, NOW_MS)).toBe(false);
1444 expect(
1445 ThreadSettlementService.resolveAutoSettlementAt({
1446 thread,
1447 pullRequest: { state: "merged", mergedAt: DateTime.formatIso(at(-1)) },
1448 nowMs: NOW_MS,
1449 autoSettleAfterDays: null,
1450 autoSettleOnMerge: true,
1451 }),
1452 ).toBeNull();
1453 });
1454});