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