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