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