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