Open History to see the last commit
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);
50}
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 };
103}
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 };
130}
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 };
486}
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 });
498}
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 };
515}
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 };
536}
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;
551}
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>;
565}
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 settingsReadCount = yield* Ref.make(0);
575 const settingsChanges = yield* PubSub.unbounded<ContractServerSettings>();
576 const mergedPullRequests = yield* PubSub.unbounded<PullRequestService.PullRequestMergeEvent>();
577 const commands = yield* Ref.make<ReadonlyArray<AutoSettleCommand>>([]);
578 const branchCalls = yield* Ref.make<
579 ReadonlyArray<{ readonly cwd: string; readonly branch: string }>
580 >([]);
581 const summaryCalls = yield* Ref.make<
582 ReadonlyArray<{
583 readonly projectId: ProjectId;
584 readonly repository: string;
585 readonly number: number;
586 }>
587 >([]);
588 const summaryRecovery = yield* Ref.make<ReadonlyArray<boolean | undefined>>([]);
589 const invalidatedCwds = yield* Ref.make<ReadonlyArray<string>>([]);
590 const domainEvents = yield* PubSub.unbounded<OrchestrationV2DomainEvent>();
591 const closedIdle = yield* Queue.unbounded<{ readonly threadId: string }>();
592 const scriptRuns =
593 yield* Queue.unbounded<ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput>();
594
595 const updateSettings = (patch: ServerSettingsPatch) =>
596 Effect.gen(function* () {
597 const next = applyServerSettingsPatch(yield* Ref.get(settings), patch);
598 yield* Ref.set(settings, next);
599 yield* PubSub.publish(settingsChanges, next);
600 return next;
601 });
602
603 const branchPullRequest: GitManager.GitManager["Service"]["branchPullRequest"] = (
604 input,
605 lookupOptions,
606 ) =>
607 Ref.update(branchCalls, (calls) => [...calls, input]).pipe(
608 Effect.andThen(options.branchPullRequest?.(input, lookupOptions) ?? Effect.succeed(null)),
609 );
610 const pullRequestSummary: PullRequestService.PullRequestService["Service"]["summary"] = (
611 input,
612 readOptions,
613 ) =>
614 Effect.gen(function* () {
615 yield* Ref.update(summaryCalls, (calls) => [...calls, input]);
616 yield* Ref.update(summaryRecovery, (values) => [
617 ...values,
618 readOptions?.recoverTransientFailure,
619 ]);
620 return yield* (
621 options.pullRequestSummary?.(input, readOptions) ??
622 Effect.succeed(
623 makePullRequestSummary({
624 ...input,
625 state: "open",
626 }),
627 )
628 );
629 });
630
631 const dispatch: Orchestrator.OrchestratorV2Shape["dispatch"] = (command) => {
632 if (command.type !== "thread.auto-settle") {
633 return Effect.die(new Error(`Unexpected command: ${command.type}`));
634 }
635 return Ref.update(commands, (recorded) => [...recorded, command]).pipe(
636 Effect.andThen(options.onDispatch?.(command) ?? Effect.void),
637 Effect.as({ sequence: 1, storedEvents: [] }),
638 );
639 };
640
641 const serverSettings = ServerSettings.ServerSettingsService.of({
642 start: Effect.void,
643 ready: Effect.void,
644 getSettings: Ref.update(settingsReadCount, (count) => count + 1).pipe(
645 Effect.andThen(Ref.get(settings)),
646 ),
647 updateSettings,
648 updateProviderInstance: () => Effect.die("Unexpected provider mutation"),
649 withSettingsSnapshot: (use) => Ref.get(settings).pipe(Effect.flatMap(use)),
650 streamChanges: Stream.fromPubSub(settingsChanges),
651 subscribeChanges: PubSub.subscribe(settingsChanges).pipe(
652 Effect.map((subscription) => Stream.fromSubscription(subscription)),
653 ),
654 });
655
656 const layerDependencies = Layer.mergeAll(
657 Layer.mock(ProjectStore.ProjectStoreV2)({
658 listShells: () => Ref.get(snapshots).pipe(Effect.map((snapshot) => snapshot.projects)),
659 }),
660 Layer.mock(ProjectionStore.ProjectionStoreV2)({
661 getSettlementCandidates: (threadId) =>
662 Ref.update(candidateReads, (reads) => [...reads, threadId]).pipe(
663 Effect.andThen(Ref.updateAndGet(snapshotReadCount, (count) => count + 1)),
664 Effect.tap((count) => Queue.offer(snapshotReads, count)),
665 Effect.andThen(Ref.get(snapshots)),
666 Effect.map((snapshot) =>
667 threadId === undefined
668 ? snapshot.threads
669 : snapshot.threads.filter((thread) => thread.id === threadId),
670 ),
671 ),
672 getThread: (threadId) => {
673 const thread = options.currentThreads?.find((candidate) => candidate.id === threadId);
674 return thread
675 ? Effect.succeed(thread)
676 : Effect.die(new Error(`Unexpected thread read: ${threadId}`));
677 },
678 }),
679 Layer.mock(Orchestrator.OrchestratorV2)({
680 streamDomainEvents: Stream.fromPubSub(domainEvents),
681 dispatch,
682 }),
683 Layer.mock(TerminalManager.TerminalManager)({
684 closeIdle: (input) =>
685 Queue.offer(closedIdle, input).pipe(Effect.andThen(options.onCloseIdle?.() ?? Effect.void)),
686 }),
687 Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({
688 runForThread: (input) =>
689 Queue.offer(scriptRuns, input).pipe(
690 Effect.andThen(options.onScriptRun?.(input) ?? Effect.void),
691 Effect.as({ status: "no-script" } as const),
692 ),
693 }),
694 Layer.mock(GitManager.GitManager)({
695 branchPullRequest,
696 invalidateStatus: (cwd) => Ref.update(invalidatedCwds, (cwds) => [...cwds, cwd]),
697 }),
698 Layer.mock(PullRequestService.PullRequestService)({
699 summary: pullRequestSummary,
700 subscribeMerges: PubSub.subscribe(mergedPullRequests).pipe(
701 Effect.map((subscription) => Stream.fromSubscription(subscription)),
702 ),
703 }),
704 Layer.succeed(ServerSettings.ServerSettingsService, serverSettings),
705 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
706 Layer.succeed(Crypto.Crypto, testCrypto),
707 FileSystem.layerNoop({
708 exists: (path) => Effect.succeed(options.existingWorktreePaths?.includes(path) ?? false),
709 }),
710 );
711
712 return {
713 activation,
714 snapshots,
715 snapshotReadCount,
716 settingsReadCount,
717 snapshotReads,
718 candidateReads,
719 commands,
720 branchCalls,
721 summaryCalls,
722 summaryRecovery,
723 invalidatedCwds,
724 closedIdle,
725 scriptRuns,
726 publishEvent: (event: OrchestrationV2DomainEvent) => PubSub.publish(domainEvents, event),
727 updateSettings,
728 publishMerge: PubSub.publish(mergedPullRequests, {
729 projectId: PROJECT_ID,
730 repository: "owner/repository",
731 number: 42,
732 mergedAt: NOW,
733 }),
734 layer: Layer.effect(
735 ThreadSettlementService.ThreadSettlementServiceV2,
736 ThreadSettlementService.make,
737 ).pipe(Layer.provide(layerDependencies)),
738 };
739});
740
741const startHarness = Effect.fn("startThreadSettlementHarness")(function* (
742 reactor: ThreadSettlementService.ThreadSettlementServiceV2["Service"],
743 activation: Deferred.Deferred<void>,
744 snapshotReads: Queue.Queue<number>,
745) {
746 yield* reactor.start();
747 yield* Deferred.succeed(activation, undefined);
748 yield* Queue.take(snapshotReads);
749 yield* reactor.drain;
750});
751
752describe("ThreadSettlementServiceV2 worker", () => {
753 it.effect("skips settings and PR decisions for recent branchless threads", () =>
754 Effect.scoped(
755 Effect.gen(function* () {
756 yield* TestClock.setTime(Date.parse(NOW));
757 const threads = Array.from({ length: 32 }, (_, index) =>
758 makeThread(`recent-${index}`, {
759 updatedAt: DateTime.makeUnsafe(NOW),
760 latestUserMessageAt: DateTime.makeUnsafe(Date.parse(NOW) - 2 * DAY_MS),
761 }),
762 );
763 const fixture = yield* makeHarness({
764 snapshot: makeSnapshot(threads),
765 settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 3 },
766 });
767 yield* Effect.gen(function* () {
768 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
769 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
770 assert.deepEqual(yield* Ref.get(fixture.commands), []);
771 assert.deepEqual(yield* Ref.get(fixture.branchCalls), []);
772 assert.equal(yield* Ref.get(fixture.settingsReadCount), 2);
773 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 1 });
774 yield* Queue.take(fixture.snapshotReads);
775 yield* service.drain;
776 assert.deepEqual(
777 new Set((yield* Ref.get(fixture.commands)).map((command) => command.threadId)),
778 new Set(threads.map((thread) => thread.id)),
779 );
780 }).pipe(Effect.provide(fixture.layer));
781 }),
782 ),
783 );
784 it.effect("settles a merged pull request stored only in the thread links", () =>
785 Effect.scoped(
786 Effect.gen(function* () {
787 yield* TestClock.setTime(Date.parse(NOW));
788 const thread = makeThread("merged-link", {
789 pullRequests: [
790 {
791 host: "example.test",
792 repository: "owner/repository",
793 number: 42,
794 url: "https://example.test/owner/repository/pull/42",
795 source: "manual",
796 linkedAt: "2026-08-20T00:00:00.000Z",
797 snapshot: {
798 state: "merged",
799 title: "Pull request",
800 headBranch: "feature",
801 baseBranch: "main",
802 isDraft: false,
803 updatedAt: NOW,
804 syncedAt: NOW,
805 mergedAt: NOW,
806 },
807 stack: null,
808 },
809 ],
810 });
811 const fixture = yield* makeHarness({
812 snapshot: makeSnapshot([thread]),
813 settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: null },
814 });
815
816 yield* Effect.gen(function* () {
817 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
818 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
819 expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
820 thread.id,
821 ]);
822 }).pipe(Effect.provide(fixture.layer));
823 }),
824 ),
825 );
826
827 it.effect("settles an idle thread with an open persisted link on the inactivity sweep", () =>
828 Effect.scoped(
829 Effect.gen(function* () {
830 yield* TestClock.setTime(Date.parse(NOW));
831 const thread = makeThread("open-link", {
832 pullRequests: [persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z"))],
833 });
834 const fixture = yield* makeHarness({
835 snapshot: makeSnapshot([thread]),
836 settings: {
837 ...DEFAULT_SERVER_SETTINGS,
838 sidebarAutoSettleAfterDays: 3,
839 sidebarAutoSettleKeepPullRequests: false,
840 },
841 });
842 yield* Effect.gen(function* () {
843 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
844 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
845 expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
846 thread.id,
847 ]);
848 }).pipe(Effect.provide(fixture.layer));
849 }),
850 ),
851 );
852
853 it.effect("settles only the project opted in while environment settlement is disabled", () =>
854 Effect.scoped(
855 Effect.gen(function* () {
856 yield* TestClock.setTime(Date.parse(NOW));
857 const thread = makeThread("project-opt-in", {
858 latestRunCompletedAt: DateTime.makeUnsafe("2026-08-25T00:00:00.000Z"),
859 });
860 const other = makeThread("environment-off", { projectId: ProjectId.make("other-project") });
861 const fixture = yield* makeHarness({
862 snapshot: makeSnapshot([thread, other]),
863 settings: {
864 ...DEFAULT_SERVER_SETTINGS,
865 sidebarAutoSettleAfterDays: null,
866 sidebarAutoSettleOnMerge: false,
867 projectSettingsOverrides: { [PROJECT_ID]: { sidebarAutoSettleAfterDays: 2 } },
868 },
869 });
870 yield* Effect.gen(function* () {
871 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
872 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
873 const commands = yield* Ref.get(fixture.commands);
874 expect(commands.map((command) => command.threadId)).toEqual([thread.id]);
875 }).pipe(Effect.provide(fixture.layer));
876 }),
877 ),
878 );
879
880 it.effect("stops settling the rest of a sweep once auto-settlement is turned off", () =>
881 Effect.scoped(
882 Effect.gen(function* () {
883 yield* TestClock.setTime(Date.parse(NOW));
884 // Sweeps settle 8 threads at a time, so the ninth starts after a dispatch turned it off.
885 const threads = Array.from({ length: 9 }, (_, index) => makeThread(`idle-${index}`));
886 let disable: Effect.Effect<unknown> = Effect.void;
887 const fixture = yield* makeHarness({
888 snapshot: makeSnapshot(threads),
889 settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 3 },
890 onDispatch: () => disable,
891 });
892 disable = fixture.updateSettings({ sidebarAutoSettleAfterDays: null });
893 yield* Effect.gen(function* () {
894 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
895 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
896 const settled = (yield* Ref.get(fixture.commands)).map((command) => command.threadId);
897 expect(settled).not.toContain(threads[8]!.id);
898 }).pipe(Effect.provide(fixture.layer));
899 }),
900 ),
901 );
902
903 it.effect("reevaluates immediately after a pull request merge", () =>
904 Effect.scoped(
905 Effect.gen(function* () {
906 yield* TestClock.setTime(Date.parse(NOW));
907 const periodicLookupStarted = yield* Deferred.make<void>();
908 const releasePeriodicLookup = yield* Deferred.make<void>();
909 const mergedThreadSettled = yield* Deferred.make<void>();
910 const branchLookupCount = yield* Ref.make(0);
911 const fixture = yield* makeHarness({
912 snapshot: makeSnapshot([
913 makeThread("merged-in-app", {
914 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
915 linkedPullRequest: {
916 projectId: PROJECT_ID,
917 repository: "Owner/Repository",
918 number: 42,
919 url: "https://example.test/owner/repository/pull/42",
920 },
921 }),
922 makeThread("slow-periodic-lookup", {
923 branch: "another-feature",
924 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
925 }),
926 ]),
927 branchPullRequest: () =>
928 Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
929 Effect.flatMap((count) =>
930 count === 1
931 ? Effect.succeed(makeBranchPullRequest("open"))
932 : Deferred.succeed(periodicLookupStarted, undefined).pipe(
933 Effect.andThen(Deferred.await(releasePeriodicLookup)),
934 Effect.as(makeBranchPullRequest("open")),
935 ),
936 ),
937 ),
938 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
939 });
940
941 yield* Effect.gen(function* () {
942 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
943 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
944 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
945 yield* Deferred.await(periodicLookupStarted);
946
947 yield* fixture.publishMerge;
948 yield* Deferred.await(mergedThreadSettled);
949
950 assert.deepStrictEqual(
951 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
952 [ThreadId.make("merged-in-app")],
953 );
954 yield* Deferred.succeed(releasePeriodicLookup, undefined);
955 yield* reactor.drain;
956 }).pipe(Effect.provide(fixture.layer));
957 }),
958 ),
959 );
960
961 it.effect("settles a merged thread when its background work ends, during a slow full sweep", () =>
962 Effect.scoped(
963 Effect.gen(function* () {
964 yield* TestClock.setTime(Date.parse(NOW));
965 const periodicLookupStarted = yield* Deferred.make<void>();
966 const releasePeriodicLookup = yield* Deferred.make<void>();
967 const settled = yield* Deferred.make<void>();
968 const branchLookupCount = yield* Ref.make(0);
969 const mergedLink: NonNullable<SettlementShell["pullRequests"]>[number] = {
970 ...persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z")),
971 snapshot: {
972 state: "merged",
973 title: "Pull request",
974 headBranch: "feature",
975 baseBranch: "main",
976 isDraft: false,
977 updatedAt: NOW,
978 syncedAt: NOW,
979 mergedAt: NOW,
980 },
981 };
982 const waiting = makeThread("waiting-on-subagent", {
983 pullRequests: [mergedLink],
984 pendingBackgroundTasks: [{ taskId: "child", kind: "subagent", description: "Review" }],
985 });
986 const slow = makeThread("slow-periodic-lookup", {
987 branch: "another-feature",
988 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
989 });
990 const fixture = yield* makeHarness({
991 snapshot: makeSnapshot([waiting, slow]),
992 branchPullRequest: () =>
993 Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
994 Effect.flatMap((count) =>
995 count === 1
996 ? Effect.succeed(makeBranchPullRequest("open"))
997 : Deferred.succeed(periodicLookupStarted, undefined).pipe(
998 Effect.andThen(Deferred.await(releasePeriodicLookup)),
999 Effect.as(makeBranchPullRequest("open")),
1000 ),
1001 ),
1002 ),
1003 onDispatch: () => Deferred.succeed(settled, undefined),
1004 });
1005
1006 yield* Effect.gen(function* () {
1007 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1008 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1009 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1010 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
1011 yield* Deferred.await(periodicLookupStarted);
1012
1013 yield* Ref.set(
1014 fixture.snapshots,
1015 makeSnapshot([{ ...waiting, pendingBackgroundTasks: [] }, slow]),
1016 );
1017 yield* fixture.publishEvent({
1018 type: "run.background-work-cancelled",
1019 id: EventId.make("event:background-ended"),
1020 threadId: waiting.id,
1021 occurredAt: DateTime.makeUnsafe(NOW),
1022 payload: { runId: RunId.make("run:waiting"), restartCancelledBackgroundWork: [] },
1023 });
1024 yield* Deferred.await(settled);
1025
1026 assert.deepStrictEqual(
1027 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1028 [waiting.id],
1029 );
1030 yield* Deferred.succeed(releasePeriodicLookup, undefined);
1031 yield* reactor.drain;
1032 }).pipe(Effect.provide(fixture.layer));
1033 }),
1034 ),
1035 );
1036
1037 it.effect("settles a stopped thread while another thread's lookup is slow", () =>
1038 Effect.scoped(
1039 Effect.gen(function* () {
1040 yield* TestClock.setTime(Date.parse(NOW));
1041 const slowLookupStarted = yield* Deferred.make<void>();
1042 const releaseSlowLookup = yield* Deferred.make<void>();
1043 const settled = yield* Deferred.make<void>();
1044 const branchLookupCount = yield* Ref.make(0);
1045 const recent = DateTime.makeUnsafe("2026-08-27T00:00:00.000Z");
1046 const slow = makeThread("slow-lookup", { branch: "feature", latestUserMessageAt: recent });
1047 const merged = makeThread("merged", {
1048 latestUserMessageAt: recent,
1049 pullRequests: [
1050 {
1051 ...persistedLink("open", recent),
1052 snapshot: {
1053 state: "merged",
1054 title: "Pull request",
1055 headBranch: "feature",
1056 baseBranch: "main",
1057 isDraft: false,
1058 updatedAt: NOW,
1059 syncedAt: NOW,
1060 mergedAt: NOW,
1061 },
1062 },
1063 ],
1064 pendingBackgroundTasks: [{ taskId: "child", kind: "subagent", description: "Review" }],
1065 });
1066 const fixture = yield* makeHarness({
1067 snapshot: makeSnapshot([slow, merged]),
1068 branchPullRequest: () =>
1069 Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
1070 Effect.flatMap((count) =>
1071 count === 1
1072 ? Effect.succeed(makeBranchPullRequest("open"))
1073 : Deferred.succeed(slowLookupStarted, undefined).pipe(
1074 Effect.andThen(Deferred.await(releaseSlowLookup)),
1075 Effect.as(makeBranchPullRequest("open")),
1076 ),
1077 ),
1078 ),
1079 onDispatch: () => Deferred.succeed(settled, undefined),
1080 });
1081 const backgroundEnded = (threadId: ThreadId): OrchestrationV2DomainEvent => ({
1082 type: "run.background-work-cancelled",
1083 id: EventId.make(`event:background-ended:${threadId}`),
1084 threadId,
1085 occurredAt: DateTime.makeUnsafe(NOW),
1086 payload: { runId: RunId.make(`run:${threadId}`), restartCancelledBackgroundWork: [] },
1087 });
1088
1089 yield* Effect.gen(function* () {
1090 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1091 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1092 yield* fixture.publishEvent(backgroundEnded(slow.id));
1093 yield* Deferred.await(slowLookupStarted);
1094 // More events for the slow thread coalesce into one more pass, not more sweeps.
1095 for (let index = 0; index < 9; index++) {
1096 yield* fixture.publishEvent(backgroundEnded(slow.id));
1097 }
1098
1099 yield* Ref.set(
1100 fixture.snapshots,
1101 makeSnapshot([slow, { ...merged, pendingBackgroundTasks: [] }]),
1102 );
1103 yield* fixture.publishEvent(backgroundEnded(merged.id));
1104 yield* Deferred.await(settled);
1105
1106 assert.deepStrictEqual(
1107 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1108 [merged.id],
1109 );
1110 yield* Deferred.succeed(releaseSlowLookup, undefined);
1111 yield* reactor.drain;
1112 // The startup sweep, the first per-thread sweep, and one coalesced rerun.
1113 assert.strictEqual(yield* Ref.get(branchLookupCount), 3);
1114 }).pipe(Effect.provide(fixture.layer));
1115 }),
1116 ),
1117 );
1118
1119 it.effect("settles an unlinked branch thread its agent merged from a shell, past the cache", () =>
1120 Effect.scoped(
1121 Effect.gen(function* () {
1122 yield* TestClock.setTime(Date.parse(NOW));
1123 const settled = yield* Deferred.make<void>();
1124 const thread = makeThread("shell-merged", {
1125 branch: "saved-feature",
1126 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1127 });
1128 const fixture = yield* makeHarness({
1129 snapshot: makeSnapshot([thread]),
1130 // The host already merged it; only a fresh read sees that past the cached open lookup.
1131 branchPullRequest: (_input, lookupOptions) =>
1132 Effect.succeed(makeBranchPullRequest(lookupOptions?.refresh ? "merged" : "open")),
1133 onDispatch: () => Deferred.succeed(settled, undefined),
1134 });
1135 const at = DateTime.makeUnsafe(NOW);
1136 const runId = RunId.make("run:shell-merged");
1137 const runEnded: OrchestrationV2DomainEvent = {
1138 type: "run.background-work-cancelled",
1139 id: EventId.make("event:shell-merged:run-ended"),
1140 threadId: thread.id,
1141 occurredAt: at,
1142 payload: { runId, restartCancelledBackgroundWork: [] },
1143 };
1144
1145 yield* Effect.gen(function* () {
1146 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1147 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1148 yield* fixture.publishEvent(runEnded);
1149 yield* Queue.take(fixture.snapshotReads);
1150 yield* reactor.drain;
1151 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1152
1153 yield* fixture.publishEvent({
1154 type: "turn-item.updated",
1155 id: EventId.make("event:shell-merged:command"),
1156 threadId: thread.id,
1157 runId,
1158 occurredAt: at,
1159 payload: {
1160 id: TurnItemId.make("item:shell-merged:command"),
1161 threadId: thread.id,
1162 runId,
1163 nodeId: null,
1164 providerThreadId: null,
1165 providerTurnId: null,
1166 nativeItemRef: null,
1167 parentItemId: null,
1168 ordinal: 1,
1169 status: "completed",
1170 title: null,
1171 startedAt: at,
1172 completedAt: at,
1173 updatedAt: at,
1174 type: "command_execution",
1175 input: "gh pr merge 42 --squash",
1176 },
1177 });
1178 yield* Deferred.await(settled);
1179 assert.deepStrictEqual(
1180 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1181 [thread.id],
1182 );
1183 }).pipe(Effect.provide(fixture.layer));
1184 }),
1185 ),
1186 );
1187
1188 it.effect(
1189 "settles branch threads on a pull request merge without waiting for the next sweep",
1190 () =>
1191 Effect.scoped(
1192 Effect.gen(function* () {
1193 yield* TestClock.setTime(Date.parse(NOW));
1194 const state = yield* Ref.make<"open" | "merged">("open");
1195 const mergedThreadSettled = yield* Deferred.make<void>();
1196 const fixture = yield* makeHarness({
1197 snapshot: makeSnapshot([
1198 makeThread("branch-thread", {
1199 branch: "saved-feature",
1200 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1201 }),
1202 ]),
1203 branchPullRequest: () => Ref.get(state).pipe(Effect.map(makeBranchPullRequest)),
1204 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
1205 });
1206
1207 yield* Effect.gen(function* () {
1208 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1209 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1210 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1211 assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), []);
1212
1213 yield* Ref.set(state, "merged");
1214 yield* fixture.publishMerge;
1215 yield* Deferred.await(mergedThreadSettled);
1216
1217 assert.deepStrictEqual(
1218 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1219 [ThreadId.make("branch-thread")],
1220 );
1221 assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), ["/workspace/project"]);
1222 yield* reactor.drain;
1223 }).pipe(Effect.provide(fixture.layer));
1224 }),
1225 ),
1226 );
1227
1228 it.effect("a merge does not settle threads linked to an unrelated pull request", () =>
1229 Effect.scoped(
1230 Effect.gen(function* () {
1231 yield* TestClock.setTime(Date.parse(NOW));
1232 const mergedThreadSettled = yield* Deferred.make<void>();
1233 const mergeLookupStarted = yield* Deferred.make<void>();
1234 const releaseMergeLookup = yield* Deferred.make<void>();
1235 const lookupCount = yield* Ref.make(0);
1236 const fixture = yield* makeHarness({
1237 snapshot: makeSnapshot([
1238 makeThread("merged-in-app", {
1239 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1240 linkedPullRequest: {
1241 projectId: PROJECT_ID,
1242 repository: "owner/repository",
1243 number: 42,
1244 url: "https://example.test/owner/repository/pull/42",
1245 },
1246 }),
1247 makeThread("unrelated-linked", {
1248 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1249 linkedPullRequest: {
1250 projectId: PROJECT_ID,
1251 repository: "owner/repository",
1252 number: 99,
1253 url: "https://example.test/owner/repository/pull/99",
1254 },
1255 }),
1256 ]),
1257 pullRequestSummary: (input) =>
1258 Ref.updateAndGet(lookupCount, (count) => count + 1).pipe(
1259 Effect.tap((count) =>
1260 count === 3 ? Deferred.succeed(mergeLookupStarted, undefined) : Effect.void,
1261 ),
1262 Effect.tap((count) =>
1263 count === 3 ? Deferred.await(releaseMergeLookup) : Effect.void,
1264 ),
1265 Effect.map(() => makePullRequestSummary({ ...input, state: "open" })),
1266 ),
1267 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
1268 });
1269
1270 yield* Effect.gen(function* () {
1271 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1272 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1273 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1274
1275 yield* fixture.publishMerge;
1276 yield* Deferred.await(mergeLookupStarted);
1277 yield* Deferred.await(mergedThreadSettled);
1278 yield* Deferred.succeed(releaseMergeLookup, undefined);
1279 yield* reactor.drain;
1280
1281 assert.deepStrictEqual(
1282 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1283 [ThreadId.make("merged-in-app")],
1284 );
1285 assert.deepStrictEqual(
1286 (yield* Ref.get(fixture.summaryCalls))
1287 .map((call) => call.number)
1288 .toSorted((left, right) => left - right),
1289 [42, 99, 99],
1290 );
1291 }).pipe(Effect.provide(fixture.layer));
1292 }),
1293 ),
1294 );
1295});
1296
1297describe("ThreadSettlementServiceV2 terminals", () => {
1298 const appThread = (
1299 id: string,
1300 settledOverride: OrchestrationV2AppThread["settledOverride"],
1301 worktreePath: string | null = null,
1302 ): OrchestrationV2AppThread => {
1303 const threadId = ThreadId.make(id);
1304 return {
1305 createdBy: "user",
1306 creationSource: "web",
1307 id: threadId,
1308 projectId: PROJECT_ID,
1309 title: id,
1310 providerInstanceId: ProviderInstanceId.make("codex"),
1311 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
1312 runtimeMode: "full-access",
1313 interactionMode: "default",
1314 branch: null,
1315 worktreePath,
1316 activeProviderThreadId: null,
1317 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
1318 forkedFrom: null,
1319 createdAt: DateTime.makeUnsafe(NOW),
1320 updatedAt: DateTime.makeUnsafe(NOW),
1321 archivedAt: null,
1322 settledOverride,
1323 settledAt: settledOverride === "settled" ? DateTime.makeUnsafe(NOW) : null,
1324 lastVisitedAt: null,
1325 deletedAt: null,
1326 };
1327 };
1328 const settledEvent = (thread: OrchestrationV2AppThread): OrchestrationV2DomainEvent => ({
1329 type: "thread.settled",
1330 id: EventId.make(`event:settled:${thread.id}`),
1331 threadId: thread.id,
1332 occurredAt: DateTime.makeUnsafe(NOW),
1333 payload: thread,
1334 });
1335
1336 it.effect("keeps the terminals of a thread re-engaged before the event ran", () =>
1337 Effect.scoped(
1338 Effect.gen(function* () {
1339 const settled = appThread("reengaged-thread", "settled");
1340 const reengaged = appThread("reengaged-thread", "active");
1341 const marker = appThread("marker-thread", "settled");
1342 const fixture = yield* makeHarness({
1343 snapshot: makeSnapshot([]),
1344 currentThreads: [reengaged, marker],
1345 });
1346
1347 yield* Effect.gen(function* () {
1348 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1349 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1350 yield* fixture.publishEvent(settledEvent(settled));
1351 yield* fixture.publishEvent(settledEvent(marker));
1352 assert.deepStrictEqual(yield* Queue.take(fixture.closedIdle), { threadId: marker.id });
1353 }).pipe(Effect.provide(fixture.layer));
1354 }),
1355 ),
1356 );
1357
1358 it.effect("runs the settle script in the thread's own worktree", () =>
1359 Effect.scoped(
1360 Effect.gen(function* () {
1361 const shared = appThread("shared-checkout-thread", "settled");
1362 const missing = appThread("removed-worktree-thread", "settled", "/worktrees/removed");
1363 const worktree = appThread("worktree-thread", "settled", "/worktrees/thread");
1364 const fixture = yield* makeHarness({
1365 snapshot: makeSnapshot([]),
1366 currentThreads: [shared, missing, worktree],
1367 existingWorktreePaths: ["/worktrees/thread"],
1368 });
1369
1370 yield* Effect.gen(function* () {
1371 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1372 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1373 yield* fixture.publishEvent(settledEvent(shared));
1374 yield* fixture.publishEvent(settledEvent(missing));
1375 yield* fixture.publishEvent(settledEvent(worktree));
1376 const run = yield* Queue.take(fixture.scriptRuns);
1377 assert.strictEqual(run.threadId, worktree.id);
1378 assert.strictEqual(run.worktreePath, "/worktrees/thread");
1379 assert.strictEqual(run.trigger, "settle");
1380 }).pipe(Effect.provide(fixture.layer));
1381 }),
1382 ),
1383 );
1384
1385 it.effect("skips the settle script for a thread re-engaged while its shells close", () =>
1386 Effect.scoped(
1387 Effect.gen(function* () {
1388 const settled = appThread("reengaging-thread", "settled", "/worktrees/reengaging");
1389 const marker = appThread("marker-thread", "settled", "/worktrees/marker");
1390 const currentThreads = [settled, marker];
1391 const fixture = yield* makeHarness({
1392 snapshot: makeSnapshot([]),
1393 currentThreads,
1394 existingWorktreePaths: ["/worktrees/reengaging", "/worktrees/marker"],
1395 onCloseIdle: () =>
1396 Effect.sync(() => {
1397 currentThreads[0] = { ...settled, settledOverride: "active" };
1398 }),
1399 });
1400
1401 yield* Effect.gen(function* () {
1402 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1403 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1404 yield* fixture.publishEvent(settledEvent(settled));
1405 yield* fixture.publishEvent(settledEvent(marker));
1406 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, marker.id);
1407 }).pipe(Effect.provide(fixture.layer));
1408 }),
1409 ),
1410 );
1411
1412 it.effect("runs the settle script once when a settlement is re-emitted", () =>
1413 Effect.scoped(
1414 Effect.gen(function* () {
1415 const repeated = appThread("repeated-thread", "settled", "/worktrees/repeated");
1416 const marker = appThread("marker-thread", "settled", "/worktrees/marker");
1417 const fixture = yield* makeHarness({
1418 snapshot: makeSnapshot([]),
1419 currentThreads: [repeated, marker],
1420 existingWorktreePaths: ["/worktrees/repeated", "/worktrees/marker"],
1421 });
1422
1423 yield* Effect.gen(function* () {
1424 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1425 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1426 yield* fixture.publishEvent(settledEvent(repeated));
1427 yield* fixture.publishEvent(settledEvent(repeated));
1428 yield* fixture.publishEvent(settledEvent(marker));
1429 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, repeated.id);
1430 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, marker.id);
1431 }).pipe(Effect.provide(fixture.layer));
1432 }),
1433 ),
1434 );
1435
1436 it.effect("retries the settle script on a re-emitted settlement after a failed start", () =>
1437 Effect.scoped(
1438 Effect.gen(function* () {
1439 const thread = appThread("failed-start-thread", "settled", "/worktrees/failed-start");
1440 const starts = yield* Ref.make(0);
1441 const fixture = yield* makeHarness({
1442 snapshot: makeSnapshot([]),
1443 currentThreads: [thread],
1444 existingWorktreePaths: ["/worktrees/failed-start"],
1445 onScriptRun: () =>
1446 Ref.updateAndGet(starts, (count) => count + 1).pipe(
1447 Effect.flatMap((count) =>
1448 count === 1 ? Effect.die(new Error("terminal failed to open")) : Effect.void,
1449 ),
1450 ),
1451 });
1452
1453 yield* Effect.gen(function* () {
1454 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1455 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1456 yield* fixture.publishEvent(settledEvent(thread));
1457 yield* fixture.publishEvent(settledEvent(thread));
1458 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, thread.id);
1459 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, thread.id);
1460 }).pipe(Effect.provide(fixture.layer));
1461 }),
1462 ),
1463 );
1464});
1465
1466describe("isSnoozed", () => {
1467 const snoozed = { snoozedAt: at(-2 * DAY_MS), snoozedUntil: at(DAY_MS) };
1468 it("keeps a run requested and completed after snoozing parked until the timer", () => {
1469 const thread = shell({
1470 ...snoozed,
1471 status: "completed",
1472 latestRunRequestedAt: at(-2 * DAY_MS + 1),
1473 latestRunStartedAt: at(-DAY_MS - 1),
1474 latestRunCompletedAt: at(-DAY_MS),
1475 });
1476
1477 expect(ThreadSettlementService.isSnoozed(thread, NOW_MS)).toBe(true);
1478 expect(ThreadSettlementService.isAutoSettlementCandidate(thread, NOW_MS)).toBe(false);
1479 expect(
1480 ThreadSettlementService.resolveAutoSettlementAt({
1481 thread,
1482 pullRequest: { state: "merged", mergedAt: DateTime.formatIso(at(-1)) },
1483 nowMs: NOW_MS,
1484 autoSettleAfterDays: null,
1485 autoSettleOnMerge: true,
1486 }),
1487 ).toBeNull();
1488 });
1489});