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 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: ThreadSettlementService.layer.pipe(Layer.provide(layerDependencies)),
731 };
732});
733
734const startHarness = Effect.fn("startThreadSettlementHarness")(function* (
735 reactor: ThreadSettlementService.ThreadSettlementServiceV2["Service"],
736 activation: Deferred.Deferred<void>,
737 snapshotReads: Queue.Queue<number>,
738) {
739 yield* reactor.start();
740 yield* Deferred.succeed(activation, undefined);
741 yield* Queue.take(snapshotReads);
742 yield* reactor.drain;
743});
744
745describe("ThreadSettlementServiceV2 worker", () => {
746 it.effect("settles a merged pull request stored only in the thread links", () =>
747 Effect.scoped(
748 Effect.gen(function* () {
749 yield* TestClock.setTime(Date.parse(NOW));
750 const thread = makeThread("merged-link", {
751 pullRequests: [
752 {
753 host: "example.test",
754 repository: "owner/repository",
755 number: 42,
756 url: "https://example.test/owner/repository/pull/42",
757 source: "manual",
758 linkedAt: "2026-08-20T00:00:00.000Z",
759 snapshot: {
760 state: "merged",
761 title: "Pull request",
762 headBranch: "feature",
763 baseBranch: "main",
764 isDraft: false,
765 updatedAt: NOW,
766 syncedAt: NOW,
767 mergedAt: NOW,
768 },
769 stack: null,
770 },
771 ],
772 });
773 const fixture = yield* makeHarness({
774 snapshot: makeSnapshot([thread]),
775 settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: null },
776 });
777
778 yield* Effect.gen(function* () {
779 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
780 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
781 expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
782 thread.id,
783 ]);
784 }).pipe(Effect.provide(fixture.layer));
785 }),
786 ),
787 );
788
789 it.effect("settles an idle thread with an open persisted link on the inactivity sweep", () =>
790 Effect.scoped(
791 Effect.gen(function* () {
792 yield* TestClock.setTime(Date.parse(NOW));
793 const thread = makeThread("open-link", {
794 pullRequests: [persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z"))],
795 });
796 const fixture = yield* makeHarness({
797 snapshot: makeSnapshot([thread]),
798 settings: {
799 ...DEFAULT_SERVER_SETTINGS,
800 sidebarAutoSettleAfterDays: 3,
801 sidebarAutoSettleKeepPullRequests: false,
802 },
803 });
804 yield* Effect.gen(function* () {
805 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
806 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
807 expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
808 thread.id,
809 ]);
810 }).pipe(Effect.provide(fixture.layer));
811 }),
812 ),
813 );
814
815 it.effect("settles only the project opted in while environment settlement is disabled", () =>
816 Effect.scoped(
817 Effect.gen(function* () {
818 yield* TestClock.setTime(Date.parse(NOW));
819 const thread = makeThread("project-opt-in", {
820 latestRunCompletedAt: DateTime.makeUnsafe("2026-08-25T00:00:00.000Z"),
821 });
822 const other = makeThread("environment-off", { projectId: ProjectId.make("other-project") });
823 const fixture = yield* makeHarness({
824 snapshot: makeSnapshot([thread, other]),
825 settings: {
826 ...DEFAULT_SERVER_SETTINGS,
827 sidebarAutoSettleAfterDays: null,
828 sidebarAutoSettleOnMerge: false,
829 projectSettingsOverrides: { [PROJECT_ID]: { sidebarAutoSettleAfterDays: 2 } },
830 },
831 });
832 yield* Effect.gen(function* () {
833 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
834 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
835 const commands = yield* Ref.get(fixture.commands);
836 expect(commands.map((command) => command.threadId)).toEqual([thread.id]);
837 }).pipe(Effect.provide(fixture.layer));
838 }),
839 ),
840 );
841
842 it.effect("reevaluates immediately after a pull request merge", () =>
843 Effect.scoped(
844 Effect.gen(function* () {
845 yield* TestClock.setTime(Date.parse(NOW));
846 const periodicLookupStarted = yield* Deferred.make<void>();
847 const releasePeriodicLookup = yield* Deferred.make<void>();
848 const mergedThreadSettled = yield* Deferred.make<void>();
849 const branchLookupCount = yield* Ref.make(0);
850 const fixture = yield* makeHarness({
851 snapshot: makeSnapshot([
852 makeThread("merged-in-app", {
853 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
854 linkedPullRequest: {
855 projectId: PROJECT_ID,
856 repository: "Owner/Repository",
857 number: 42,
858 url: "https://example.test/owner/repository/pull/42",
859 },
860 }),
861 makeThread("slow-periodic-lookup", {
862 branch: "another-feature",
863 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
864 }),
865 ]),
866 branchPullRequest: () =>
867 Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
868 Effect.flatMap((count) =>
869 count === 1
870 ? Effect.succeed(makeBranchPullRequest("open"))
871 : Deferred.succeed(periodicLookupStarted, undefined).pipe(
872 Effect.andThen(Deferred.await(releasePeriodicLookup)),
873 Effect.as(makeBranchPullRequest("open")),
874 ),
875 ),
876 ),
877 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
878 });
879
880 yield* Effect.gen(function* () {
881 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
882 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
883 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
884 yield* Deferred.await(periodicLookupStarted);
885
886 yield* fixture.publishMerge;
887 yield* Deferred.await(mergedThreadSettled);
888
889 assert.deepStrictEqual(
890 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
891 [ThreadId.make("merged-in-app")],
892 );
893 yield* Deferred.succeed(releasePeriodicLookup, undefined);
894 yield* reactor.drain;
895 }).pipe(Effect.provide(fixture.layer));
896 }),
897 ),
898 );
899
900 it.effect("settles a merged thread when its background work ends, during a slow full sweep", () =>
901 Effect.scoped(
902 Effect.gen(function* () {
903 yield* TestClock.setTime(Date.parse(NOW));
904 const periodicLookupStarted = yield* Deferred.make<void>();
905 const releasePeriodicLookup = yield* Deferred.make<void>();
906 const settled = yield* Deferred.make<void>();
907 const branchLookupCount = yield* Ref.make(0);
908 const mergedLink: NonNullable<SettlementShell["pullRequests"]>[number] = {
909 ...persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z")),
910 snapshot: {
911 state: "merged",
912 title: "Pull request",
913 headBranch: "feature",
914 baseBranch: "main",
915 isDraft: false,
916 updatedAt: NOW,
917 syncedAt: NOW,
918 mergedAt: NOW,
919 },
920 };
921 const waiting = makeThread("waiting-on-subagent", {
922 pullRequests: [mergedLink],
923 pendingBackgroundTasks: [{ taskId: "child", kind: "subagent", description: "Review" }],
924 });
925 const slow = makeThread("slow-periodic-lookup", {
926 branch: "another-feature",
927 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
928 });
929 const fixture = yield* makeHarness({
930 snapshot: makeSnapshot([waiting, slow]),
931 branchPullRequest: () =>
932 Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
933 Effect.flatMap((count) =>
934 count === 1
935 ? Effect.succeed(makeBranchPullRequest("open"))
936 : Deferred.succeed(periodicLookupStarted, undefined).pipe(
937 Effect.andThen(Deferred.await(releasePeriodicLookup)),
938 Effect.as(makeBranchPullRequest("open")),
939 ),
940 ),
941 ),
942 onDispatch: () => Deferred.succeed(settled, undefined),
943 });
944
945 yield* Effect.gen(function* () {
946 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
947 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
948 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
949 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
950 yield* Deferred.await(periodicLookupStarted);
951
952 yield* Ref.set(
953 fixture.snapshots,
954 makeSnapshot([{ ...waiting, pendingBackgroundTasks: [] }, slow]),
955 );
956 yield* fixture.publishEvent({
957 type: "run.background-work-cancelled",
958 id: EventId.make("event:background-ended"),
959 threadId: waiting.id,
960 occurredAt: DateTime.makeUnsafe(NOW),
961 payload: { runId: RunId.make("run:waiting"), restartCancelledBackgroundWork: [] },
962 });
963 yield* Deferred.await(settled);
964
965 assert.deepStrictEqual(
966 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
967 [waiting.id],
968 );
969 yield* Deferred.succeed(releasePeriodicLookup, undefined);
970 yield* reactor.drain;
971 }).pipe(Effect.provide(fixture.layer));
972 }),
973 ),
974 );
975
976 it.effect("settles a stopped thread while another thread's lookup is slow", () =>
977 Effect.scoped(
978 Effect.gen(function* () {
979 yield* TestClock.setTime(Date.parse(NOW));
980 const slowLookupStarted = yield* Deferred.make<void>();
981 const releaseSlowLookup = yield* Deferred.make<void>();
982 const settled = yield* Deferred.make<void>();
983 const branchLookupCount = yield* Ref.make(0);
984 const recent = DateTime.makeUnsafe("2026-08-27T00:00:00.000Z");
985 const slow = makeThread("slow-lookup", { branch: "feature", latestUserMessageAt: recent });
986 const merged = makeThread("merged", {
987 latestUserMessageAt: recent,
988 pullRequests: [
989 {
990 ...persistedLink("open", recent),
991 snapshot: {
992 state: "merged",
993 title: "Pull request",
994 headBranch: "feature",
995 baseBranch: "main",
996 isDraft: false,
997 updatedAt: NOW,
998 syncedAt: NOW,
999 mergedAt: NOW,
1000 },
1001 },
1002 ],
1003 pendingBackgroundTasks: [{ taskId: "child", kind: "subagent", description: "Review" }],
1004 });
1005 const fixture = yield* makeHarness({
1006 snapshot: makeSnapshot([slow, merged]),
1007 branchPullRequest: () =>
1008 Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
1009 Effect.flatMap((count) =>
1010 count === 1
1011 ? Effect.succeed(makeBranchPullRequest("open"))
1012 : Deferred.succeed(slowLookupStarted, undefined).pipe(
1013 Effect.andThen(Deferred.await(releaseSlowLookup)),
1014 Effect.as(makeBranchPullRequest("open")),
1015 ),
1016 ),
1017 ),
1018 onDispatch: () => Deferred.succeed(settled, undefined),
1019 });
1020 const backgroundEnded = (threadId: ThreadId): OrchestrationV2DomainEvent => ({
1021 type: "run.background-work-cancelled",
1022 id: EventId.make(`event:background-ended:${threadId}`),
1023 threadId,
1024 occurredAt: DateTime.makeUnsafe(NOW),
1025 payload: { runId: RunId.make(`run:${threadId}`), restartCancelledBackgroundWork: [] },
1026 });
1027
1028 yield* Effect.gen(function* () {
1029 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1030 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1031 yield* fixture.publishEvent(backgroundEnded(slow.id));
1032 yield* Deferred.await(slowLookupStarted);
1033 // More events for the slow thread coalesce into one more pass, not more sweeps.
1034 for (let index = 0; index < 9; index++) {
1035 yield* fixture.publishEvent(backgroundEnded(slow.id));
1036 }
1037
1038 yield* Ref.set(
1039 fixture.snapshots,
1040 makeSnapshot([slow, { ...merged, pendingBackgroundTasks: [] }]),
1041 );
1042 yield* fixture.publishEvent(backgroundEnded(merged.id));
1043 yield* Deferred.await(settled);
1044
1045 assert.deepStrictEqual(
1046 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1047 [merged.id],
1048 );
1049 yield* Deferred.succeed(releaseSlowLookup, undefined);
1050 yield* reactor.drain;
1051 // The startup sweep, the first per-thread sweep, and one coalesced rerun.
1052 assert.strictEqual(yield* Ref.get(branchLookupCount), 3);
1053 }).pipe(Effect.provide(fixture.layer));
1054 }),
1055 ),
1056 );
1057
1058 it.effect("settles an unlinked branch thread its agent merged from a shell, past the cache", () =>
1059 Effect.scoped(
1060 Effect.gen(function* () {
1061 yield* TestClock.setTime(Date.parse(NOW));
1062 const settled = yield* Deferred.make<void>();
1063 const thread = makeThread("shell-merged", {
1064 branch: "saved-feature",
1065 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1066 });
1067 const fixture = yield* makeHarness({
1068 snapshot: makeSnapshot([thread]),
1069 // The host already merged it; only a fresh read sees that past the cached open lookup.
1070 branchPullRequest: (_input, lookupOptions) =>
1071 Effect.succeed(makeBranchPullRequest(lookupOptions?.refresh ? "merged" : "open")),
1072 onDispatch: () => Deferred.succeed(settled, undefined),
1073 });
1074 const at = DateTime.makeUnsafe(NOW);
1075 const runId = RunId.make("run:shell-merged");
1076 const runEnded: OrchestrationV2DomainEvent = {
1077 type: "run.background-work-cancelled",
1078 id: EventId.make("event:shell-merged:run-ended"),
1079 threadId: thread.id,
1080 occurredAt: at,
1081 payload: { runId, restartCancelledBackgroundWork: [] },
1082 };
1083
1084 yield* Effect.gen(function* () {
1085 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1086 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1087 yield* fixture.publishEvent(runEnded);
1088 yield* Queue.take(fixture.snapshotReads);
1089 yield* reactor.drain;
1090 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1091
1092 yield* fixture.publishEvent({
1093 type: "turn-item.updated",
1094 id: EventId.make("event:shell-merged:command"),
1095 threadId: thread.id,
1096 runId,
1097 occurredAt: at,
1098 payload: {
1099 id: TurnItemId.make("item:shell-merged:command"),
1100 threadId: thread.id,
1101 runId,
1102 nodeId: null,
1103 providerThreadId: null,
1104 providerTurnId: null,
1105 nativeItemRef: null,
1106 parentItemId: null,
1107 ordinal: 1,
1108 status: "completed",
1109 title: null,
1110 startedAt: at,
1111 completedAt: at,
1112 updatedAt: at,
1113 type: "command_execution",
1114 input: "gh pr merge 42 --squash",
1115 },
1116 });
1117 yield* Deferred.await(settled);
1118 assert.deepStrictEqual(
1119 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1120 [thread.id],
1121 );
1122 }).pipe(Effect.provide(fixture.layer));
1123 }),
1124 ),
1125 );
1126
1127 it.effect(
1128 "settles branch threads on a pull request merge without waiting for the next sweep",
1129 () =>
1130 Effect.scoped(
1131 Effect.gen(function* () {
1132 yield* TestClock.setTime(Date.parse(NOW));
1133 const state = yield* Ref.make<"open" | "merged">("open");
1134 const mergedThreadSettled = yield* Deferred.make<void>();
1135 const fixture = yield* makeHarness({
1136 snapshot: makeSnapshot([
1137 makeThread("branch-thread", {
1138 branch: "saved-feature",
1139 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1140 }),
1141 ]),
1142 branchPullRequest: () => Ref.get(state).pipe(Effect.map(makeBranchPullRequest)),
1143 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
1144 });
1145
1146 yield* Effect.gen(function* () {
1147 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1148 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1149 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1150 assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), []);
1151
1152 yield* Ref.set(state, "merged");
1153 yield* fixture.publishMerge;
1154 yield* Deferred.await(mergedThreadSettled);
1155
1156 assert.deepStrictEqual(
1157 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1158 [ThreadId.make("branch-thread")],
1159 );
1160 assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), ["/workspace/project"]);
1161 yield* reactor.drain;
1162 }).pipe(Effect.provide(fixture.layer));
1163 }),
1164 ),
1165 );
1166
1167 it.effect("a merge does not settle threads linked to an unrelated pull request", () =>
1168 Effect.scoped(
1169 Effect.gen(function* () {
1170 yield* TestClock.setTime(Date.parse(NOW));
1171 const mergedThreadSettled = yield* Deferred.make<void>();
1172 const mergeLookupStarted = yield* Deferred.make<void>();
1173 const releaseMergeLookup = yield* Deferred.make<void>();
1174 const lookupCount = yield* Ref.make(0);
1175 const fixture = yield* makeHarness({
1176 snapshot: makeSnapshot([
1177 makeThread("merged-in-app", {
1178 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1179 linkedPullRequest: {
1180 projectId: PROJECT_ID,
1181 repository: "owner/repository",
1182 number: 42,
1183 url: "https://example.test/owner/repository/pull/42",
1184 },
1185 }),
1186 makeThread("unrelated-linked", {
1187 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1188 linkedPullRequest: {
1189 projectId: PROJECT_ID,
1190 repository: "owner/repository",
1191 number: 99,
1192 url: "https://example.test/owner/repository/pull/99",
1193 },
1194 }),
1195 ]),
1196 pullRequestSummary: (input) =>
1197 Ref.updateAndGet(lookupCount, (count) => count + 1).pipe(
1198 Effect.tap((count) =>
1199 count === 3 ? Deferred.succeed(mergeLookupStarted, undefined) : Effect.void,
1200 ),
1201 Effect.tap((count) =>
1202 count === 3 ? Deferred.await(releaseMergeLookup) : Effect.void,
1203 ),
1204 Effect.map(() => makePullRequestSummary({ ...input, state: "open" })),
1205 ),
1206 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
1207 });
1208
1209 yield* Effect.gen(function* () {
1210 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1211 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1212 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1213
1214 yield* fixture.publishMerge;
1215 yield* Deferred.await(mergeLookupStarted);
1216 yield* Deferred.await(mergedThreadSettled);
1217 yield* Deferred.succeed(releaseMergeLookup, undefined);
1218 yield* reactor.drain;
1219
1220 assert.deepStrictEqual(
1221 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1222 [ThreadId.make("merged-in-app")],
1223 );
1224 assert.deepStrictEqual(
1225 (yield* Ref.get(fixture.summaryCalls))
1226 .map((call) => call.number)
1227 .toSorted((left, right) => left - right),
1228 [42, 99, 99],
1229 );
1230 }).pipe(Effect.provide(fixture.layer));
1231 }),
1232 ),
1233 );
1234});
1235
1236describe("ThreadSettlementServiceV2 terminals", () => {
1237 const appThread = (
1238 id: string,
1239 settledOverride: OrchestrationV2AppThread["settledOverride"],
1240 worktreePath: string | null = null,
1241 ): OrchestrationV2AppThread => {
1242 const threadId = ThreadId.make(id);
1243 return {
1244 createdBy: "user",
1245 creationSource: "web",
1246 id: threadId,
1247 projectId: PROJECT_ID,
1248 title: id,
1249 providerInstanceId: ProviderInstanceId.make("codex"),
1250 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
1251 runtimeMode: "full-access",
1252 interactionMode: "default",
1253 branch: null,
1254 worktreePath,
1255 activeProviderThreadId: null,
1256 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
1257 forkedFrom: null,
1258 createdAt: DateTime.makeUnsafe(NOW),
1259 updatedAt: DateTime.makeUnsafe(NOW),
1260 archivedAt: null,
1261 settledOverride,
1262 settledAt: settledOverride === "settled" ? DateTime.makeUnsafe(NOW) : null,
1263 lastVisitedAt: null,
1264 deletedAt: null,
1265 };
1266 };
1267 const settledEvent = (thread: OrchestrationV2AppThread): OrchestrationV2DomainEvent => ({
1268 type: "thread.settled",
1269 id: EventId.make(`event:settled:${thread.id}`),
1270 threadId: thread.id,
1271 occurredAt: DateTime.makeUnsafe(NOW),
1272 payload: thread,
1273 });
1274
1275 it.effect("keeps the terminals of a thread re-engaged before the event ran", () =>
1276 Effect.scoped(
1277 Effect.gen(function* () {
1278 const settled = appThread("reengaged-thread", "settled");
1279 const reengaged = appThread("reengaged-thread", "active");
1280 const marker = appThread("marker-thread", "settled");
1281 const fixture = yield* makeHarness({
1282 snapshot: makeSnapshot([]),
1283 currentThreads: [reengaged, marker],
1284 });
1285
1286 yield* Effect.gen(function* () {
1287 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1288 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1289 yield* fixture.publishEvent(settledEvent(settled));
1290 yield* fixture.publishEvent(settledEvent(marker));
1291 assert.deepStrictEqual(yield* Queue.take(fixture.closedIdle), { threadId: marker.id });
1292 }).pipe(Effect.provide(fixture.layer));
1293 }),
1294 ),
1295 );
1296
1297 it.effect("runs the settle script in the thread's own worktree", () =>
1298 Effect.scoped(
1299 Effect.gen(function* () {
1300 const shared = appThread("shared-checkout-thread", "settled");
1301 const missing = appThread("removed-worktree-thread", "settled", "/worktrees/removed");
1302 const worktree = appThread("worktree-thread", "settled", "/worktrees/thread");
1303 const fixture = yield* makeHarness({
1304 snapshot: makeSnapshot([]),
1305 currentThreads: [shared, missing, worktree],
1306 existingWorktreePaths: ["/worktrees/thread"],
1307 });
1308
1309 yield* Effect.gen(function* () {
1310 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1311 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1312 yield* fixture.publishEvent(settledEvent(shared));
1313 yield* fixture.publishEvent(settledEvent(missing));
1314 yield* fixture.publishEvent(settledEvent(worktree));
1315 const run = yield* Queue.take(fixture.scriptRuns);
1316 assert.strictEqual(run.threadId, worktree.id);
1317 assert.strictEqual(run.worktreePath, "/worktrees/thread");
1318 assert.strictEqual(run.trigger, "settle");
1319 }).pipe(Effect.provide(fixture.layer));
1320 }),
1321 ),
1322 );
1323
1324 it.effect("skips the settle script for a thread re-engaged while its shells close", () =>
1325 Effect.scoped(
1326 Effect.gen(function* () {
1327 const settled = appThread("reengaging-thread", "settled", "/worktrees/reengaging");
1328 const marker = appThread("marker-thread", "settled", "/worktrees/marker");
1329 const currentThreads = [settled, marker];
1330 const fixture = yield* makeHarness({
1331 snapshot: makeSnapshot([]),
1332 currentThreads,
1333 existingWorktreePaths: ["/worktrees/reengaging", "/worktrees/marker"],
1334 onCloseIdle: () =>
1335 Effect.sync(() => {
1336 currentThreads[0] = { ...settled, settledOverride: "active" };
1337 }),
1338 });
1339
1340 yield* Effect.gen(function* () {
1341 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1342 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1343 yield* fixture.publishEvent(settledEvent(settled));
1344 yield* fixture.publishEvent(settledEvent(marker));
1345 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, marker.id);
1346 }).pipe(Effect.provide(fixture.layer));
1347 }),
1348 ),
1349 );
1350
1351 it.effect("runs the settle script once when a settlement is re-emitted", () =>
1352 Effect.scoped(
1353 Effect.gen(function* () {
1354 const repeated = appThread("repeated-thread", "settled", "/worktrees/repeated");
1355 const marker = appThread("marker-thread", "settled", "/worktrees/marker");
1356 const fixture = yield* makeHarness({
1357 snapshot: makeSnapshot([]),
1358 currentThreads: [repeated, marker],
1359 existingWorktreePaths: ["/worktrees/repeated", "/worktrees/marker"],
1360 });
1361
1362 yield* Effect.gen(function* () {
1363 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1364 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1365 yield* fixture.publishEvent(settledEvent(repeated));
1366 yield* fixture.publishEvent(settledEvent(repeated));
1367 yield* fixture.publishEvent(settledEvent(marker));
1368 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, repeated.id);
1369 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, marker.id);
1370 }).pipe(Effect.provide(fixture.layer));
1371 }),
1372 ),
1373 );
1374
1375 it.effect("retries the settle script on a re-emitted settlement after a failed start", () =>
1376 Effect.scoped(
1377 Effect.gen(function* () {
1378 const thread = appThread("failed-start-thread", "settled", "/worktrees/failed-start");
1379 const starts = yield* Ref.make(0);
1380 const fixture = yield* makeHarness({
1381 snapshot: makeSnapshot([]),
1382 currentThreads: [thread],
1383 existingWorktreePaths: ["/worktrees/failed-start"],
1384 onScriptRun: () =>
1385 Ref.updateAndGet(starts, (count) => count + 1).pipe(
1386 Effect.flatMap((count) =>
1387 count === 1 ? Effect.die(new Error("terminal failed to open")) : Effect.void,
1388 ),
1389 ),
1390 });
1391
1392 yield* Effect.gen(function* () {
1393 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1394 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1395 yield* fixture.publishEvent(settledEvent(thread));
1396 yield* fixture.publishEvent(settledEvent(thread));
1397 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, thread.id);
1398 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, thread.id);
1399 }).pipe(Effect.provide(fixture.layer));
1400 }),
1401 ),
1402 );
1403});
1404
1405describe("isSnoozed", () => {
1406 const snoozed = { snoozedAt: at(-2 * DAY_MS), snoozedUntil: at(DAY_MS) };
1407 it("keeps a run requested and completed after snoozing parked until the timer", () => {
1408 const thread = shell({
1409 ...snoozed,
1410 status: "completed",
1411 latestRunRequestedAt: at(-2 * DAY_MS + 1),
1412 latestRunStartedAt: at(-DAY_MS - 1),
1413 latestRunCompletedAt: at(-DAY_MS),
1414 });
1415
1416 expect(ThreadSettlementService.isSnoozed(thread, NOW_MS)).toBe(true);
1417 expect(ThreadSettlementService.isAutoSettlementCandidate(thread, NOW_MS)).toBe(false);
1418 expect(
1419 ThreadSettlementService.resolveAutoSettlementAt({
1420 thread,
1421 pullRequest: { state: "merged", mergedAt: DateTime.formatIso(at(-1)) },
1422 nowMs: NOW_MS,
1423 autoSettleAfterDays: null,
1424 autoSettleOnMerge: true,
1425 }),
1426 ).toBeNull();
1427 });
1428});