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

ThreadSettlementService.test.ts

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