Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadSettlementService.test.ts

1,297 lines48.9 KB

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