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

ThreadSettlementService.test.ts

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