The best way to control Claude Code, Codex and more from any computer or phone

main
ts 2,334 lines 89.2 KB
Raw
1 import { SourceControlProviderKind } from "@t3tools/contracts";
2 import { assert, describe, expect, it } from "@effect/vitest";
3 import * as DateTime from "effect/DateTime";
4 import {
5 DEFAULT_SERVER_SETTINGS,
6 ProjectId,
7 EventId,
8 ProviderInstanceId,
9 MessageId,
10 RuntimeRequestId,
11 RunId,
12 type OrchestrationV2Run,
13 ThreadId,
14 TurnItemId,
15 type OrchestrationProjectShell,
16 type OrchestrationV2AppThread,
17 type OrchestrationV2Command,
18 type OrchestrationV2DomainEvent,
19 type OrchestrationV2ShellSnapshot,
20 type OrchestrationV2ThreadShell,
21 type PullRequestSummary,
22 type ServerSettings as ContractServerSettings,
23 type ServerSettingsPatch,
24 } from "@t3tools/contracts";
25 import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
26 import * as SecureRandom from "effect/crypto/SecureRandom";
27 import * as Deferred from "effect/Deferred";
28 import * as Effect from "effect/Effect";
29 import * as FileSystem from "effect/FileSystem";
30 import * as Layer from "effect/Layer";
31 import * as Path from "effect/Path";
32 import * as PlatformError from "effect/PlatformError";
33 import * as PubSub from "effect/PubSub";
34 import * as Queue from "effect/Queue";
35 import * as Ref from "effect/Ref";
36 import * as Stream from "effect/Stream";
37 import { TestClock } from "effect/testing";
38
39 import * as GitManager from "../git/GitManager.ts";
40 import * as SqlitePersistence from "../persistence/Sqlite.ts";
41 import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
42 import * as PullRequestService from "../pullRequest/PullRequestService.ts";
43 import * as ServerActivation from "../serverActivation.ts";
44 import * as ServerSettings from "../serverSettings.ts";
45 import * as TerminalManager from "../terminal/Manager.ts";
46 import * as ProjectStore from "./ProjectStore.ts";
47 import * as Orchestrator from "./Orchestrator.ts";
48 import * as ProjectionStore from "./ProjectionStore.ts";
49 import * as ThreadSettlementService from "./ThreadSettlementService.ts";
50
51 const NOW_MS = Date.parse("2026-06-10T12:00:00.000Z");
52 const DAY_MS = 24 * 60 * 60 * 1_000;
53
54 function at(offsetMs: number): DateTime.Utc {
55 return DateTime.makeUnsafe(NOW_MS + offsetMs);
56 }
57
58 type SettlementShell = OrchestrationV2ThreadShell &
59 Pick<ProjectionStore.ProjectionSettlementCandidate, "latestUserAuthoredMessageAt">;
60
61 function shell(overrides: Partial<SettlementShell> = {}): SettlementShell {
62 return {
63 id: ThreadId.make("thread-1"),
64 projectId: ProjectId.make("project-1"),
65 title: "Thread",
66 providerInstanceId: ProviderInstanceId.make("codex"),
67 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
68 runtimeMode: "full-access",
69 interactionMode: "default",
70 worktreePath: null,
71 activeProviderThreadId: null,
72 lineage: {
73 rootThreadId: ThreadId.make("thread-1"),
74 parentThreadId: null,
75 relationshipToParent: null,
76 },
77 forkedFrom: null,
78 createdBy: "user",
79 creationSource: "web",
80 activeRunId: null,
81 latestVisibleMessage: null,
82 hasActionableProposedPlan: false,
83 itemCount: 0,
84 visibleItemCount: 0,
85 lastVisitedAt: null,
86 deletedAt: null,
87 branch: null,
88 linkedPullRequest: null,
89 status: "idle",
90 activityRunStatus: null,
91 pendingRuntimeRequest: null,
92 pendingBackgroundTasks: [],
93 latestRunId: null,
94 latestRunRequestedAt: null,
95 latestRunStartedAt: null,
96 latestRunCompletedAt: null,
97 latestUserMessageAt: null,
98 latestUserAuthoredMessageAt: overrides.latestUserMessageAt ?? null,
99 createdAt: at(-30 * DAY_MS),
100 updatedAt: at(-10 * DAY_MS),
101 archivedAt: null,
102 settledOverride: null,
103 settledAt: null,
104 snoozedUntil: null,
105 snoozedAt: null,
106 pinnedAt: null,
107 ...overrides,
108 };
109 }
110
111 function persistedLink(
112 state: "open" | null,
113 linkedAt: DateTime.Utc,
114 ): NonNullable<SettlementShell["pullRequests"]>[number] {
115 return {
116 host: "example.test",
117 repository: "owner/repository",
118 number: 42,
119 url: "https://example.test/owner/repository/pull/42",
120 source: "manual",
121 linkedAt: DateTime.formatIso(linkedAt),
122 snapshot:
123 state === null
124 ? null
125 : {
126 state,
127 title: "Pull request",
128 headBranch: "feature",
129 baseBranch: "main",
130 isDraft: false,
131 updatedAt: DateTime.formatIso(linkedAt),
132 syncedAt: DateTime.formatIso(linkedAt),
133 },
134 stack: null,
135 };
136 }
137
138 describe("isAutoSettlementCandidate", () => {
139 it("settles a thread whose only background work is a command left running", () => {
140 expect(
141 ThreadSettlementService.isAutoSettlementCandidate(
142 shell({
143 pendingBackgroundTasks: [
144 { taskId: "dev", kind: "command", description: "vp run dev --share" },
145 ],
146 }),
147 NOW_MS,
148 ),
149 ).toBe(true);
150 // A pull request watch whose checks finished holds nothing, yet still keeps the thread.
151 expect(
152 ThreadSettlementService.isAutoSettlementCandidate(
153 shell({
154 pendingBackgroundTasks: [
155 { taskId: "pull-request-watch:github.com/acme/app#1", kind: "monitor" },
156 ],
157 }),
158 NOW_MS,
159 ),
160 ).toBe(false);
161 });
162
163 it("never settles, or keeps snoozed, a thread whose guest is waiting on the owner", () => {
164 expect(
165 ThreadSettlementService.isAutoSettlementCandidate(
166 shell({ pendingGuestMessageCount: 1 }),
167 NOW_MS,
168 ),
169 ).toBe(false);
170 const snoozed = shell({
171 snoozedUntil: at(60 * 60 * 1_000),
172 snoozedAt: at(-60 * 60 * 1_000),
173 pendingGuestMessageCount: 1,
174 });
175 expect(ThreadSettlementService.isSnoozed(snoozed, NOW_MS)).toBe(false);
176 });
177
178 it("keeps snoozed threads parked until a fresh failure or timer wake", () => {
179 const snoozed = shell({
180 snoozedUntil: at(60 * 60 * 1_000),
181 snoozedAt: at(-60 * 60 * 1_000),
182 });
183 expect(ThreadSettlementService.isAutoSettlementCandidate(snoozed, NOW_MS)).toBe(false);
184 expect(
185 ThreadSettlementService.isAutoSettlementCandidate(
186 shell({ ...snoozed, status: "failed", latestRunCompletedAt: at(-30 * 60 * 1_000) }),
187 NOW_MS,
188 ),
189 ).toBe(true);
190 expect(
191 ThreadSettlementService.isAutoSettlementCandidate(
192 shell({ ...snoozed, status: "failed", latestRunCompletedAt: at(-2 * 60 * 60 * 1_000) }),
193 NOW_MS,
194 ),
195 ).toBe(false);
196 expect(
197 ThreadSettlementService.isAutoSettlementCandidate(
198 shell({ ...snoozed, status: "failed", latestRunCompletedAt: snoozed.snoozedAt }),
199 NOW_MS,
200 ),
201 ).toBe(false);
202 expect(
203 ThreadSettlementService.isAutoSettlementCandidate(
204 shell({ ...snoozed, status: "failed", latestRunCompletedAt: null }),
205 NOW_MS,
206 ),
207 ).toBe(false);
208 expect(
209 ThreadSettlementService.isAutoSettlementCandidate(
210 shell({ ...snoozed, snoozedUntil: at(-1) }),
211 NOW_MS,
212 ),
213 ).toBe(true);
214 });
215 });
216
217 describe("resolveAutoSettlementAt", () => {
218 it("keeps threads with a PR from inactivity settlement only when asked", () => {
219 const input = {
220 thread: shell({
221 latestUserMessageAt: at(-4 * DAY_MS),
222 linkedPullRequest: {
223 projectId: ProjectId.make("project-1"),
224 repository: "owner/repo",
225 number: 1,
226 url: "https://example.test/owner/repo/pull/1",
227 },
228 }),
229 pullRequest: null,
230 nowMs: NOW_MS,
231 autoSettleAfterDays: 3,
232 autoSettleOnMerge: true,
233 autoSettleKeepPullRequests: true,
234 };
235 expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toBeNull();
236 expect(
237 ThreadSettlementService.resolveAutoSettlementAt({
238 ...input,
239 autoSettleKeepPullRequests: false,
240 }),
241 ).toEqual(at(-4 * DAY_MS));
242 expect(
243 ThreadSettlementService.resolveAutoSettlementAt({
244 ...input,
245 pullRequest: { state: "merged", mergedAt: DateTime.formatIso(at(-1)) },
246 }),
247 ).toEqual(at(-4 * DAY_MS));
248 });
249
250 it("settles an idle thread with an open persisted link only while retention is off", () => {
251 const input = {
252 thread: shell({
253 latestUserMessageAt: at(-4 * DAY_MS),
254 pullRequests: [persistedLink("open", at(-5 * DAY_MS))],
255 }),
256 pullRequest: null,
257 nowMs: NOW_MS,
258 autoSettleAfterDays: 3,
259 autoSettleOnMerge: true,
260 autoSettleKeepPullRequests: false,
261 };
262 expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toEqual(at(-4 * DAY_MS));
263 expect(
264 ThreadSettlementService.resolveAutoSettlementAt({
265 ...input,
266 autoSettleKeepPullRequests: true,
267 }),
268 ).toBeNull();
269 // The open link outranks a merged lookup, so only inactivity can settle it.
270 expect(
271 ThreadSettlementService.resolveAutoSettlementAt({
272 ...input,
273 pullRequest: { state: "merged", mergedAt: DateTime.formatIso(at(-1)) },
274 autoSettleAfterDays: null,
275 }),
276 ).toBeNull();
277 });
278
279 it("keeps an idle thread whose persisted link was never synced", () => {
280 expect(
281 ThreadSettlementService.resolveAutoSettlementAt({
282 thread: shell({
283 latestUserMessageAt: at(-4 * DAY_MS),
284 pullRequests: [persistedLink(null, at(-5 * DAY_MS))],
285 }),
286 pullRequest: null,
287 nowMs: NOW_MS,
288 autoSettleAfterDays: 3,
289 autoSettleOnMerge: true,
290 autoSettleKeepPullRequests: false,
291 }),
292 ).toBeNull();
293 });
294
295 it("uses the latest activity time when the inactivity window elapses", () => {
296 const idle = shell({
297 latestUserMessageAt: at(-4 * DAY_MS),
298 latestRunRequestedAt: at(-4 * DAY_MS),
299 latestRunStartedAt: at(-4 * DAY_MS),
300 latestRunCompletedAt: at(-3 * DAY_MS),
301 });
302 const input = {
303 thread: idle,
304 pullRequest: null,
305 nowMs: NOW_MS,
306 autoSettleAfterDays: 2,
307 autoSettleOnMerge: true,
308 };
309 expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toEqual(at(-3 * DAY_MS));
310 expect(
311 ThreadSettlementService.resolveAutoSettlementAt({ ...input, autoSettleAfterDays: 5 }),
312 ).toBeNull();
313 expect(
314 ThreadSettlementService.resolveAutoSettlementAt({ ...input, autoSettleAfterDays: null }),
315 ).toBeNull();
316 });
317
318 it("anchors an empty thread's inactivity at its creation time", () => {
319 const input = {
320 thread: shell({ createdAt: at(-3 * DAY_MS) }),
321 pullRequest: null,
322 nowMs: NOW_MS,
323 autoSettleAfterDays: 2,
324 autoSettleOnMerge: false,
325 };
326 expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toEqual(at(-3 * DAY_MS));
327 expect(
328 ThreadSettlementService.resolveAutoSettlementAt({
329 ...input,
330 thread: shell({ createdAt: at(-DAY_MS) }),
331 }),
332 ).toBeNull();
333 expect(
334 ThreadSettlementService.resolveAutoSettlementAt({
335 ...input,
336 thread: { ...input.thread, lastSnoozeWakeAt: at(-DAY_MS) },
337 }),
338 ).toBeNull();
339 });
340
341 it.each(["manual", "timer"])("restarts inactivity on a %s snooze wake", (wake) => {
342 const thread = {
343 ...shell({ latestRunCompletedAt: at(-4 * DAY_MS) }),
344 ...(wake === "manual"
345 ? { lastSnoozeWakeAt: at(-1_000) }
346 : { snoozedAt: at(-3 * DAY_MS), snoozedUntil: at(-1_000) }),
347 };
348 const input = {
349 thread,
350 pullRequest: null,
351 nowMs: NOW_MS,
352 autoSettleAfterDays: 1,
353 autoSettleOnMerge: false,
354 };
355 expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toBeNull();
356 expect(
357 ThreadSettlementService.resolveAutoSettlementAt({ ...input, nowMs: NOW_MS + DAY_MS }),
358 ).toEqual(at(-1_000));
359 });
360
361 it("settles on merge only after the user's last action and preserves the activity time", () => {
362 const thread = shell({
363 latestUserMessageAt: at(-2 * 60 * 60 * 1_000),
364 latestRunCompletedAt: at(-90 * 60 * 1_000),
365 });
366 const input = {
367 thread,
368 pullRequest: {
369 state: "merged" as const,
370 mergedAt: DateTime.formatIso(at(-60 * 60 * 1_000)),
371 },
372 nowMs: NOW_MS,
373 autoSettleAfterDays: null,
374 autoSettleOnMerge: true,
375 };
376 expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toEqual(at(-90 * 60 * 1_000));
377 expect(
378 ThreadSettlementService.resolveAutoSettlementAt({ ...input, autoSettleOnMerge: false }),
379 ).toBeNull();
380 expect(
381 ThreadSettlementService.resolveAutoSettlementAt({
382 ...input,
383 pullRequest: { state: "merged", mergedAt: DateTime.formatIso(at(-3 * 60 * 60 * 1_000)) },
384 }),
385 ).toBeNull();
386 expect(
387 ThreadSettlementService.resolveAutoSettlementAt({
388 ...input,
389 thread: shell(),
390 pullRequest: { state: "closed", closedAt: DateTime.formatIso(at(-1)) },
391 autoSettleOnMerge: false,
392 }),
393 ).toEqual(shell().createdAt);
394 });
395
396 it("settles on merge after agent-started runs, but not after the user writes again", () => {
397 const woken = shell({
398 latestUserMessageAt: at(-30 * 60 * 1_000),
399 latestUserAuthoredMessageAt: at(-2 * 60 * 60 * 1_000),
400 latestRunRequestedAt: at(-30 * 60 * 1_000),
401 latestRunCompletedAt: at(-29 * 60 * 1_000),
402 });
403 const input = {
404 thread: woken,
405 pullRequest: { state: "merged" as const, mergedAt: DateTime.formatIso(at(-60 * 60 * 1_000)) },
406 nowMs: NOW_MS,
407 autoSettleAfterDays: null,
408 autoSettleOnMerge: true,
409 };
410 expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toEqual(at(-29 * 60 * 1_000));
411 expect(
412 ThreadSettlementService.resolveAutoSettlementAt({
413 ...input,
414 thread: { ...woken, latestUserAuthoredMessageAt: at(-30 * 60 * 1_000) },
415 }),
416 ).toBeNull();
417 });
418
419 it("does not settle on pull requests that were already merged when linked", () => {
420 const link = (number: number, linkedAt: DateTime.Utc, mergedAt: DateTime.Utc) => ({
421 host: "example.test",
422 repository: "owner/repository",
423 number,
424 url: `https://example.test/owner/repository/pull/${number}`,
425 source: "agent" as const,
426 linkedAt: DateTime.formatIso(linkedAt),
427 snapshot: {
428 state: "merged" as const,
429 title: "Pull request",
430 headBranch: `feature-${number}`,
431 baseBranch: "main",
432 isDraft: false,
433 updatedAt: DateTime.formatIso(mergedAt),
434 syncedAt: DateTime.formatIso(linkedAt),
435 mergedAt: DateTime.formatIso(mergedAt),
436 },
437 stack: null,
438 });
439 const recorded = link(1, at(-50 * 60 * 1_000), at(-55 * 60 * 1_000));
440 const input = {
441 thread: shell({
442 latestUserMessageAt: at(-2 * 60 * 60 * 1_000),
443 latestRunCompletedAt: at(-45 * 60 * 1_000),
444 pullRequests: [recorded],
445 }),
446 pullRequest: null,
447 nowMs: NOW_MS,
448 autoSettleAfterDays: null,
449 autoSettleOnMerge: true,
450 };
451 expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toBeNull();
452 expect(
453 ThreadSettlementService.resolveAutoSettlementAt({
454 ...input,
455 thread: {
456 ...input.thread,
457 pullRequests: [recorded, link(2, at(-90 * 60 * 1_000), at(-40 * 60 * 1_000))],
458 },
459 }),
460 ).toEqual(at(-45 * 60 * 1_000));
461 });
462 });
463
464 const NOW = "2026-08-28T12:00:00.000Z";
465 const PROJECT_ID = ProjectId.make("settlement-project");
466
467 describe("autoSettlementSettingsKey", () => {
468 it("distinguishes a project that inherits the threshold from one that disables it", () => {
469 const inherits = ThreadSettlementService.autoSettlementSettingsKey({
470 ...DEFAULT_SERVER_SETTINGS,
471 projectSettingsOverrides: { [PROJECT_ID]: { sidebarAutoSettleOnMerge: true } },
472 });
473 const never = ThreadSettlementService.autoSettlementSettingsKey({
474 ...DEFAULT_SERVER_SETTINGS,
475 projectSettingsOverrides: {
476 [PROJECT_ID]: { sidebarAutoSettleOnMerge: true, sidebarAutoSettleAfterDays: null },
477 },
478 });
479 assert.notStrictEqual(inherits, never);
480 });
481 });
482
483 type AutoSettleCommand = Extract<OrchestrationV2Command, { readonly type: "thread.auto-settle" }>;
484
485 const testCrypto = SecureRandom.make((size) => new Uint8Array(size).fill(1));
486
487 function makeProject(
488 id: ProjectId = PROJECT_ID,
489 workspaceRoot = "/workspace/project",
490 ): OrchestrationProjectShell {
491 return {
492 id,
493 title: `Project ${id}`,
494 workspaceRoot,
495 defaultModelSelection: null,
496 scripts: [],
497 createdAt: "2026-08-01T00:00:00.000Z",
498 updatedAt: NOW,
499 };
500 }
501
502 function makeThread(id: string, overrides: Partial<SettlementShell> = {}): SettlementShell {
503 return shell({
504 id: ThreadId.make(id),
505 projectId: PROJECT_ID,
506 title: id,
507 createdAt: DateTime.makeUnsafe("2026-08-01T00:00:00.000Z"),
508 updatedAt: DateTime.makeUnsafe("2026-08-20T00:00:00.000Z"),
509 latestUserMessageAt: DateTime.makeUnsafe("2026-08-20T00:00:00.000Z"),
510 ...overrides,
511 });
512 }
513
514 type SettlementSnapshot = Omit<OrchestrationV2ShellSnapshot, "threads"> & {
515 readonly threads: ReadonlyArray<SettlementShell>;
516 };
517
518 function makeSnapshot(
519 threads: ReadonlyArray<SettlementShell>,
520 projects: ReadonlyArray<OrchestrationProjectShell> = [makeProject()],
521 ): SettlementSnapshot {
522 return {
523 schemaVersion: 1,
524 snapshotSequence: 1,
525 projects,
526 threads,
527 archivedThreads: [],
528 };
529 }
530
531 function makePullRequestSummary(input: {
532 readonly projectId: ProjectId;
533 readonly repository: string;
534 readonly number: number;
535 readonly state: "open" | "closed" | "merged";
536 readonly updatedAt?: string;
537 }): PullRequestSummary {
538 return {
539 provider: SourceControlProviderKind.make("github"),
540 projectId: input.projectId,
541 repository: input.repository,
542 number: input.number,
543 title: "Pull request",
544 url: `https://example.test/${input.repository}/pull/${input.number}`,
545 state: input.state,
546 headBranch: "feature",
547 baseBranch: "main",
548 updatedAt: input.updatedAt ?? NOW,
549 };
550 }
551
552 function makeBranchPullRequest(state: "open" | "closed" | "merged") {
553 return {
554 number: 42,
555 title: "Pull request",
556 url: "https://example.test/owner/repository/pull/42",
557 baseRef: "main",
558 headRef: "feature",
559 state,
560 repositoryKey: "example.test/owner/repository",
561 updatedAt: NOW,
562 closedAt: state === "closed" ? NOW : null,
563 mergedAt: state === "merged" ? NOW : null,
564 } satisfies GitManager.GitBranchPullRequest;
565 }
566
567 // GitManager rereads git state on request, and by default whenever its
568 // remembered answer is merged or closed.
569 function readsFreshGitState(
570 options: Parameters<GitManager.GitManager["Service"]["branchPullRequest"]>[1],
571 ): boolean {
572 return (
573 options?.refresh === true ||
574 options?.freshGitState === true ||
575 options?.confirmTerminal !== false
576 );
577 }
578
579 interface HarnessOptions {
580 readonly snapshot: SettlementSnapshot;
581 readonly settings?: ContractServerSettings;
582 readonly branchPullRequest?: GitManager.GitManager["Service"]["branchPullRequest"];
583 readonly pullRequestSummary?: PullRequestService.PullRequestService["Service"]["summary"];
584 readonly existingWorktreePaths?: ReadonlyArray<string>;
585 readonly unreadablePaths?: ReadonlyArray<string>;
586 readonly onDispatch?: (command: AutoSettleCommand) => Effect.Effect<void>;
587 readonly onScriptRun?: (
588 input: ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput,
589 ) => Effect.Effect<void>;
590 readonly onCloseIdle?: () => Effect.Effect<void>;
591 readonly hasActiveSubprocess?: (input: { readonly threadId: string }) => Effect.Effect<boolean>;
592 readonly currentThreads?: ReadonlyArray<OrchestrationV2AppThread>;
593 readonly projections?: ProjectionStore.ProjectionStoreV2Shape;
594 }
595
596 const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: HarnessOptions) {
597 const activation = yield* Deferred.make<void>();
598 const snapshots = yield* Ref.make(options.snapshot);
599 const snapshotReadCount = yield* Ref.make(0);
600 const snapshotReads = yield* Queue.unbounded<number>();
601 const candidateReads = yield* Ref.make<ReadonlyArray<string | undefined>>([]);
602 const settings = yield* Ref.make(options.settings ?? DEFAULT_SERVER_SETTINGS);
603 const settingsReadCount = yield* Ref.make(0);
604 const settingsChanges = yield* PubSub.unbounded<ContractServerSettings>();
605 const mergedPullRequests = yield* PubSub.unbounded<PullRequestService.PullRequestMergeEvent>();
606 const pullRequestRefreshes = yield* PubSub.unbounded<number>();
607 const commands = yield* Ref.make<ReadonlyArray<AutoSettleCommand>>([]);
608 const branchCalls = yield* Ref.make<
609 ReadonlyArray<{ readonly cwd: string; readonly branch: string }>
610 >([]);
611 const summaryCalls = yield* Ref.make<
612 ReadonlyArray<{
613 readonly projectId: ProjectId;
614 readonly repository: string;
615 readonly number: number;
616 }>
617 >([]);
618 const summaryRecovery = yield* Ref.make<ReadonlyArray<boolean | undefined>>([]);
619 const invalidatedCwds = yield* Ref.make<ReadonlyArray<string>>([]);
620 const domainEvents = yield* PubSub.unbounded<OrchestrationV2DomainEvent>();
621 const observedEvents = yield* Queue.unbounded<EventId>();
622 const closedIdle = yield* Queue.unbounded<{ readonly threadId: string }>();
623 const scriptRuns =
624 yield* Queue.unbounded<ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput>();
625
626 const updateSettings = (patch: ServerSettingsPatch) =>
627 Effect.gen(function* () {
628 const next = applyServerSettingsPatch(yield* Ref.get(settings), patch);
629 yield* Ref.set(settings, next);
630 yield* PubSub.publish(settingsChanges, next);
631 return next;
632 });
633
634 const branchPullRequest: GitManager.GitManager["Service"]["branchPullRequest"] = (
635 input,
636 lookupOptions,
637 ) =>
638 Ref.update(branchCalls, (calls) => [...calls, input]).pipe(
639 Effect.andThen(options.branchPullRequest?.(input, lookupOptions) ?? Effect.succeed(null)),
640 );
641 const pullRequestSummary: PullRequestService.PullRequestService["Service"]["summary"] = (
642 input,
643 readOptions,
644 ) =>
645 Effect.gen(function* () {
646 yield* Ref.update(summaryCalls, (calls) => [...calls, input]);
647 yield* Ref.update(summaryRecovery, (values) => [
648 ...values,
649 readOptions?.recoverTransientFailure,
650 ]);
651 return yield* (
652 options.pullRequestSummary?.(input, readOptions) ??
653 Effect.succeed(
654 makePullRequestSummary({
655 ...input,
656 state: "open",
657 }),
658 )
659 );
660 });
661
662 const dispatch: Orchestrator.OrchestratorV2Shape["dispatch"] = (command) => {
663 if (command.type !== "thread.auto-settle") {
664 return Effect.die(new Error(`Unexpected command: ${command.type}`));
665 }
666 return Ref.update(commands, (recorded) => [...recorded, command]).pipe(
667 Effect.andThen(options.onDispatch?.(command) ?? Effect.void),
668 Effect.as({ sequence: 1, storedEvents: [] }),
669 );
670 };
671
672 const serverSettings = ServerSettings.ServerSettingsService.of({
673 start: Effect.void,
674 ready: Effect.void,
675 getSettings: Ref.update(settingsReadCount, (count) => count + 1).pipe(
676 Effect.andThen(Ref.get(settings)),
677 ),
678 updateSettings,
679 updateProviderInstance: () => Effect.die("Unexpected provider mutation"),
680 withSettingsSnapshot: (use) => Ref.get(settings).pipe(Effect.flatMap(use)),
681 streamChanges: Stream.fromPubSub(settingsChanges),
682 subscribeChanges: PubSub.subscribe(settingsChanges).pipe(
683 Effect.map((subscription) => Stream.fromSubscription(subscription)),
684 ),
685 });
686
687 const layerDependencies = Layer.mergeAll(
688 Layer.mock(ProjectStore.ProjectStoreV2)({
689 listShells: () => Ref.get(snapshots).pipe(Effect.map((snapshot) => snapshot.projects)),
690 }),
691 Layer.mock(ProjectionStore.ProjectionStoreV2)({
692 ...options.projections,
693 getSettlementCandidates: (threadId) =>
694 Ref.update(candidateReads, (reads) => [...reads, threadId]).pipe(
695 Effect.andThen(Ref.updateAndGet(snapshotReadCount, (count) => count + 1)),
696 Effect.tap((count) => Queue.offer(snapshotReads, count)),
697 Effect.andThen(
698 options.projections?.getSettlementCandidates(threadId) ??
699 Ref.get(snapshots).pipe(
700 Effect.map((snapshot) =>
701 threadId === undefined
702 ? snapshot.threads
703 : snapshot.threads.filter((thread) => thread.id === threadId),
704 ),
705 ),
706 ),
707 ),
708 getThread: (threadId) => {
709 if (options.projections) return options.projections.getThread(threadId);
710 const thread = options.currentThreads?.find((candidate) => candidate.id === threadId);
711 return thread
712 ? Effect.succeed(thread)
713 : Effect.die(new Error(`Unexpected thread read: ${threadId}`));
714 },
715 }),
716 Layer.mock(Orchestrator.OrchestratorV2)({
717 streamDomainEvents: Stream.fromPubSub(domainEvents).pipe(
718 Stream.tap((event) => Queue.offer(observedEvents, event.id)),
719 ),
720 dispatch,
721 }),
722 Layer.mock(TerminalManager.TerminalManager)({
723 closeOnSettle: (input) =>
724 Queue.offer(closedIdle, input).pipe(Effect.andThen(options.onCloseIdle?.() ?? Effect.void)),
725 hasActiveSubprocess: (input) => options.hasActiveSubprocess?.(input) ?? Effect.succeed(false),
726 }),
727 Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({
728 runForThread: (input) =>
729 Queue.offer(scriptRuns, input).pipe(
730 Effect.andThen(options.onScriptRun?.(input) ?? Effect.void),
731 Effect.as({ status: "no-script" } as const),
732 ),
733 }),
734 Layer.mock(GitManager.GitManager)({
735 branchPullRequest,
736 invalidateStatus: (cwd) => Ref.update(invalidatedCwds, (cwds) => [...cwds, cwd]),
737 }),
738 Layer.mock(PullRequestService.PullRequestService)({
739 summary: pullRequestSummary,
740 subscribeMerges: PubSub.subscribe(mergedPullRequests).pipe(
741 Effect.map((subscription) => Stream.fromSubscription(subscription)),
742 ),
743 subscribeRefreshes: Stream.fromPubSub(pullRequestRefreshes),
744 }),
745 Layer.succeed(ServerSettings.ServerSettingsService, serverSettings),
746 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
747 Layer.succeed(SecureRandom.SecureRandom, testCrypto),
748 FileSystem.layerNoop({
749 exists: (path) =>
750 options.unreadablePaths?.includes(path)
751 ? Effect.fail(
752 PlatformError.systemError({
753 _tag: "PermissionDenied",
754 module: "FileSystem",
755 method: "exists",
756 pathOrDescriptor: path,
757 }),
758 )
759 : Effect.succeed(options.existingWorktreePaths?.includes(path) ?? false),
760 }),
761 Path.layer,
762 );
763
764 return {
765 activation,
766 settings,
767 snapshots,
768 snapshotReadCount,
769 settingsReadCount,
770 snapshotReads,
771 candidateReads,
772 commands,
773 branchCalls,
774 summaryCalls,
775 summaryRecovery,
776 invalidatedCwds,
777 closedIdle,
778 scriptRuns,
779 observedEvents,
780 publishEvent: (event: OrchestrationV2DomainEvent) => PubSub.publish(domainEvents, event),
781 updateSettings,
782 publishRefresh: PubSub.publish(pullRequestRefreshes, 1),
783 publishMerge: PubSub.publish(mergedPullRequests, {
784 projectId: PROJECT_ID,
785 repository: "owner/repository",
786 number: 42,
787 mergedAt: NOW,
788 }),
789 layer: Layer.effect(
790 ThreadSettlementService.ThreadSettlementServiceV2,
791 ThreadSettlementService.make,
792 ).pipe(Layer.provide(layerDependencies)),
793 };
794 });
795
796 const startHarness = Effect.fn("startThreadSettlementHarness")(function* (
797 reactor: ThreadSettlementService.ThreadSettlementServiceV2["Service"],
798 activation: Deferred.Deferred<void>,
799 snapshotReads: Queue.Queue<number>,
800 ) {
801 yield* reactor.start();
802 yield* Deferred.succeed(activation, undefined);
803 yield* Queue.take(snapshotReads);
804 yield* reactor.drain;
805 });
806
807 const projectionStoreSql = ProjectionStore.layer.pipe(
808 Layer.provideMerge(SqlitePersistence.layerMemory),
809 );
810
811 const appThread = (
812 id: string,
813 settledOverride: OrchestrationV2AppThread["settledOverride"],
814 worktreePath: string | null = null,
815 ): OrchestrationV2AppThread => {
816 const threadId = ThreadId.make(id);
817 return {
818 createdBy: "user",
819 creationSource: "web",
820 id: threadId,
821 projectId: PROJECT_ID,
822 title: id,
823 providerInstanceId: ProviderInstanceId.make("codex"),
824 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
825 runtimeMode: "full-access",
826 interactionMode: "default",
827 branch: null,
828 worktreePath,
829 activeProviderThreadId: null,
830 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
831 forkedFrom: null,
832 createdAt: DateTime.makeUnsafe(NOW),
833 updatedAt: DateTime.makeUnsafe(NOW),
834 archivedAt: null,
835 settledOverride,
836 settledAt: settledOverride === "settled" ? DateTime.makeUnsafe(NOW) : null,
837 lastVisitedAt: null,
838 deletedAt: null,
839 };
840 };
841 const settledEvent = (thread: OrchestrationV2AppThread): OrchestrationV2DomainEvent => ({
842 type: "thread.settled",
843 id: EventId.make(`event:settled:${thread.id}`),
844 threadId: thread.id,
845 occurredAt: DateTime.makeUnsafe(NOW),
846 payload: thread,
847 });
848
849 describe("ThreadSettlementServiceV2 worker", () => {
850 it.effect("skips settings and PR decisions for recent branchless threads", () =>
851 Effect.gen(function* () {
852 yield* TestClock.setTime(Date.parse(NOW));
853 const threads = Array.from({ length: 32 }, (_, index) =>
854 makeThread(`recent-${index}`, {
855 updatedAt: DateTime.makeUnsafe(NOW),
856 latestUserMessageAt: DateTime.makeUnsafe(Date.parse(NOW) - 2 * DAY_MS),
857 }),
858 );
859 const fixture = yield* makeHarness({
860 snapshot: makeSnapshot(threads),
861 settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 3 },
862 });
863 yield* Effect.gen(function* () {
864 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
865 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
866 assert.deepEqual(yield* Ref.get(fixture.commands), []);
867 assert.deepEqual(yield* Ref.get(fixture.branchCalls), []);
868 assert.equal(yield* Ref.get(fixture.settingsReadCount), 2);
869 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 1 });
870 yield* Queue.take(fixture.snapshotReads);
871 yield* service.drain;
872 assert.deepEqual(
873 new Set((yield* Ref.get(fixture.commands)).map((command) => command.threadId)),
874 new Set(threads.map((thread) => thread.id)),
875 );
876 }).pipe(Effect.provide(fixture.layer));
877 }),
878 );
879 it.effect("settles a merged pull request stored only in the thread links", () =>
880 Effect.gen(function* () {
881 yield* TestClock.setTime(Date.parse(NOW));
882 const thread = makeThread("merged-link", {
883 pullRequests: [
884 {
885 host: "example.test",
886 repository: "owner/repository",
887 number: 42,
888 url: "https://example.test/owner/repository/pull/42",
889 source: "manual",
890 linkedAt: "2026-08-20T00:00:00.000Z",
891 snapshot: {
892 state: "merged",
893 title: "Pull request",
894 headBranch: "feature",
895 baseBranch: "main",
896 isDraft: false,
897 updatedAt: NOW,
898 syncedAt: NOW,
899 mergedAt: NOW,
900 },
901 stack: null,
902 },
903 ],
904 });
905 const fixture = yield* makeHarness({
906 snapshot: makeSnapshot([thread]),
907 settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: null },
908 });
909
910 yield* Effect.gen(function* () {
911 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
912 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
913 expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
914 thread.id,
915 ]);
916 }).pipe(Effect.provide(fixture.layer));
917 }),
918 );
919
920 it.effect("settles an idle thread with an open persisted link on the inactivity sweep", () =>
921 Effect.gen(function* () {
922 yield* TestClock.setTime(Date.parse(NOW));
923 const thread = makeThread("open-link", {
924 pullRequests: [persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z"))],
925 });
926 const fixture = yield* makeHarness({
927 snapshot: makeSnapshot([thread]),
928 settings: {
929 ...DEFAULT_SERVER_SETTINGS,
930 sidebarAutoSettleAfterDays: 3,
931 sidebarAutoSettleKeepPullRequests: false,
932 },
933 });
934 yield* Effect.gen(function* () {
935 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
936 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
937 expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
938 thread.id,
939 ]);
940 }).pipe(Effect.provide(fixture.layer));
941 }),
942 );
943
944 it.effect("does not auto-settle a thread whose terminal has an active subprocess", () =>
945 Effect.gen(function* () {
946 yield* TestClock.setTime(Date.parse(NOW));
947 const thread = makeThread("active-terminal");
948 const fixture = yield* makeHarness({
949 snapshot: makeSnapshot([thread]),
950 settings: {
951 ...DEFAULT_SERVER_SETTINGS,
952 sidebarAutoSettleAfterDays: 3,
953 },
954 hasActiveSubprocess: ({ threadId }) => Effect.succeed(threadId === thread.id),
955 });
956 yield* Effect.gen(function* () {
957 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
958 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
959 expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([]);
960 }).pipe(Effect.provide(fixture.layer));
961 }),
962 );
963
964 it.effect("settles only the project opted in while environment settlement is disabled", () =>
965 Effect.gen(function* () {
966 yield* TestClock.setTime(Date.parse(NOW));
967 const thread = makeThread("project-opt-in", {
968 latestRunCompletedAt: DateTime.makeUnsafe("2026-08-25T00:00:00.000Z"),
969 });
970 const other = makeThread("environment-off", { projectId: ProjectId.make("other-project") });
971 const fixture = yield* makeHarness({
972 snapshot: makeSnapshot([thread, other]),
973 settings: {
974 ...DEFAULT_SERVER_SETTINGS,
975 sidebarAutoSettleAfterDays: null,
976 sidebarAutoSettleOnMerge: false,
977 projectSettingsOverrides: { [PROJECT_ID]: { sidebarAutoSettleAfterDays: 2 } },
978 },
979 });
980 yield* Effect.gen(function* () {
981 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
982 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
983 const commands = yield* Ref.get(fixture.commands);
984 expect(commands.map((command) => command.threadId)).toEqual([thread.id]);
985 }).pipe(Effect.provide(fixture.layer));
986 }),
987 );
988
989 it.effect("stops settling the rest of a sweep once auto-settlement is turned off", () =>
990 Effect.gen(function* () {
991 yield* TestClock.setTime(Date.parse(NOW));
992 // Sweeps settle 8 threads at a time, so the ninth starts after a dispatch turned it off.
993 const threads = Array.from({ length: 9 }, (_, index) => makeThread(`idle-${index}`));
994 let disable: Effect.Effect<unknown> = Effect.void;
995 const fixture = yield* makeHarness({
996 snapshot: makeSnapshot(threads),
997 settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 3 },
998 onDispatch: () => disable,
999 });
1000 disable = fixture.updateSettings({ sidebarAutoSettleAfterDays: null });
1001 yield* Effect.gen(function* () {
1002 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1003 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1004 const settled = (yield* Ref.get(fixture.commands)).map((command) => command.threadId);
1005 expect(settled).not.toContain(threads[8]!.id);
1006 }).pipe(Effect.provide(fixture.layer));
1007 }),
1008 );
1009
1010 it.effect(
1011 "drains idle subagents of a settled parent and retries busy children without PR lookups",
1012 () =>
1013 Effect.gen(function* () {
1014 yield* TestClock.setTime(Date.parse(NOW));
1015 const store = yield* ProjectionStore.ProjectionStoreV2;
1016 const parent = appThread("subagent-parent", "settled");
1017 const child = (id: string, overrides: Partial<OrchestrationV2AppThread> = {}) => ({
1018 ...appThread(id, null),
1019 branch: "feature",
1020 lineage: {
1021 rootThreadId: parent.id,
1022 parentThreadId: parent.id,
1023 relationshipToParent: "subagent" as const,
1024 },
1025 ...overrides,
1026 });
1027 const empty = child("empty");
1028 const recent = child("recent");
1029 const busy = child("busy");
1030 const marker = appThread("marker", "settled");
1031 for (const thread of [
1032 parent,
1033 empty,
1034 recent,
1035 busy,
1036 marker,
1037 child("pinned", { pinnedAt: DateTime.makeUnsafe(NOW) }),
1038 child("opted-out", { autoSettleDisabledAt: DateTime.makeUnsafe(NOW) }),
1039 ]) {
1040 yield* store.apply({
1041 type: "thread.created",
1042 id: EventId.make(`created:${thread.id}`),
1043 threadId: thread.id,
1044 occurredAt: thread.createdAt,
1045 payload: thread,
1046 });
1047 }
1048 const run = (threadId: ThreadId, status: "running" | "completed"): OrchestrationV2Run => ({
1049 id: RunId.make(`run:${threadId}`),
1050 threadId,
1051 ordinal: 1,
1052 providerInstanceId: parent.providerInstanceId,
1053 modelSelection: parent.modelSelection,
1054 providerThreadId: null,
1055 userMessageId: MessageId.make(`message:${threadId}`),
1056 rootNodeId: null,
1057 activeAttemptId: null,
1058 status,
1059 requestedAt: DateTime.makeUnsafe(NOW),
1060 startedAt: DateTime.makeUnsafe(NOW),
1061 completedAt: status === "completed" ? DateTime.makeUnsafe(NOW) : null,
1062 checkpointId: null,
1063 contextHandoffId: null,
1064 });
1065 for (const payload of [run(recent.id, "completed"), run(busy.id, "running")]) {
1066 yield* store.apply({
1067 type: "run.created",
1068 id: EventId.make(`created:${payload.id}`),
1069 threadId: payload.threadId,
1070 occurredAt: DateTime.makeUnsafe(NOW),
1071 payload,
1072 });
1073 }
1074 const fixture = yield* makeHarness({
1075 snapshot: makeSnapshot([]),
1076 projections: store,
1077 settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 2 },
1078 onDispatch: (command) =>
1079 store.getThread(command.threadId).pipe(
1080 Effect.flatMap((thread) =>
1081 store.apply(
1082 settledEvent({
1083 ...thread,
1084 settledOverride: "settled",
1085 settledAt: DateTime.makeUnsafe(NOW),
1086 }),
1087 ),
1088 ),
1089 Effect.orDie,
1090 ),
1091 });
1092 yield* Effect.gen(function* () {
1093 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1094 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1095 const commands = yield* Ref.get(fixture.commands);
1096 expect(commands.map((command) => command.threadId).toSorted()).toEqual([
1097 empty.id,
1098 recent.id,
1099 ]);
1100 for (const command of commands) {
1101 expect(command.snapshotAt).toEqual(DateTime.makeUnsafe(NOW));
1102 expect(command.settledAt).toBeUndefined();
1103 }
1104 const finished: OrchestrationV2DomainEvent = {
1105 type: "run.updated",
1106 id: EventId.make("busy:completed"),
1107 threadId: busy.id,
1108 occurredAt: DateTime.makeUnsafe(NOW),
1109 payload: run(busy.id, "completed"),
1110 };
1111 yield* store.apply(finished);
1112 yield* fixture.publishEvent(finished);
1113 // Cleanup of the following event marks delivery of the run event before draining.
1114 yield* fixture.publishEvent(settledEvent(marker));
1115 expect(yield* Queue.take(fixture.closedIdle)).toEqual({ threadId: marker.id });
1116 yield* service.drain;
1117 expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
1118 empty.id,
1119 recent.id,
1120 busy.id,
1121 ]);
1122 expect(yield* Ref.get(fixture.branchCalls)).toEqual([]);
1123 expect(yield* Ref.get(fixture.summaryCalls)).toEqual([]);
1124 }).pipe(Effect.provide(fixture.layer));
1125 }).pipe(Effect.provide(projectionStoreSql)),
1126 );
1127
1128 it.effect(
1129 "manual parent settlement drains hidden children with automatic settlement disabled",
1130 () =>
1131 Effect.gen(function* () {
1132 yield* TestClock.setTime(Date.parse(NOW));
1133 const store = yield* ProjectionStore.ProjectionStoreV2;
1134 const parent = appThread("manual-parent", null);
1135 const child = {
1136 ...appThread("manual-child", null),
1137 branch: "feature",
1138 lineage: {
1139 rootThreadId: parent.id,
1140 parentThreadId: parent.id,
1141 relationshipToParent: "subagent" as const,
1142 },
1143 };
1144 const marker = appThread("marker", "settled");
1145 for (const thread of [parent, child, marker]) {
1146 yield* store.apply({
1147 type: "thread.created",
1148 id: EventId.make(`created:${thread.id}`),
1149 threadId: thread.id,
1150 occurredAt: thread.createdAt,
1151 payload: thread,
1152 });
1153 }
1154 const fixture = yield* makeHarness({
1155 snapshot: makeSnapshot([]),
1156 projections: store,
1157 settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 2 },
1158 onDispatch: (command) =>
1159 store.getThread(command.threadId).pipe(
1160 Effect.flatMap((thread) =>
1161 store.apply(
1162 settledEvent({
1163 ...thread,
1164 settledOverride: "settled",
1165 settledAt: DateTime.makeUnsafe(NOW),
1166 }),
1167 ),
1168 ),
1169 Effect.orDie,
1170 ),
1171 });
1172 yield* Effect.gen(function* () {
1173 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1174 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1175 expect(yield* Ref.get(fixture.commands)).toEqual([]);
1176 expect(yield* Ref.get(fixture.branchCalls)).toEqual([]);
1177 // Avoid a settings-change sweep: the parent event must trigger the child dispatch.
1178 yield* Ref.set(fixture.settings, {
1179 ...DEFAULT_SERVER_SETTINGS,
1180 sidebarAutoSettleAfterDays: null,
1181 sidebarAutoSettleOnMerge: false,
1182 });
1183 const event = settledEvent({
1184 ...parent,
1185 settledOverride: "settled",
1186 settledAt: DateTime.makeUnsafe(NOW),
1187 });
1188 yield* store.apply(event);
1189 yield* fixture.publishEvent(event);
1190 yield* fixture.publishEvent(settledEvent(marker));
1191 expect(yield* Queue.take(fixture.closedIdle)).toEqual({ threadId: parent.id });
1192 expect(yield* Queue.take(fixture.closedIdle)).toEqual({ threadId: marker.id });
1193 yield* service.drain;
1194 expect(yield* Ref.get(fixture.commands)).toEqual([
1195 expect.objectContaining({
1196 type: "thread.auto-settle",
1197 threadId: child.id,
1198 snapshotAt: child.updatedAt,
1199 }),
1200 ]);
1201 expect(yield* Ref.get(fixture.branchCalls)).toEqual([]);
1202 expect(yield* Ref.get(fixture.summaryCalls)).toEqual([]);
1203 }).pipe(Effect.provide(fixture.layer));
1204 }).pipe(Effect.provide(projectionStoreSql)),
1205 );
1206
1207 it.effect(
1208 "coalesces bulk cleanup wakes and still drains children discovered during a sweep",
1209 () =>
1210 Effect.gen(function* () {
1211 yield* TestClock.setTime(Date.parse(NOW));
1212 const store = yield* ProjectionStore.ProjectionStoreV2;
1213 const sweepStarted = yield* Deferred.make<void>();
1214 const releaseSweep = yield* Deferred.make<void>();
1215 const childSettled = yield* Deferred.make<void>();
1216 const parent = appThread("bulk-parent", null);
1217 const child = {
1218 ...appThread("bulk-child", null),
1219 lineage: {
1220 parentThreadId: parent.id,
1221 rootThreadId: parent.id,
1222 relationshipToParent: "subagent" as const,
1223 },
1224 };
1225 const marker = appThread("bulk-marker", "settled");
1226 const parents = [
1227 parent,
1228 ...Array.from({ length: 233 }, (_, i) => appThread(`bulk-parent-${i}`, null)),
1229 ];
1230 for (const thread of [...parents, child, marker]) {
1231 yield* store.apply({
1232 type: "thread.created",
1233 id: EventId.make(`created:${thread.id}`),
1234 threadId: thread.id,
1235 occurredAt: thread.createdAt,
1236 payload: thread,
1237 });
1238 }
1239 let blockNextSweep = false;
1240 const fixture = yield* makeHarness({
1241 snapshot: makeSnapshot([]),
1242 settings: {
1243 ...DEFAULT_SERVER_SETTINGS,
1244 sidebarAutoSettleAfterDays: null,
1245 sidebarAutoSettleOnMerge: false,
1246 },
1247 projections: {
1248 ...store,
1249 getSettlementCandidates: (threadId) =>
1250 Effect.gen(function* () {
1251 const candidates = yield* store.getSettlementCandidates(threadId);
1252 if (blockNextSweep) {
1253 blockNextSweep = false;
1254 yield* Deferred.succeed(sweepStarted, undefined);
1255 yield* Deferred.await(releaseSweep);
1256 }
1257 return candidates;
1258 }),
1259 },
1260 onDispatch: (command): Effect.Effect<void> =>
1261 Effect.gen(function* () {
1262 const thread = yield* store.getThread(command.threadId);
1263 const event = settledEvent({
1264 ...thread,
1265 settledOverride: "settled",
1266 settledAt: DateTime.makeUnsafe(NOW),
1267 });
1268 yield* store.apply(event);
1269 yield* fixture.publishEvent(event);
1270 yield* Deferred.succeed(childSettled, undefined);
1271 }).pipe(Effect.orDie),
1272 });
1273 yield* Effect.gen(function* () {
1274 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1275 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1276 yield* Ref.set(fixture.candidateReads, []);
1277 blockNextSweep = true;
1278 yield* fixture.publishEvent(settledEvent(marker));
1279 yield* Deferred.await(sweepStarted);
1280
1281 for (const [i, thread] of parents.entries()) {
1282 const type = (["thread.settled", "thread.archived", "thread.deleted"] as const)[i % 3]!;
1283 const event: OrchestrationV2DomainEvent = {
1284 type,
1285 id: EventId.make(`bulk:${thread.id}`),
1286 threadId: thread.id,
1287 occurredAt: DateTime.makeUnsafe(NOW),
1288 payload: {
1289 ...thread,
1290 ...(type === "thread.settled"
1291 ? { settledOverride: "settled" as const, settledAt: DateTime.makeUnsafe(NOW) }
1292 : type === "thread.archived"
1293 ? { archivedAt: DateTime.makeUnsafe(NOW) }
1294 : { deletedAt: DateTime.makeUnsafe(NOW) }),
1295 },
1296 };
1297 yield* store.apply(event);
1298 yield* fixture.publishEvent(event);
1299 }
1300 const markDelivery = (id: string) =>
1301 fixture
1302 .publishEvent({
1303 type: "thread.created",
1304 id: EventId.make(id),
1305 threadId: marker.id,
1306 occurredAt: marker.createdAt,
1307 payload: marker,
1308 })
1309 .pipe(
1310 // The next event is observed only after the previous handler has finished enqueueing.
1311 Effect.andThen(
1312 Queue.take(fixture.observedEvents).pipe(
1313 Effect.repeat({ until: (seen) => seen === id }),
1314 ),
1315 ),
1316 );
1317 yield* markDelivery("bulk-delivered");
1318 yield* Deferred.succeed(releaseSweep, undefined);
1319 yield* Deferred.await(childSettled);
1320 yield* markDelivery("child-delivered");
1321 yield* service.drain;
1322
1323 expect(yield* Ref.get(fixture.candidateReads)).toEqual([undefined, undefined, undefined]);
1324 expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
1325 child.id,
1326 ]);
1327 expect((yield* store.getThread(child.id)).settledOverride).toBe("settled");
1328 expect(yield* Ref.get(fixture.branchCalls)).toEqual([]);
1329 expect(yield* Ref.get(fixture.summaryCalls)).toEqual([]);
1330 }).pipe(Effect.provide(fixture.layer));
1331 }).pipe(Effect.provide(projectionStoreSql)),
1332 );
1333
1334 it.effect("looks up a branch in its worktree only while the worktree has .git", () =>
1335 Effect.gen(function* () {
1336 yield* TestClock.setTime(Date.parse(NOW));
1337 const fixture = yield* makeHarness({
1338 snapshot: makeSnapshot([
1339 makeThread("linked-worktree", {
1340 branch: "linked",
1341 worktreePath: "/worktrees/linked",
1342 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1343 }),
1344 // A folder that outlived its .git makes git fail with not_a_repository.
1345 makeThread("emptied-worktree", {
1346 branch: "emptied",
1347 worktreePath: "/worktrees/emptied",
1348 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1349 }),
1350 ]),
1351 existingWorktreePaths: [
1352 "/worktrees/linked",
1353 "/worktrees/linked/.git",
1354 "/worktrees/emptied",
1355 ],
1356 });
1357
1358 yield* Effect.gen(function* () {
1359 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1360 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1361 const cwdByBranch = Object.fromEntries(
1362 (yield* Ref.get(fixture.branchCalls)).map((call) => [call.branch, call.cwd]),
1363 );
1364 expect(cwdByBranch).toEqual({
1365 linked: "/worktrees/linked",
1366 emptied: "/workspace/project",
1367 });
1368 }).pipe(Effect.provide(fixture.layer));
1369 }),
1370 );
1371
1372 it.effect("does not settle a thread whose worktree cannot be checked", () =>
1373 Effect.gen(function* () {
1374 yield* TestClock.setTime(Date.parse(NOW));
1375 const fixture = yield* makeHarness({
1376 snapshot: makeSnapshot(
1377 [
1378 makeThread("unreadable-worktree", {
1379 branch: "unreadable",
1380 worktreePath: "/worktrees/unreadable",
1381 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1382 }),
1383 // A merged linked pull request still needs the branch recheck before settling.
1384 makeThread("unreadable-linked-worktree", {
1385 branch: "feature",
1386 worktreePath: "/worktrees/unreadable-linked",
1387 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1388 linkedPullRequest: {
1389 projectId: PROJECT_ID,
1390 repository: "owner/repository",
1391 number: 41,
1392 url: "https://example.test/owner/repository/pull/41",
1393 },
1394 }),
1395 makeThread("readable-worktree", {
1396 branch: "readable",
1397 worktreePath: "/worktrees/readable",
1398 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1399 }),
1400 ],
1401 [
1402 {
1403 ...makeProject(),
1404 repositoryIdentity: {
1405 canonicalKey: "example.test/owner/repository",
1406 locator: {
1407 source: "git-remote",
1408 remoteName: "origin",
1409 remoteUrl: "https://example.test/owner/repository.git",
1410 },
1411 provider: SourceControlProviderKind.make("github"),
1412 owner: "owner",
1413 name: "repository",
1414 },
1415 },
1416 ],
1417 ),
1418 existingWorktreePaths: ["/worktrees/readable", "/worktrees/readable/.git"],
1419 unreadablePaths: ["/worktrees/unreadable/.git", "/worktrees/unreadable-linked/.git"],
1420 pullRequestSummary: (input) =>
1421 Effect.succeed({
1422 ...makePullRequestSummary({ ...input, state: "merged" }),
1423 mergedAt: NOW,
1424 }),
1425 branchPullRequest: (input) =>
1426 input.cwd.startsWith("/worktrees/unreadable")
1427 ? Effect.die(new Error("git: permission denied"))
1428 : Effect.succeed(makeBranchPullRequest("merged")),
1429 });
1430
1431 yield* Effect.gen(function* () {
1432 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1433 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1434 expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
1435 ThreadId.make("readable-worktree"),
1436 ]);
1437 }).pipe(Effect.provide(fixture.layer));
1438 }),
1439 );
1440
1441 it.effect("reevaluates immediately after a pull request merge", () =>
1442 Effect.gen(function* () {
1443 yield* TestClock.setTime(Date.parse(NOW));
1444 const periodicLookupStarted = yield* Deferred.make<void>();
1445 const releasePeriodicLookup = yield* Deferred.make<void>();
1446 const mergedThreadSettled = yield* Deferred.make<void>();
1447 const branchLookupCount = yield* Ref.make(0);
1448 const fixture = yield* makeHarness({
1449 snapshot: makeSnapshot([
1450 makeThread("merged-in-app", {
1451 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1452 linkedPullRequest: {
1453 projectId: PROJECT_ID,
1454 repository: "Owner/Repository",
1455 number: 42,
1456 url: "https://example.test/owner/repository/pull/42",
1457 },
1458 }),
1459 makeThread("slow-periodic-lookup", {
1460 branch: "another-feature",
1461 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1462 }),
1463 ]),
1464 branchPullRequest: () =>
1465 Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
1466 Effect.flatMap((count) =>
1467 count === 1
1468 ? Effect.succeed(makeBranchPullRequest("open"))
1469 : Deferred.succeed(periodicLookupStarted, undefined).pipe(
1470 Effect.andThen(Deferred.await(releasePeriodicLookup)),
1471 Effect.as(makeBranchPullRequest("open")),
1472 ),
1473 ),
1474 ),
1475 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
1476 });
1477
1478 yield* Effect.gen(function* () {
1479 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1480 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1481 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
1482 yield* Deferred.await(periodicLookupStarted);
1483
1484 yield* fixture.publishMerge;
1485 yield* Deferred.await(mergedThreadSettled);
1486
1487 assert.deepStrictEqual(
1488 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1489 [ThreadId.make("merged-in-app")],
1490 );
1491 yield* Deferred.succeed(releasePeriodicLookup, undefined);
1492 yield* reactor.drain;
1493 }).pipe(Effect.provide(fixture.layer));
1494 }),
1495 );
1496
1497 it.effect("settles a merged thread when its background work ends, during a slow full sweep", () =>
1498 Effect.gen(function* () {
1499 yield* TestClock.setTime(Date.parse(NOW));
1500 const periodicLookupStarted = yield* Deferred.make<void>();
1501 const releasePeriodicLookup = yield* Deferred.make<void>();
1502 const settled = yield* Deferred.make<void>();
1503 const branchLookupCount = yield* Ref.make(0);
1504 const mergedLink: NonNullable<SettlementShell["pullRequests"]>[number] = {
1505 ...persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z")),
1506 snapshot: {
1507 state: "merged",
1508 title: "Pull request",
1509 headBranch: "feature",
1510 baseBranch: "main",
1511 isDraft: false,
1512 updatedAt: NOW,
1513 syncedAt: NOW,
1514 mergedAt: NOW,
1515 },
1516 };
1517 const waiting = makeThread("waiting-on-subagent", {
1518 pullRequests: [mergedLink],
1519 pendingBackgroundTasks: [{ taskId: "child", kind: "subagent", description: "Review" }],
1520 });
1521 const slow = makeThread("slow-periodic-lookup", {
1522 branch: "another-feature",
1523 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1524 });
1525 const fixture = yield* makeHarness({
1526 snapshot: makeSnapshot([waiting, slow]),
1527 branchPullRequest: () =>
1528 Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
1529 Effect.flatMap((count) =>
1530 count === 1
1531 ? Effect.succeed(makeBranchPullRequest("open"))
1532 : Deferred.succeed(periodicLookupStarted, undefined).pipe(
1533 Effect.andThen(Deferred.await(releasePeriodicLookup)),
1534 Effect.as(makeBranchPullRequest("open")),
1535 ),
1536 ),
1537 ),
1538 onDispatch: () => Deferred.succeed(settled, undefined),
1539 });
1540
1541 yield* Effect.gen(function* () {
1542 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1543 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1544 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1545 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
1546 yield* Deferred.await(periodicLookupStarted);
1547
1548 yield* Ref.set(
1549 fixture.snapshots,
1550 makeSnapshot([{ ...waiting, pendingBackgroundTasks: [] }, slow]),
1551 );
1552 yield* fixture.publishEvent({
1553 type: "run.background-work-cancelled",
1554 id: EventId.make("event:background-ended"),
1555 threadId: waiting.id,
1556 occurredAt: DateTime.makeUnsafe(NOW),
1557 payload: { runId: RunId.make("run:waiting"), restartCancelledBackgroundWork: [] },
1558 });
1559 yield* Deferred.await(settled);
1560
1561 assert.deepStrictEqual(
1562 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1563 [waiting.id],
1564 );
1565 yield* Deferred.succeed(releasePeriodicLookup, undefined);
1566 yield* reactor.drain;
1567 }).pipe(Effect.provide(fixture.layer));
1568 }),
1569 );
1570
1571 it.effect("settles a stopped thread while another thread's lookup is slow", () =>
1572 Effect.gen(function* () {
1573 yield* TestClock.setTime(Date.parse(NOW));
1574 const slowLookupStarted = yield* Deferred.make<void>();
1575 const releaseSlowLookup = yield* Deferred.make<void>();
1576 const settled = yield* Deferred.make<void>();
1577 const branchLookupCount = yield* Ref.make(0);
1578 const recent = DateTime.makeUnsafe("2026-08-27T00:00:00.000Z");
1579 const slow = makeThread("slow-lookup", { branch: "feature", latestUserMessageAt: recent });
1580 const merged = makeThread("merged", {
1581 latestUserMessageAt: recent,
1582 pullRequests: [
1583 {
1584 ...persistedLink("open", recent),
1585 snapshot: {
1586 state: "merged",
1587 title: "Pull request",
1588 headBranch: "feature",
1589 baseBranch: "main",
1590 isDraft: false,
1591 updatedAt: NOW,
1592 syncedAt: NOW,
1593 mergedAt: NOW,
1594 },
1595 },
1596 ],
1597 pendingBackgroundTasks: [{ taskId: "child", kind: "subagent", description: "Review" }],
1598 });
1599 const fixture = yield* makeHarness({
1600 snapshot: makeSnapshot([slow, merged]),
1601 branchPullRequest: () =>
1602 Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
1603 Effect.flatMap((count) =>
1604 count === 1
1605 ? Effect.succeed(makeBranchPullRequest("open"))
1606 : Deferred.succeed(slowLookupStarted, undefined).pipe(
1607 Effect.andThen(Deferred.await(releaseSlowLookup)),
1608 Effect.as(makeBranchPullRequest("open")),
1609 ),
1610 ),
1611 ),
1612 onDispatch: () => Deferred.succeed(settled, undefined),
1613 });
1614 const backgroundEnded = (threadId: ThreadId): OrchestrationV2DomainEvent => ({
1615 type: "run.background-work-cancelled",
1616 id: EventId.make(`event:background-ended:${threadId}`),
1617 threadId,
1618 occurredAt: DateTime.makeUnsafe(NOW),
1619 payload: { runId: RunId.make(`run:${threadId}`), restartCancelledBackgroundWork: [] },
1620 });
1621
1622 yield* Effect.gen(function* () {
1623 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1624 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1625 yield* fixture.publishEvent(backgroundEnded(slow.id));
1626 yield* Deferred.await(slowLookupStarted);
1627 // More events for the slow thread coalesce into one more pass, not more sweeps.
1628 for (let index = 0; index < 9; index++) {
1629 yield* fixture.publishEvent(backgroundEnded(slow.id));
1630 }
1631
1632 yield* Ref.set(
1633 fixture.snapshots,
1634 makeSnapshot([slow, { ...merged, pendingBackgroundTasks: [] }]),
1635 );
1636 yield* fixture.publishEvent(backgroundEnded(merged.id));
1637 yield* Deferred.await(settled);
1638
1639 assert.deepStrictEqual(
1640 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1641 [merged.id],
1642 );
1643 yield* Deferred.succeed(releaseSlowLookup, undefined);
1644 yield* reactor.drain;
1645 // The startup sweep, the first per-thread sweep, and one coalesced rerun.
1646 assert.strictEqual(yield* Ref.get(branchLookupCount), 3);
1647 }).pipe(Effect.provide(fixture.layer));
1648 }),
1649 );
1650
1651 it.effect.each([
1652 { kind: "an unlinked", linked: false },
1653 { kind: "a quiet linked", linked: true },
1654 ])("settles $kind branch thread its agent merged from a shell, past the cache", ({ linked }) =>
1655 Effect.gen(function* () {
1656 yield* TestClock.setTime(Date.parse(NOW));
1657 const thread = makeThread("shell-merged", {
1658 branch: "saved-feature",
1659 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1660 ...(linked
1661 ? {
1662 branchPullRequest: {
1663 projectId: PROJECT_ID,
1664 repository: "owner/repository",
1665 number: 42,
1666 url: "https://example.test/owner/repository/pull/42",
1667 },
1668 }
1669 : {}),
1670 });
1671 const fixture = yield* makeHarness({
1672 snapshot: makeSnapshot([thread]),
1673 // The host already merged it; only a fresh read sees that past the cached open lookup.
1674 branchPullRequest: (_input, lookupOptions) =>
1675 Effect.succeed(makeBranchPullRequest(lookupOptions?.refresh ? "merged" : "open")),
1676 pullRequestSummary: (input, readOptions) =>
1677 Effect.succeed({
1678 ...makePullRequestSummary({
1679 ...input,
1680 state: readOptions?.bypassCache ? "merged" : "open",
1681 updatedAt: DateTime.formatIso(DateTime.makeUnsafe(Date.parse(NOW) - 2 * DAY_MS)),
1682 }),
1683 ...(readOptions?.bypassCache ? { mergedAt: NOW } : {}),
1684 }),
1685 });
1686 const at = DateTime.makeUnsafe(NOW);
1687 const runId = RunId.make("run:shell-merged");
1688 const runEnded: OrchestrationV2DomainEvent = {
1689 type: "run.background-work-cancelled",
1690 id: EventId.make("event:shell-merged:run-ended"),
1691 threadId: thread.id,
1692 occurredAt: at,
1693 payload: { runId, restartCancelledBackgroundWork: [] },
1694 };
1695
1696 yield* Effect.gen(function* () {
1697 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1698 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1699 yield* fixture.publishEvent(runEnded);
1700 yield* Queue.take(fixture.snapshotReads);
1701 yield* reactor.drain;
1702 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1703
1704 yield* fixture.publishEvent({
1705 type: "turn-item.updated",
1706 id: EventId.make("event:shell-merged:command"),
1707 threadId: thread.id,
1708 runId,
1709 occurredAt: at,
1710 payload: {
1711 id: TurnItemId.make("item:shell-merged:command"),
1712 threadId: thread.id,
1713 runId,
1714 nodeId: null,
1715 providerThreadId: null,
1716 providerTurnId: null,
1717 nativeItemRef: null,
1718 parentItemId: null,
1719 ordinal: 1,
1720 status: "completed",
1721 title: null,
1722 startedAt: at,
1723 completedAt: at,
1724 updatedAt: at,
1725 type: "command_execution",
1726 input: "gh pr merge 42 --squash",
1727 },
1728 });
1729 yield* Queue.take(fixture.snapshotReads);
1730 yield* reactor.drain;
1731 assert.deepStrictEqual(
1732 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1733 [thread.id],
1734 );
1735 }).pipe(Effect.provide(fixture.layer));
1736 }),
1737 );
1738
1739 it.effect(
1740 "settles branch threads on a pull request merge without waiting for the next sweep",
1741 () =>
1742 Effect.gen(function* () {
1743 yield* TestClock.setTime(Date.parse(NOW));
1744 const state = yield* Ref.make<"open" | "merged">("open");
1745 const mergedThreadSettled = yield* Deferred.make<void>();
1746 const fixture = yield* makeHarness({
1747 snapshot: makeSnapshot([
1748 makeThread("branch-thread", {
1749 branch: "saved-feature",
1750 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1751 }),
1752 ]),
1753 branchPullRequest: () => Ref.get(state).pipe(Effect.map(makeBranchPullRequest)),
1754 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
1755 });
1756
1757 yield* Effect.gen(function* () {
1758 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1759 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1760 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1761 assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), []);
1762
1763 yield* Ref.set(state, "merged");
1764 yield* fixture.publishMerge;
1765 yield* Deferred.await(mergedThreadSettled);
1766
1767 assert.deepStrictEqual(
1768 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1769 [ThreadId.make("branch-thread")],
1770 );
1771 assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), ["/workspace/project"]);
1772 yield* reactor.drain;
1773 }).pipe(Effect.provide(fixture.layer));
1774 }),
1775 );
1776
1777 it.effect("reads a quiet open branch pull request every 5 minutes", () =>
1778 Effect.gen(function* () {
1779 yield* TestClock.setTime(Date.parse(NOW));
1780 const fixture = yield* makeHarness({
1781 snapshot: makeSnapshot([
1782 makeThread("active-branch", {
1783 branch: "feature",
1784 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1785 branchPullRequest: {
1786 projectId: PROJECT_ID,
1787 repository: "owner/repository",
1788 number: 42,
1789 url: "https://example.test/owner/repository/pull/42",
1790 },
1791 }),
1792 ]),
1793 pullRequestSummary: (input) =>
1794 Effect.succeed(
1795 makePullRequestSummary({
1796 ...input,
1797 state: "open",
1798 updatedAt: DateTime.formatIso(DateTime.makeUnsafe(Date.parse(NOW) - 2 * DAY_MS)),
1799 }),
1800 ),
1801 });
1802
1803 yield* Effect.gen(function* () {
1804 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1805 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1806 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
1807
1808 for (let minute = 0; minute < 4; minute++) {
1809 yield* TestClock.adjust("1 minute");
1810 yield* Queue.take(fixture.snapshotReads);
1811 yield* reactor.drain;
1812 }
1813 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
1814
1815 yield* TestClock.adjust("1 minute");
1816 yield* Queue.take(fixture.snapshotReads);
1817 yield* reactor.drain;
1818 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
1819
1820 // An app merge the host completes later sends only a refresh; reads stay on the minute
1821 // cadence while the pull request still reads open.
1822 yield* fixture.publishRefresh;
1823 for (const expected of [3, 4]) {
1824 yield* TestClock.adjust("1 minute");
1825 yield* Queue.take(fixture.snapshotReads);
1826 yield* reactor.drain;
1827 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, expected);
1828 }
1829 }).pipe(Effect.provide(fixture.layer));
1830 }),
1831 );
1832
1833 it.effect.each([
1834 { when: "after", mergeDuringRead: false },
1835 { when: "during", mergeDuringRead: true },
1836 ])(
1837 "a merge $when a quiet pull request's read, while its thread is not a candidate, rereads it next sweep",
1838 ({ mergeDuringRead }) =>
1839 Effect.gen(function* () {
1840 yield* TestClock.setTime(Date.parse(NOW));
1841 const thread = makeThread("busy-branch", {
1842 branch: "feature",
1843 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1844 branchPullRequest: {
1845 projectId: PROJECT_ID,
1846 repository: "owner/repository",
1847 number: 42,
1848 url: "https://example.test/owner/repository/pull/42",
1849 },
1850 });
1851 const readStarted = yield* Deferred.make<void>();
1852 const releaseRead = yield* Deferred.make<void>();
1853 if (!mergeDuringRead) yield* Deferred.succeed(releaseRead, undefined);
1854 const fixture = yield* makeHarness({
1855 snapshot: makeSnapshot([thread]),
1856 pullRequestSummary: (input) =>
1857 Deferred.succeed(readStarted, undefined).pipe(
1858 Effect.andThen(Deferred.await(releaseRead)),
1859 Effect.as(
1860 makePullRequestSummary({
1861 ...input,
1862 state: "open",
1863 updatedAt: DateTime.formatIso(DateTime.makeUnsafe(Date.parse(NOW) - 2 * DAY_MS)),
1864 }),
1865 ),
1866 ),
1867 });
1868
1869 yield* Effect.gen(function* () {
1870 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1871 yield* reactor.start();
1872 yield* Deferred.succeed(fixture.activation, undefined);
1873 yield* Queue.take(fixture.snapshotReads);
1874 yield* Deferred.await(readStarted);
1875 if (!mergeDuringRead) yield* reactor.drain;
1876 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
1877
1878 yield* Ref.set(fixture.snapshots, makeSnapshot([]));
1879 yield* fixture.publishMerge;
1880 yield* Queue.take(fixture.snapshotReads);
1881 yield* Deferred.succeed(releaseRead, undefined);
1882 yield* reactor.drain;
1883
1884 yield* Ref.set(fixture.snapshots, makeSnapshot([thread]));
1885 yield* TestClock.adjust("1 minute");
1886 yield* Queue.take(fixture.snapshotReads);
1887 yield* reactor.drain;
1888 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
1889 }).pipe(Effect.provide(fixture.layer));
1890 }),
1891 );
1892
1893 it.effect("rereads a branch without a pull request less often the longer its thread idles", () =>
1894 Effect.gen(function* () {
1895 yield* TestClock.setTime(Date.parse(NOW));
1896 const recent = makeThread("recent-branch", {
1897 branch: "recent-feature",
1898 latestUserMessageAt: DateTime.makeUnsafe(Date.parse(NOW) - 30 * 60 * 1_000),
1899 });
1900 const old = makeThread("old-branch", {
1901 branch: "old-feature",
1902 latestUserMessageAt: DateTime.makeUnsafe(Date.parse(NOW) - 2 * DAY_MS),
1903 });
1904 const fixture = yield* makeHarness({ snapshot: makeSnapshot([recent, old]) });
1905 const branches = Ref.get(fixture.branchCalls).pipe(
1906 Effect.map((calls) => calls.map((call) => call.branch).sort()),
1907 );
1908
1909 yield* Effect.gen(function* () {
1910 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1911 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1912 for (let minute = 1; minute <= 29; minute += 1) {
1913 yield* TestClock.adjust("1 minute");
1914 yield* Queue.take(fixture.snapshotReads);
1915 yield* reactor.drain;
1916 }
1917 assert.deepStrictEqual(yield* branches, ["old-feature", "recent-feature"]);
1918
1919 yield* TestClock.adjust("1 minute");
1920 yield* Queue.take(fixture.snapshotReads);
1921 yield* reactor.drain;
1922 assert.deepStrictEqual(yield* branches, [
1923 "old-feature",
1924 "recent-feature",
1925 "recent-feature",
1926 ]);
1927
1928 // Work ending in the thread reads its branch at once.
1929 yield* fixture.publishEvent({
1930 type: "run.background-work-cancelled",
1931 id: EventId.make("event:old-branch:run-ended"),
1932 threadId: old.id,
1933 occurredAt: DateTime.makeUnsafe(NOW),
1934 payload: { runId: RunId.make("run:old-branch"), restartCancelledBackgroundWork: [] },
1935 });
1936 yield* Queue.take(fixture.snapshotReads);
1937 yield* reactor.drain;
1938 assert.deepStrictEqual(yield* branches, [
1939 "old-feature",
1940 "old-feature",
1941 "recent-feature",
1942 "recent-feature",
1943 ]);
1944 }).pipe(Effect.provide(fixture.layer));
1945 }),
1946 );
1947
1948 it.effect("a sweep looks up a few branches without a pull request, not every one", () =>
1949 Effect.gen(function* () {
1950 yield* TestClock.setTime(Date.parse(NOW));
1951 const threads = Array.from({ length: 10 }, (_, index) =>
1952 makeThread(`idle-${index}`, {
1953 branch: `idle-${index}`,
1954 latestUserMessageAt: DateTime.makeUnsafe(Date.parse(NOW) - (index + 10) * 60 * 1_000),
1955 }),
1956 );
1957 const fixture = yield* makeHarness({ snapshot: makeSnapshot(threads) });
1958 const branches = Ref.get(fixture.branchCalls).pipe(
1959 Effect.map((calls) => calls.map((call) => call.branch).sort()),
1960 );
1961
1962 yield* Effect.gen(function* () {
1963 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1964 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1965 // The most recently active first, then the rest in turn, each once.
1966 assert.deepStrictEqual(yield* branches, ["idle-0", "idle-1", "idle-2", "idle-3"]);
1967 for (let minute = 1; minute <= 5; minute += 1) {
1968 yield* TestClock.adjust("1 minute");
1969 yield* Queue.take(fixture.snapshotReads);
1970 yield* reactor.drain;
1971 }
1972 assert.deepStrictEqual(
1973 yield* branches,
1974 threads.map((thread) => thread.branch),
1975 );
1976 }).pipe(Effect.provide(fixture.layer));
1977 }),
1978 );
1979
1980 it.effect("a merged branch PR that cannot settle its thread rereads no git state", () =>
1981 Effect.gen(function* () {
1982 yield* TestClock.setTime(Date.parse(NOW));
1983 const freshReads = yield* Ref.make(0);
1984 const fixture = yield* makeHarness({
1985 snapshot: makeSnapshot([
1986 makeThread("worked-after-merge", {
1987 branch: "merged-feature",
1988 latestUserAuthoredMessageAt: DateTime.makeUnsafe("2026-08-28T06:00:00.000Z"),
1989 }),
1990 ]),
1991 settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: null },
1992 branchPullRequest: (_input, lookupOptions) =>
1993 Ref.update(
1994 freshReads,
1995 (count) => count + (readsFreshGitState(lookupOptions) ? 1 : 0),
1996 ).pipe(
1997 Effect.as({
1998 ...makeBranchPullRequest("merged"),
1999 mergedAt: "2026-08-27T00:00:00.000Z",
2000 }),
2001 ),
2002 });
2003
2004 yield* Effect.gen(function* () {
2005 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
2006 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
2007 yield* TestClock.adjust("1 minute");
2008 yield* Queue.take(fixture.snapshotReads);
2009 yield* reactor.drain;
2010
2011 assert.strictEqual((yield* Ref.get(fixture.branchCalls)).length, 2);
2012 assert.strictEqual(yield* Ref.get(freshReads), 0);
2013 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
2014 }).pipe(Effect.provide(fixture.layer));
2015 }),
2016 );
2017
2018 it.effect("a remembered merged branch PR settles only after fresh git state agrees", () =>
2019 Effect.gen(function* () {
2020 yield* TestClock.setTime(Date.parse(NOW));
2021 const freshState = yield* Ref.make<"open" | "merged">("open");
2022 const fixture = yield* makeHarness({
2023 snapshot: makeSnapshot([makeThread("merged-branch", { branch: "merged-feature" })]),
2024 settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: null },
2025 branchPullRequest: (_input, lookupOptions) =>
2026 readsFreshGitState(lookupOptions)
2027 ? Ref.get(freshState).pipe(Effect.map(makeBranchPullRequest))
2028 : Effect.succeed(makeBranchPullRequest("merged")),
2029 });
2030
2031 yield* Effect.gen(function* () {
2032 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
2033 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
2034 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
2035
2036 yield* Ref.set(freshState, "merged");
2037 yield* TestClock.adjust("1 minute");
2038 yield* Queue.take(fixture.snapshotReads);
2039 yield* reactor.drain;
2040
2041 assert.deepStrictEqual(
2042 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
2043 [ThreadId.make("merged-branch")],
2044 );
2045 }).pipe(Effect.provide(fixture.layer));
2046 }),
2047 );
2048
2049 it.effect("a merge does not settle threads linked to an unrelated pull request", () =>
2050 Effect.gen(function* () {
2051 yield* TestClock.setTime(Date.parse(NOW));
2052 const mergedThreadSettled = yield* Deferred.make<void>();
2053 const mergeLookupStarted = yield* Deferred.make<void>();
2054 const releaseMergeLookup = yield* Deferred.make<void>();
2055 const lookupCount = yield* Ref.make(0);
2056 const fixture = yield* makeHarness({
2057 snapshot: makeSnapshot([
2058 makeThread("merged-in-app", {
2059 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
2060 linkedPullRequest: {
2061 projectId: PROJECT_ID,
2062 repository: "owner/repository",
2063 number: 42,
2064 url: "https://example.test/owner/repository/pull/42",
2065 },
2066 }),
2067 makeThread("unrelated-linked", {
2068 latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
2069 linkedPullRequest: {
2070 projectId: PROJECT_ID,
2071 repository: "owner/repository",
2072 number: 99,
2073 url: "https://example.test/owner/repository/pull/99",
2074 },
2075 }),
2076 ]),
2077 pullRequestSummary: (input) =>
2078 Ref.updateAndGet(lookupCount, (count) => count + 1).pipe(
2079 Effect.tap((count) =>
2080 count === 3 ? Deferred.succeed(mergeLookupStarted, undefined) : Effect.void,
2081 ),
2082 Effect.tap((count) => (count === 3 ? Deferred.await(releaseMergeLookup) : Effect.void)),
2083 Effect.map(() => makePullRequestSummary({ ...input, state: "open" })),
2084 ),
2085 onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
2086 });
2087
2088 yield* Effect.gen(function* () {
2089 const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
2090 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
2091 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
2092
2093 yield* fixture.publishMerge;
2094 yield* Deferred.await(mergeLookupStarted);
2095 yield* Deferred.await(mergedThreadSettled);
2096 yield* Deferred.succeed(releaseMergeLookup, undefined);
2097 yield* reactor.drain;
2098
2099 assert.deepStrictEqual(
2100 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
2101 [ThreadId.make("merged-in-app")],
2102 );
2103 assert.deepStrictEqual(
2104 (yield* Ref.get(fixture.summaryCalls))
2105 .map((call) => call.number)
2106 .toSorted((left, right) => left - right),
2107 [42, 99, 99],
2108 );
2109 }).pipe(Effect.provide(fixture.layer));
2110 }),
2111 );
2112 });
2113
2114 describe("ThreadSettlementServiceV2 terminals", () => {
2115 it.effect.each(["re-engaged", "deleted"] as const)(
2116 "skips settlement actions for a thread %s before the event ran",
2117 (state) =>
2118 Effect.gen(function* () {
2119 const settled = appThread("stale-thread", "settled", "/worktrees/stale");
2120 const current =
2121 state === "re-engaged"
2122 ? { ...settled, settledOverride: "active" as const }
2123 : { ...settled, deletedAt: DateTime.makeUnsafe(NOW) };
2124 const marker = appThread("marker-thread", "settled", "/worktrees/marker");
2125 const fixture = yield* makeHarness({
2126 snapshot: makeSnapshot([]),
2127 currentThreads: [current, marker],
2128 existingWorktreePaths: ["/worktrees/stale", "/worktrees/marker"],
2129 });
2130
2131 yield* Effect.gen(function* () {
2132 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
2133 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
2134 yield* fixture.publishEvent(settledEvent(settled));
2135 yield* fixture.publishEvent(settledEvent(marker));
2136 assert.deepStrictEqual(yield* Queue.take(fixture.closedIdle), { threadId: marker.id });
2137 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, marker.id);
2138 }).pipe(Effect.provide(fixture.layer));
2139 }),
2140 );
2141
2142 it.effect("runs the settle script in the thread's own worktree", () =>
2143 Effect.gen(function* () {
2144 const shared = appThread("shared-checkout-thread", "settled");
2145 const missing = appThread("removed-worktree-thread", "settled", "/worktrees/removed");
2146 const worktree = appThread("worktree-thread", "settled", "/worktrees/thread");
2147 const fixture = yield* makeHarness({
2148 snapshot: makeSnapshot([]),
2149 currentThreads: [shared, missing, worktree],
2150 existingWorktreePaths: ["/worktrees/thread"],
2151 });
2152
2153 yield* Effect.gen(function* () {
2154 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
2155 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
2156 yield* fixture.publishEvent(settledEvent(shared));
2157 yield* fixture.publishEvent(settledEvent(missing));
2158 yield* fixture.publishEvent(settledEvent(worktree));
2159 const run = yield* Queue.take(fixture.scriptRuns);
2160 assert.strictEqual(run.threadId, worktree.id);
2161 assert.strictEqual(run.worktreePath, "/worktrees/thread");
2162 assert.strictEqual(run.trigger, "settle");
2163 }).pipe(Effect.provide(fixture.layer));
2164 }),
2165 );
2166
2167 it.effect.each(["re-engaged", "deleted"] as const)(
2168 "skips the settle script for a thread %s while its shells close",
2169 (state) =>
2170 Effect.gen(function* () {
2171 const settled = appThread("stale-thread", "settled", "/worktrees/stale");
2172 const marker = appThread("marker-thread", "settled", "/worktrees/marker");
2173 const currentThreads = [settled, marker];
2174 const fixture = yield* makeHarness({
2175 snapshot: makeSnapshot([]),
2176 currentThreads,
2177 existingWorktreePaths: ["/worktrees/stale", "/worktrees/marker"],
2178 onCloseIdle: () =>
2179 Effect.sync(() => {
2180 currentThreads[0] =
2181 state === "re-engaged"
2182 ? { ...settled, settledOverride: "active" }
2183 : { ...settled, deletedAt: DateTime.makeUnsafe(NOW) };
2184 }),
2185 });
2186
2187 yield* Effect.gen(function* () {
2188 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
2189 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
2190 yield* fixture.publishEvent(settledEvent(settled));
2191 yield* fixture.publishEvent(settledEvent(marker));
2192 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, marker.id);
2193 }).pipe(Effect.provide(fixture.layer));
2194 }),
2195 );
2196
2197 it.effect("skips the settle script for a subagent in its parent's worktree", () =>
2198 Effect.gen(function* () {
2199 const parent = appThread("subagent-parent", "settled", "/worktrees/parent");
2200 const subagent = (id: string, worktreePath: string) => ({
2201 ...appThread(id, "settled", worktreePath),
2202 lineage: {
2203 parentThreadId: parent.id,
2204 relationshipToParent: "subagent" as const,
2205 rootThreadId: parent.id,
2206 },
2207 });
2208 const shared = subagent("subagent-shared", "/worktrees/parent");
2209 const own = subagent("subagent-own", "/worktrees/own");
2210 const fixture = yield* makeHarness({
2211 snapshot: makeSnapshot([]),
2212 currentThreads: [parent, shared, own],
2213 existingWorktreePaths: ["/worktrees/parent", "/worktrees/own"],
2214 });
2215
2216 yield* Effect.gen(function* () {
2217 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
2218 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
2219 // Events run in order, so the first run belongs to the second event
2220 // only if the shared-worktree child was skipped. Both still close.
2221 yield* fixture.publishEvent(settledEvent(shared));
2222 yield* fixture.publishEvent(settledEvent(own));
2223 assert.deepStrictEqual(yield* Queue.take(fixture.closedIdle), { threadId: shared.id });
2224 assert.deepStrictEqual(yield* Queue.take(fixture.closedIdle), { threadId: own.id });
2225 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, own.id);
2226 }).pipe(Effect.provide(fixture.layer));
2227 }),
2228 );
2229
2230 it.effect("runs the settle script once when a settlement is re-emitted", () =>
2231 Effect.gen(function* () {
2232 const repeated = appThread("repeated-thread", "settled", "/worktrees/repeated");
2233 const marker = appThread("marker-thread", "settled", "/worktrees/marker");
2234 const fixture = yield* makeHarness({
2235 snapshot: makeSnapshot([]),
2236 currentThreads: [repeated, marker],
2237 existingWorktreePaths: ["/worktrees/repeated", "/worktrees/marker"],
2238 });
2239
2240 yield* Effect.gen(function* () {
2241 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
2242 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
2243 yield* fixture.publishEvent(settledEvent(repeated));
2244 yield* fixture.publishEvent(settledEvent(repeated));
2245 yield* fixture.publishEvent(settledEvent(marker));
2246 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, repeated.id);
2247 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, marker.id);
2248 }).pipe(Effect.provide(fixture.layer));
2249 }),
2250 );
2251
2252 it.effect("retries the settle script on a re-emitted settlement after a failed start", () =>
2253 Effect.gen(function* () {
2254 const thread = appThread("failed-start-thread", "settled", "/worktrees/failed-start");
2255 const starts = yield* Ref.make(0);
2256 const fixture = yield* makeHarness({
2257 snapshot: makeSnapshot([]),
2258 currentThreads: [thread],
2259 existingWorktreePaths: ["/worktrees/failed-start"],
2260 onScriptRun: () =>
2261 Ref.updateAndGet(starts, (count) => count + 1).pipe(
2262 Effect.flatMap((count) =>
2263 count === 1 ? Effect.die(new Error("terminal failed to open")) : Effect.void,
2264 ),
2265 ),
2266 });
2267
2268 yield* Effect.gen(function* () {
2269 const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
2270 yield* startHarness(service, fixture.activation, fixture.snapshotReads);
2271 yield* fixture.publishEvent(settledEvent(thread));
2272 yield* fixture.publishEvent(settledEvent(thread));
2273 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, thread.id);
2274 assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, thread.id);
2275 }).pipe(Effect.provide(fixture.layer));
2276 }),
2277 );
2278 });
2279
2280 describe("isSnoozed", () => {
2281 const snoozed = { snoozedAt: at(-2 * DAY_MS), snoozedUntil: at(DAY_MS) };
2282 it("defers existing input while new questions and approvals wake the thread", () => {
2283 const request = {
2284 id: RuntimeRequestId.make("question"),
2285 kind: "user_input" as const,
2286 createdAt: snoozed.snoozedAt,
2287 };
2288 expect(
2289 ThreadSettlementService.isSnoozed(
2290 shell({ ...snoozed, pendingRuntimeRequest: request }),
2291 NOW_MS,
2292 ),
2293 ).toBe(true);
2294 expect(
2295 ThreadSettlementService.isSnoozed(
2296 shell({ ...snoozed, pendingRuntimeRequest: { ...request, createdAt: at(-DAY_MS) } }),
2297 NOW_MS,
2298 ),
2299 ).toBe(false);
2300 expect(
2301 ThreadSettlementService.isSnoozed(
2302 shell({ ...snoozed, pendingRuntimeRequest: { ...request, kind: "command" } }),
2303 NOW_MS,
2304 ),
2305 ).toBe(false);
2306 expect(
2307 ThreadSettlementService.isSnoozed(
2308 shell({ ...snoozed, snoozedAt: null, pendingRuntimeRequest: request }),
2309 NOW_MS,
2310 ),
2311 ).toBe(false);
2312 });
2313 it("keeps a run requested and completed after snoozing parked until the timer", () => {
2314 const thread = shell({
2315 ...snoozed,
2316 status: "completed",
2317 latestRunRequestedAt: at(-2 * DAY_MS + 1),
2318 latestRunStartedAt: at(-DAY_MS - 1),
2319 latestRunCompletedAt: at(-DAY_MS),
2320 });
2321
2322 expect(ThreadSettlementService.isSnoozed(thread, NOW_MS)).toBe(true);
2323 expect(ThreadSettlementService.isAutoSettlementCandidate(thread, NOW_MS)).toBe(false);
2324 expect(
2325 ThreadSettlementService.resolveAutoSettlementAt({
2326 thread,
2327 pullRequest: { state: "merged", mergedAt: DateTime.formatIso(at(-1)) },
2328 nowMs: NOW_MS,
2329 autoSettleAfterDays: null,
2330 autoSettleOnMerge: true,
2331 }),
2332 ).toBeNull();
2333 });
2334 });