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

ThreadSettlementService.test.ts

1,276 lines48.2 KB

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