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

ThreadSettlementReactor.test.ts

622 lines22.6 KB

1import {
2 DEFAULT_SERVER_SETTINGS,
3 ProjectId,
4 ProviderInstanceId,
5 PullRequestOperationError,
6 ThreadId,
7 type OrchestrationCommand,
8 type OrchestrationProjectShell,
9 type OrchestrationShellSnapshot,
10 type OrchestrationThreadShell,
11 type PullRequestSummary,
12 type ServerSettings,
13 type ServerSettingsPatch,
14} from "@t3tools/contracts";
15import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
16import { assert, describe, it } from "@effect/vitest";
17import * as Crypto from "effect/Crypto";
18import * as Deferred from "effect/Deferred";
19import * as Effect from "effect/Effect";
20import * as Layer from "effect/Layer";
21import * as PubSub from "effect/PubSub";
22import * as Queue from "effect/Queue";
23import * as Ref from "effect/Ref";
24import * as Stream from "effect/Stream";
25import { TestClock } from "effect/testing";
26​
27import { GitManager } from "../git/GitManager.ts";
28import { PullRequestService } from "../pullRequest/PullRequestService.ts";
29import { ServerActivation } from "../serverActivation.ts";
30import { ServerSettingsService } from "../serverSettings.ts";
31import { OrchestrationCommandInvariantError } from "./Errors.ts";
32import {
33 OrchestrationEngineService,
34 type OrchestrationEngineShape,
35} from "./Services/OrchestrationEngine.ts";
36import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";
37import * as ThreadSettlementReactor from "./ThreadSettlementReactor.ts";
38​
39const NOW = "2026-08-28T12:00:00.000Z";
40const PROJECT_ID = ProjectId.make("settlement-project");
41const LINKED_PROJECT_ID = ProjectId.make("linked-settlement-project");
42​
43type AutoSettleCommand = Extract<OrchestrationCommand, { readonly type: "thread.auto-settle" }>;
44​
45const testCrypto = Crypto.make({
46 randomBytes: (size) => new Uint8Array(size).fill(1),
47 digest: (_algorithm, data) => Effect.succeed(data),
48});
49​
50function makeProject(
51 id: ProjectId = PROJECT_ID,
52 workspaceRoot = "/workspace/project",
53): OrchestrationProjectShell {
54 return {
55 id,
56 title: `Project ${id}`,
57 workspaceRoot,
58 defaultModelSelection: null,
59 scripts: [],
60 createdAt: "2026-08-01T00:00:00.000Z",
61 updatedAt: NOW,
62 };
64​
65function makeThread(
66 id: string,
67 overrides: Partial<OrchestrationThreadShell> = {},
68): OrchestrationThreadShell {
69 return {
70 id: ThreadId.make(id),
71 projectId: PROJECT_ID,
72 title: id,
73 modelSelection: {
74 instanceId: ProviderInstanceId.make("codex"),
75 model: "gpt-5",
76 },
77 runtimeMode: "full-access",
78 interactionMode: "default",
79 branch: null,
80 worktreePath: null,
81 latestTurn: null,
82 createdAt: "2026-08-01T00:00:00.000Z",
83 updatedAt: "2026-08-20T00:00:00.000Z",
84 archivedAt: null,
85 settledOverride: null,
86 settledAt: null,
87 session: null,
88 latestUserMessageAt: "2026-08-20T00:00:00.000Z",
89 hasPendingApprovals: false,
90 hasPendingUserInput: false,
91 hasActionableProposedPlan: false,
92 ...overrides,
93 };
95​
96function makeSnapshot(
97 threads: ReadonlyArray<OrchestrationThreadShell>,
98 projects: ReadonlyArray<OrchestrationProjectShell> = [makeProject()],
99): OrchestrationShellSnapshot {
100 return {
101 snapshotSequence: 1,
102 projects,
103 threads,
104 updatedAt: NOW,
105 };
107​
108function makePullRequestSummary(input: {
109 readonly projectId: ProjectId;
110 readonly repository: string;
111 readonly number: number;
112 readonly state: "open" | "closed" | "merged";
113 readonly updatedAt?: string;
114}): PullRequestSummary {
115 return {
116 provider: "github",
117 projectId: input.projectId,
118 repository: input.repository,
119 number: input.number,
120 title: "Pull request",
121 url: `https://example.test/${input.repository}/pull/${input.number}`,
122 state: input.state,
123 headBranch: "feature",
124 baseBranch: "main",
125 updatedAt: input.updatedAt ?? NOW,
126 };
128​
129interface HarnessOptions {
130 readonly snapshot: OrchestrationShellSnapshot;
131 readonly settings?: ServerSettings;
132 readonly branchPullRequest?: GitManager["Service"]["branchPullRequest"];
133 readonly pullRequestSummary?: PullRequestService["Service"]["summary"];
134 readonly onDispatch?: (
135 command: AutoSettleCommand,
136 ) => Effect.Effect<void, OrchestrationCommandInvariantError>;
138​
139const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: HarnessOptions) {
140 const activation = yield* Deferred.make<void>();
141 const snapshots = yield* Ref.make(options.snapshot);
142 const snapshotReadCount = yield* Ref.make(0);
143 const snapshotReads = yield* Queue.unbounded<number>();
144 const settings = yield* Ref.make(options.settings ?? DEFAULT_SERVER_SETTINGS);
145 const settingsChanges = yield* PubSub.unbounded<ServerSettings>();
146 const commands = yield* Ref.make<ReadonlyArray<AutoSettleCommand>>([]);
147 const branchCalls = yield* Ref.make<
148 ReadonlyArray<{ readonly cwd: string; readonly branch: string }>
149 >([]);
150 const summaryCalls = yield* Ref.make<
151 ReadonlyArray<{
152 readonly projectId: ProjectId;
153 readonly repository: string;
154 readonly number: number;
155 }>
156 >([]);
157 const summaryRecovery = yield* Ref.make<ReadonlyArray<boolean | undefined>>([]);
158​
159 const updateSettings = (patch: ServerSettingsPatch) =>
160 Effect.gen(function* () {
161 const next = applyServerSettingsPatch(yield* Ref.get(settings), patch);
162 yield* Ref.set(settings, next);
163 yield* PubSub.publish(settingsChanges, next);
164 return next;
165 });
166​
167 const branchPullRequest: GitManager["Service"]["branchPullRequest"] = (input) =>
168 Ref.update(branchCalls, (calls) => [...calls, input]).pipe(
169 Effect.andThen(options.branchPullRequest?.(input) ?? Effect.succeed(null)),
170 );
171​
172 const pullRequestSummary: PullRequestService["Service"]["summary"] = (input, readOptions) =>
173 Effect.gen(function* () {
174 yield* Ref.update(summaryCalls, (calls) => [...calls, input]);
175 yield* Ref.update(summaryRecovery, (values) => [
176 ...values,
177 readOptions?.recoverTransientFailure,
178 ]);
179 return yield* (
180 options.pullRequestSummary?.(input, readOptions) ??
181 Effect.succeed(
182 makePullRequestSummary({
183 ...input,
184 state: "open",
185 }),
186 )
187 );
188 });
189​
190 const dispatch: OrchestrationEngineShape["dispatch"] = (command) => {
191 if (command.type !== "thread.auto-settle") {
192 return Effect.die(new Error(`Unexpected command: ${command.type}`));
193 }
194 return Ref.update(commands, (recorded) => [...recorded, command]).pipe(
195 Effect.andThen(options.onDispatch?.(command) ?? Effect.void),
196 Effect.as({ sequence: 1 }),
197 );
198 };
199​
200 const serverSettings = ServerSettingsService.of({
201 start: Effect.void,
202 ready: Effect.void,
203 getSettings: Ref.get(settings),
204 updateSettings,
205 streamChanges: Stream.fromPubSub(settingsChanges),
206 subscribeChanges: PubSub.subscribe(settingsChanges).pipe(
207 Effect.map((subscription) => Stream.fromSubscription(subscription)),
208 ),
209 });
210​
211 const dependencies = Layer.mergeAll(
212 Layer.mock(ProjectionSnapshotQuery)({
213 getShellSnapshot: () =>
214 Ref.updateAndGet(snapshotReadCount, (count) => count + 1).pipe(
215 Effect.tap((count) => Queue.offer(snapshotReads, count)),
216 Effect.andThen(Ref.get(snapshots)),
217 ),
218 }),
219 Layer.mock(GitManager)({ branchPullRequest }),
220 Layer.mock(PullRequestService)({ summary: pullRequestSummary }),
221 Layer.mock(OrchestrationEngineService)({
222 readEvents: () => Stream.empty,
223 dispatch,
224 streamDomainEvents: Stream.empty,
225 latestSequence: Effect.succeed(0),
226 }),
227 Layer.succeed(ServerSettingsService, serverSettings),
228 Layer.succeed(ServerActivation, Deferred.await(activation)),
229 Layer.succeed(Crypto.Crypto, testCrypto),
230 );
231​
232 return {
233 activation,
234 snapshots,
235 snapshotReadCount,
236 snapshotReads,
237 commands,
238 branchCalls,
239 summaryCalls,
240 summaryRecovery,
241 updateSettings,
242 layer: ThreadSettlementReactor.layer.pipe(Layer.provide(dependencies)),
243 };
244});
245​
246const startHarness = Effect.fn("startThreadSettlementHarness")(function* (
247 reactor: ThreadSettlementReactor.ThreadSettlementReactor["Service"],
248 activation: Deferred.Deferred<void>,
249 snapshotReads: Queue.Queue<number>,
250) {
251 yield* reactor.start();
252 yield* Deferred.succeed(activation, undefined);
253 yield* Queue.take(snapshotReads);
254 yield* reactor.drain;
255});
256​
257describe("ThreadSettlementReactor", () => {
258 it.effect("starts without clients and skips protected threads before pull request lookup", () =>
259 Effect.scoped(
260 Effect.gen(function* () {
261 yield* TestClock.setTime(Date.parse(NOW));
262 const linkedPullRequest = {
263 projectId: LINKED_PROJECT_ID,
264 repository: "owner/repository",
265 number: 42,
266 url: "https://example.test/owner/repository/pull/42",
267 } as const;
268 const skipped = [
269 makeThread("pending-approval", {
270 branch: "skip-approval",
271 hasPendingApprovals: true,
272 }),
273 makeThread("snoozed", {
274 branch: "skip-snoozed",
275 snoozedUntil: "2026-08-29T00:00:00.000Z",
276 }),
277 ];
278 const fixture = yield* makeHarness({
279 snapshot: makeSnapshot(
280 [
281 makeThread("inactive", { branch: "inactive-feature" }),
282 makeThread("closed-pr", { linkedPullRequest }),
283 ...skipped,
284 ],
285 [makeProject(), makeProject(LINKED_PROJECT_ID, "/workspace/linked")],
286 ),
287 branchPullRequest: () => Effect.succeed(null),
288 pullRequestSummary: (input) =>
289 Effect.succeed(makePullRequestSummary({ ...input, state: "closed" })),
290 });
291​
292 yield* Effect.gen(function* () {
293 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
294 yield* reactor.start();
295 assert.strictEqual(yield* Ref.get(fixture.snapshotReadCount), 0);
296​
297 yield* Deferred.succeed(fixture.activation, undefined);
298 yield* Queue.take(fixture.snapshotReads);
299 yield* reactor.drain;
300​
301 const commands = yield* Ref.get(fixture.commands);
302 assert.deepStrictEqual(
303 commands
304 .map(({ threadId, snapshotSequence, settledAt }) => ({
305 threadId,
306 snapshotSequence,
307 settledAt,
308 }))
309 .sort((left, right) => left.threadId.localeCompare(right.threadId)),
310 [
311 {
312 threadId: ThreadId.make("closed-pr"),
313 snapshotSequence: 1,
314 settledAt: "2026-08-20T00:00:00.000Z",
315 },
316 {
317 threadId: ThreadId.make("inactive"),
318 snapshotSequence: 1,
319 settledAt: "2026-08-20T00:00:00.000Z",
320 },
321 ],
322 );
323 assert.deepStrictEqual(yield* Ref.get(fixture.branchCalls), [
324 { cwd: "/workspace/project", branch: "inactive-feature" },
325 ]);
326 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), [
327 { projectId: LINKED_PROJECT_ID, repository: "owner/repository", number: 42 },
328 ]);
329 assert.deepStrictEqual(yield* Ref.get(fixture.summaryRecovery), [false]);
330 }).pipe(Effect.provide(fixture.layer));
331 }),
332 ),
333 );
334​
335 it.effect("reevaluates inactivity and pull request state once per minute", () =>
336 Effect.scoped(
337 Effect.gen(function* () {
338 yield* TestClock.setTime(Date.parse(NOW));
339 const pullRequest = yield* Ref.make<"open" | "merged">("open");
340 const fixture = yield* makeHarness({
341 snapshot: makeSnapshot([
342 makeThread("at-boundary", {
343 latestUserMessageAt: "2026-08-25T12:00:00.000Z",
344 }),
345 makeThread("open-pr", {
346 branch: "saved-feature",
347 latestUserMessageAt: "2026-08-27T00:00:00.000Z",
348 }),
349 ]),
350 branchPullRequest: () =>
351 Ref.get(pullRequest).pipe(Effect.map((state) => ({ state, updatedAt: NOW }))),
352 });
353​
354 yield* Effect.gen(function* () {
355 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
356 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
357 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
358​
359 yield* Ref.set(pullRequest, "merged");
360 yield* TestClock.adjust("1 minute");
361 yield* Queue.take(fixture.snapshotReads);
362 yield* reactor.drain;
363​
364 assert.deepStrictEqual(
365 (yield* Ref.get(fixture.commands))
366 .map((command) => command.threadId)
367 .sort((left, right) => left.localeCompare(right)),
368 [ThreadId.make("at-boundary"), ThreadId.make("open-pr")],
369 );
370 assert.strictEqual((yield* Ref.get(fixture.branchCalls)).length, 2);
371 }).pipe(Effect.provide(fixture.layer));
372 }),
373 ),
374 );
375​
376 it.effect("uses fresh settlement settings after lookup and ignores unrelated changes", () =>
377 Effect.scoped(
378 Effect.gen(function* () {
379 yield* TestClock.setTime(Date.parse(NOW));
380 const state = yield* Ref.make<"merged" | "closed">("merged");
381 const firstLookupStarted = yield* Deferred.make<void>();
382 const releaseFirstLookup = yield* Deferred.make<void>();
383 const laterLookupStarted = yield* Deferred.make<void>();
384 const releaseLaterLookup = yield* Deferred.make<void>();
385 const lookupCount = yield* Ref.make(0);
386 const fixture = yield* makeHarness({
387 snapshot: makeSnapshot([makeThread("settings-thread", { branch: "saved-feature" })]),
388 settings: {
389 ...DEFAULT_SERVER_SETTINGS,
390 sidebarAutoSettleAfterDays: null,
391 sidebarAutoSettleOnMerge: true,
392 },
393 branchPullRequest: () =>
394 Ref.updateAndGet(lookupCount, (count) => count + 1).pipe(
395 Effect.tap((count) =>
396 count === 1
397 ? Deferred.succeed(firstLookupStarted, undefined)
398 : count === 3
399 ? Deferred.succeed(laterLookupStarted, undefined)
400 : Effect.void,
401 ),
402 Effect.tap((count) =>
403 count === 1
404 ? Deferred.await(releaseFirstLookup)
405 : count === 3
406 ? Deferred.await(releaseLaterLookup)
407 : Effect.void,
408 ),
409 Effect.andThen(Ref.get(state)),
410 Effect.map((pullRequestState) => ({ state: pullRequestState, updatedAt: NOW })),
411 ),
412 });
413​
414 yield* Effect.gen(function* () {
415 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
416 yield* reactor.start();
417 yield* Deferred.succeed(fixture.activation, undefined);
418 yield* Queue.take(fixture.snapshotReads);
419 yield* Deferred.await(firstLookupStarted);
420​
421 yield* fixture.updateSettings({ sidebarAutoSettleOnMerge: false });
422 yield* Deferred.succeed(releaseFirstLookup, undefined);
423 yield* Queue.take(fixture.snapshotReads);
424 yield* reactor.drain;
425 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
426 assert.strictEqual(yield* Ref.get(fixture.snapshotReadCount), 2);
427​
428 yield* Ref.set(state, "closed");
429 yield* fixture.updateSettings({ enableAgentBrowserAccess: false });
430 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 1 });
431 yield* Deferred.await(laterLookupStarted);
432 yield* Deferred.succeed(releaseLaterLookup, undefined);
433 yield* reactor.drain;
434​
435 assert.strictEqual(yield* Ref.get(fixture.snapshotReadCount), 3);
436 assert.strictEqual(yield* Ref.get(lookupCount), 3);
437 assert.deepStrictEqual(
438 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
439 [ThreadId.make("settings-thread")],
440 );
441 }).pipe(Effect.provide(fixture.layer));
442 }),
443 ),
444 );
445​
446 it.effect("keeps an unknown pull request active and continues with other candidates", () =>
447 Effect.scoped(
448 Effect.gen(function* () {
449 yield* TestClock.setTime(Date.parse(NOW));
450 const fixture = yield* makeHarness({
451 snapshot: makeSnapshot(
452 [
453 makeThread("lookup-failed", {
454 linkedPullRequest: {
455 projectId: LINKED_PROJECT_ID,
456 repository: "owner/repository",
457 number: 9,
458 url: "https://example.test/owner/repository/pull/9",
459 },
460 }),
461 makeThread("inactive-without-pr"),
462 ],
463 [makeProject(), makeProject(LINKED_PROJECT_ID, "/workspace/linked")],
464 ),
465 pullRequestSummary: () =>
466 Effect.fail(
467 new PullRequestOperationError({
468 operation: "summary",
469 detail: "host unavailable",
470 }),
471 ),
472 });
473​
474 yield* Effect.gen(function* () {
475 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
476 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
477​
478 assert.deepStrictEqual(
479 (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
480 [ThreadId.make("inactive-without-pr")],
481 );
482 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
483 }).pipe(Effect.provide(fixture.layer));
484 }),
485 ),
486 );
487​
488 it.effect("keeps threads active when their pull request project is unavailable", () =>
489 Effect.scoped(
490 Effect.gen(function* () {
491 yield* TestClock.setTime(Date.parse(NOW));
492 const linkedPullRequest = {
493 projectId: LINKED_PROJECT_ID,
494 repository: "owner/repository",
495 number: 10,
496 url: "https://example.test/owner/repository/pull/10",
497 } as const;
498 const fixture = yield* makeHarness({
499 snapshot: makeSnapshot(
500 [
501 makeThread("missing-own-project", { linkedPullRequest }),
502 makeThread("missing-branch-project", { branch: "saved-feature" }),
503 ],
504 [makeProject(LINKED_PROJECT_ID, "/workspace/linked")],
505 ),
506 pullRequestSummary: (input) =>
507 Effect.succeed(makePullRequestSummary({ ...input, state: "open" })),
508 });
509​
510 yield* Effect.gen(function* () {
511 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
512 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
513​
514 assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
515 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), [
516 { projectId: LINKED_PROJECT_ID, repository: "owner/repository", number: 10 },
517 ]);
518 assert.deepStrictEqual(yield* Ref.get(fixture.branchCalls), []);
519 }).pipe(Effect.provide(fixture.layer));
520 }),
521 ),
522 );
523​
524 it.effect("deduplicates saved-branch and linked pull request lookups within a sweep", () =>
525 Effect.scoped(
526 Effect.gen(function* () {
527 yield* TestClock.setTime(Date.parse(NOW));
528 const linkedPullRequest = {
529 projectId: LINKED_PROJECT_ID,
530 repository: "owner/repository",
531 number: 77,
532 url: "https://example.test/owner/repository/pull/77",
533 } as const;
534 const fixture = yield* makeHarness({
535 snapshot: makeSnapshot(
536 [
537 makeThread("branch-one", {
538 branch: "saved-feature",
539 worktreePath: "/deleted/worktree-one",
540 }),
541 makeThread("branch-two", {
542 branch: "saved-feature",
543 worktreePath: "/deleted/worktree-two",
544 }),
545 makeThread("linked-one", { linkedPullRequest }),
546 makeThread("linked-two", { linkedPullRequest }),
547 ],
548 [
549 makeProject(PROJECT_ID, "/workspace/project-root"),
550 makeProject(LINKED_PROJECT_ID, "/workspace/linked-root"),
551 ],
552 ),
553 branchPullRequest: () => Effect.succeed({ state: "closed", updatedAt: NOW }),
554 pullRequestSummary: (input) =>
555 Effect.succeed(makePullRequestSummary({ ...input, state: "merged" })),
556 });
557​
558 yield* Effect.gen(function* () {
559 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
560 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
561​
562 assert.deepStrictEqual(yield* Ref.get(fixture.branchCalls), [
563 { cwd: "/workspace/project-root", branch: "saved-feature" },
564 ]);
565 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), [
566 { projectId: LINKED_PROJECT_ID, repository: "owner/repository", number: 77 },
567 ]);
568 assert.deepStrictEqual(
569 new Set((yield* Ref.get(fixture.commands)).map((command) => command.threadId)),
570 new Set([
571 ThreadId.make("branch-one"),
572 ThreadId.make("branch-two"),
573 ThreadId.make("linked-one"),
574 ThreadId.make("linked-two"),
575 ]),
576 );
577 }).pipe(Effect.provide(fixture.layer));
578 }),
579 ),
580 );
581​
582 it.effect("carries the snapshot guard and survives a stale dispatch rejection", () =>
583 Effect.scoped(
584 Effect.gen(function* () {
585 yield* TestClock.setTime(Date.parse(NOW));
586 const fixture = yield* makeHarness({
587 snapshot: makeSnapshot([makeThread("stale"), makeThread("next-candidate")]),
588 onDispatch: (command) =>
589 command.threadId === ThreadId.make("stale")
590 ? Effect.fail(
591 new OrchestrationCommandInvariantError({
592 commandType: command.type,
593 detail: "thread changed after settlement evaluation",
594 }),
595 )
596 : Effect.void,
597 });
598​
599 yield* Effect.gen(function* () {
600 const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
601 yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
602​
603 const firstSweep = yield* Ref.get(fixture.commands);
604 assert.strictEqual(
605 firstSweep.find((command) => command.threadId === ThreadId.make("stale"))
606 ?.snapshotSequence,
607 1,
608 );
609 assert.strictEqual(
610 firstSweep.some((command) => command.threadId === ThreadId.make("next-candidate")),
611 true,
612 );
613​
614 yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
615 yield* Queue.take(fixture.snapshotReads);
616 yield* reactor.drain;
617 assert.strictEqual((yield* Ref.get(fixture.commands)).length, 4);
618 }).pipe(Effect.provide(fixture.layer));
619 }),
620 ),
621 );
622});