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

ThreadSettlementService.test.ts

1,486 lines55.7 KB

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