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