Open History to see the last commit
1import {
2 CommandId,
3 EventId,
4 MessageId,
5 ProjectId,
6 ProviderInstanceId,
7 ThreadId,
8 type OrchestrationReadModel,
9 type OrchestrationSession,
10 type OrchestrationThread,
11} from "@t3tools/contracts";
12import * as NodeServices from "@effect/platform-node/NodeServices";
13import { expect, it } from "@effect/vitest";
14import * as Effect from "effect/Effect";
15
16import { decideOrchestrationCommand } from "./decider.ts";
17
18const NOW = "2026-01-01T00:00:00.000Z";
19const SETTLED_AT = "2025-12-30T00:00:00.000Z";
20
21function makeReadModel(
22 settledOverride: OrchestrationThread["settledOverride"],
23 archivedAt: string | null = null,
24 session: OrchestrationSession | null = null,
25 activities: OrchestrationThread["activities"] = [],
26 messages: OrchestrationThread["messages"] = [],
27): OrchestrationReadModel {
28 return {
29 snapshotSequence: 0,
30 projects: [],
31 threads: [
32 {
33 id: ThreadId.make("thread-1"),
34 projectId: ProjectId.make("project-1"),
35 title: "Thread",
36 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
37 runtimeMode: "full-access",
38 interactionMode: "default",
39 branch: null,
40 worktreePath: null,
41 latestTurn: null,
42 createdAt: NOW,
43 updatedAt: NOW,
44 archivedAt,
45 settledOverride,
46 settledAt: settledOverride === "settled" ? SETTLED_AT : null,
47 deletedAt: null,
48 messages,
49 proposedPlans: [],
50 activities,
51 checkpoints: [],
52 session,
53 },
54 ],
55 updatedAt: NOW,
56 };
57}
58
59function makeSession(status: OrchestrationSession["status"]): OrchestrationSession {
60 return {
61 threadId: ThreadId.make("thread-1"),
62 status,
63 providerName: "Codex",
64 runtimeMode: "full-access",
65 activeTurnId: null,
66 lastError: null,
67 updatedAt: NOW,
68 };
69}
70
71it.layer(NodeServices.layer)("settled thread decider", (it) => {
72 it.effect("settles active threads and re-emits idempotently for settled ones", () =>
73 Effect.gen(function* () {
74 const event = yield* decideOrchestrationCommand({
75 command: {
76 type: "thread.settle",
77 commandId: CommandId.make("cmd-settle"),
78 threadId: ThreadId.make("thread-1"),
79 },
80 readModel: makeReadModel(null),
81 });
82 const events = Array.isArray(event) ? event : [event];
83 expect(events).toHaveLength(1);
84 expect(events[0]?.type).toBe("thread.settled");
85 if (events[0]?.type === "thread.settled") {
86 expect(events[0].payload.settledAt).toBe(events[0].payload.updatedAt);
87 }
88
89 // Already settled: the engine rejects zero-event commands, so idempotency
90 // is by re-emission — preserving the original settledAt.
91 const reEmit = yield* decideOrchestrationCommand({
92 command: {
93 type: "thread.settle",
94 commandId: CommandId.make("cmd-settle-again"),
95 threadId: ThreadId.make("thread-1"),
96 },
97 readModel: makeReadModel("settled"),
98 });
99 const reEmitEvents = Array.isArray(reEmit) ? reEmit : [reEmit];
100 expect(reEmitEvents).toHaveLength(1);
101 expect(reEmitEvents[0]?.type).toBe("thread.settled");
102 if (reEmitEvents[0]?.type === "thread.settled") {
103 expect(reEmitEvents[0].payload.settledAt).toBe(SETTLED_AT);
104 // updatedAt must NOT rewind to the historical settledAt: sorting and
105 // relative-time labels key on it.
106 expect(reEmitEvents[0].payload.updatedAt).not.toBe(SETTLED_AT);
107 }
108 }),
109 );
110
111 it.effect("rejects settling a thread with a live session", () =>
112 Effect.gen(function* () {
113 for (const status of ["starting", "running"] as const) {
114 const error = yield* decideOrchestrationCommand({
115 command: {
116 type: "thread.settle",
117 commandId: CommandId.make(`cmd-settle-live-${status}`),
118 threadId: ThreadId.make("thread-1"),
119 },
120 readModel: makeReadModel(null, null, makeSession(status)),
121 }).pipe(Effect.flip);
122 expect(error._tag).toBe("OrchestrationCommandInvariantError");
123 }
124 // Stopped/error sessions are settleable — only live work is protected.
125 const settled = yield* decideOrchestrationCommand({
126 command: {
127 type: "thread.settle",
128 commandId: CommandId.make("cmd-settle-stopped"),
129 threadId: ThreadId.make("thread-1"),
130 },
131 readModel: makeReadModel(null, null, makeSession("stopped")),
132 });
133 const settledEvents = Array.isArray(settled) ? settled : [settled];
134 expect(settledEvents[0]?.type).toBe("thread.settled");
135 }),
136 );
137
138 it.effect("rejects settling a thread with an open approval or user-input request", () =>
139 Effect.gen(function* () {
140 const requestActivity = (kind: string, requestId: string, at: string) =>
141 ({
142 id: EventId.make(`activity-${requestId}-${kind}`),
143 tone: "approval" as const,
144 kind,
145 summary: kind,
146 payload: { requestId },
147 turnId: null,
148 createdAt: at,
149 }) as OrchestrationThread["activities"][number];
150
151 // Open approval request: settle rejected.
152 const openError = yield* decideOrchestrationCommand({
153 command: {
154 type: "thread.settle",
155 commandId: CommandId.make("cmd-settle-pending"),
156 threadId: ThreadId.make("thread-1"),
157 },
158 readModel: makeReadModel(null, null, null, [
159 requestActivity("approval.requested", "req-1", NOW),
160 ]),
161 }).pipe(Effect.flip);
162 expect(openError._tag).toBe("OrchestrationCommandInvariantError");
163
164 // Same request later resolved: settleable again.
165 const settled = yield* decideOrchestrationCommand({
166 command: {
167 type: "thread.settle",
168 commandId: CommandId.make("cmd-settle-resolved"),
169 threadId: ThreadId.make("thread-1"),
170 },
171 readModel: makeReadModel(null, null, null, [
172 requestActivity("approval.requested", "req-1", NOW),
173 requestActivity("approval.resolved", "req-1", NOW),
174 ]),
175 });
176 const settledEvents = Array.isArray(settled) ? settled : [settled];
177 expect(settledEvents[0]?.type).toBe("thread.settled");
178
179 // Open user-input request: also rejected.
180 const inputError = yield* decideOrchestrationCommand({
181 command: {
182 type: "thread.settle",
183 commandId: CommandId.make("cmd-settle-pending-input"),
184 threadId: ThreadId.make("thread-1"),
185 },
186 readModel: makeReadModel(null, null, null, [
187 requestActivity("user-input.requested", "req-2", NOW),
188 ]),
189 }).pipe(Effect.flip);
190 expect(inputError._tag).toBe("OrchestrationCommandInvariantError");
191 }),
192 );
193
194 it.effect("clears an open request when its respond failure marks it stale", () =>
195 Effect.gen(function* () {
196 const activity = (
197 kind: string,
198 requestId: string,
199 payload: Record<string, unknown>,
200 ): OrchestrationThread["activities"][number] =>
201 ({
202 id: EventId.make(`activity-${requestId}-${kind}`),
203 tone: "approval" as const,
204 kind,
205 summary: kind,
206 payload: { requestId, ...payload },
207 turnId: null,
208 createdAt: NOW,
209 }) as OrchestrationThread["activities"][number];
210
211 // Stale-failure detail clears the request — mirrors the projection's
212 // pending accounting, which is what the client's canSettle sees.
213 const settled = yield* decideOrchestrationCommand({
214 command: {
215 type: "thread.settle",
216 commandId: CommandId.make("cmd-settle-stale-failed"),
217 threadId: ThreadId.make("thread-1"),
218 },
219 readModel: makeReadModel(null, null, null, [
220 activity("approval.requested", "req-1", {}),
221 activity("provider.approval.respond.failed", "req-1", {
222 detail: "Unknown pending approval request req-1",
223 }),
224 activity("user-input.requested", "req-2", {}),
225 activity("provider.user-input.respond.failed", "req-2", {
226 detail: "stale pending user-input request req-2",
227 }),
228 ]),
229 });
230 const settledEvents = Array.isArray(settled) ? settled : [settled];
231 expect(settledEvents[0]?.type).toBe("thread.settled");
232
233 // A non-stale respond failure (transient provider error) keeps the
234 // request open: the user can retry, so it is still blocked-on-you.
235 const stillOpen = yield* decideOrchestrationCommand({
236 command: {
237 type: "thread.settle",
238 commandId: CommandId.make("cmd-settle-transient-failed"),
239 threadId: ThreadId.make("thread-1"),
240 },
241 readModel: makeReadModel(null, null, null, [
242 activity("approval.requested", "req-3", {}),
243 activity("provider.approval.respond.failed", "req-3", {
244 detail: "provider connection reset",
245 }),
246 ]),
247 }).pipe(Effect.flip);
248 expect(stillOpen._tag).toBe("OrchestrationCommandInvariantError");
249 }),
250 );
251
252 it.effect("bounds the queued-turn grace window against client clock skew", () =>
253 Effect.gen(function* () {
254 const userMessage = (createdAt: string): OrchestrationThread["messages"][number] => ({
255 id: MessageId.make("message-queued"),
256 role: "user",
257 text: "Continue",
258 turnId: null,
259 streaming: false,
260 createdAt,
261 updatedAt: createdAt,
262 });
263
264 // The decider's clock is the Effect test clock, pinned to the epoch:
265 // timestamps here are relative to 1970-01-01T00:00:00.000Z.
266
267 // Within the grace window: genuinely queued, settle rejected.
268 const queuedError = yield* decideOrchestrationCommand({
269 command: {
270 type: "thread.settle",
271 commandId: CommandId.make("cmd-settle-queued"),
272 threadId: ThreadId.make("thread-1"),
273 },
274 readModel: makeReadModel(null, null, null, [], [userMessage("1969-12-31T23:59:30.000Z")]),
275 }).pipe(Effect.flip);
276 expect(queuedError._tag).toBe("OrchestrationCommandInvariantError");
277
278 // Message timestamp far in the FUTURE (client clock ahead of server):
279 // a negative age must not read as queued forever — past the grace
280 // bound in either direction the thread is settleable.
281 const skewed = yield* decideOrchestrationCommand({
282 command: {
283 type: "thread.settle",
284 commandId: CommandId.make("cmd-settle-skewed"),
285 threadId: ThreadId.make("thread-1"),
286 },
287 readModel: makeReadModel(null, null, null, [], [userMessage("1970-01-01T01:00:00.000Z")]),
288 });
289 const skewedEvents = Array.isArray(skewed) ? skewed : [skewed];
290 expect(skewedEvents[0]?.type).toBe("thread.settled");
291 }),
292 );
293
294 it.effect("rejects settling and unsettling archived threads", () =>
295 Effect.gen(function* () {
296 const settleError = yield* decideOrchestrationCommand({
297 command: {
298 type: "thread.settle",
299 commandId: CommandId.make("cmd-settle-archived"),
300 threadId: ThreadId.make("thread-1"),
301 },
302 readModel: makeReadModel(null, NOW),
303 }).pipe(Effect.flip);
304 expect(settleError._tag).toBe("OrchestrationCommandInvariantError");
305
306 const unsettleError = yield* decideOrchestrationCommand({
307 command: {
308 type: "thread.unsettle",
309 commandId: CommandId.make("cmd-unsettle-archived"),
310 threadId: ThreadId.make("thread-1"),
311 reason: "user",
312 },
313 readModel: makeReadModel("settled", NOW),
314 }).pipe(Effect.flip);
315 expect(unsettleError._tag).toBe("OrchestrationCommandInvariantError");
316 }),
317 );
318
319 it.effect("maps unsettle reasons to overrides and re-emits idempotently", () =>
320 Effect.gen(function* () {
321 const userEvent = yield* decideOrchestrationCommand({
322 command: {
323 type: "thread.unsettle",
324 commandId: CommandId.make("cmd-unsettle-user"),
325 threadId: ThreadId.make("thread-1"),
326 reason: "user",
327 },
328 readModel: makeReadModel("settled"),
329 });
330 const userEvents = Array.isArray(userEvent) ? userEvent : [userEvent];
331 expect(userEvents).toHaveLength(1);
332 expect(userEvents[0]?.type).toBe("thread.unsettled");
333 if (userEvents[0]?.type === "thread.unsettled") {
334 expect(userEvents[0].payload.reason).toBe("user");
335 }
336
337 // Re-dispatching against the already-reached state re-emits rather than
338 // producing zero events (the engine rejects empty commands).
339 const userAgain = yield* decideOrchestrationCommand({
340 command: {
341 type: "thread.unsettle",
342 commandId: CommandId.make("cmd-unsettle-user-again"),
343 threadId: ThreadId.make("thread-1"),
344 reason: "user",
345 },
346 readModel: makeReadModel("active"),
347 });
348 const userAgainEvents = Array.isArray(userAgain) ? userAgain : [userAgain];
349 expect(userAgainEvents).toHaveLength(1);
350 expect(userAgainEvents[0]?.type).toBe("thread.unsettled");
351 }),
352 );
353
354 it.effect("prepends activity unsets for turn starts and live session updates", () =>
355 Effect.gen(function* () {
356 const turnResult = yield* decideOrchestrationCommand({
357 command: {
358 type: "thread.turn.start",
359 commandId: CommandId.make("cmd-turn-start"),
360 threadId: ThreadId.make("thread-1"),
361 message: {
362 messageId: MessageId.make("message-1"),
363 role: "user",
364 text: "Continue",
365 attachments: [],
366 },
367 runtimeMode: "full-access",
368 interactionMode: "default",
369 createdAt: NOW,
370 },
371 readModel: makeReadModel("settled"),
372 });
373 const turnEvents = Array.isArray(turnResult) ? turnResult : [turnResult];
374 expect(turnEvents.map((event) => event.type)).toEqual([
375 "thread.unsettled",
376 "thread.message-sent",
377 "thread.turn-start-requested",
378 ]);
379
380 const sessionResult = yield* decideOrchestrationCommand({
381 command: {
382 type: "thread.session.set",
383 commandId: CommandId.make("cmd-session-set"),
384 threadId: ThreadId.make("thread-1"),
385 session: makeSession("running"),
386 createdAt: NOW,
387 },
388 // A keep-active pin is also an override: real activity clears it
389 // back to neutral so auto-settle can apply again later.
390 readModel: makeReadModel("active"),
391 });
392 const sessionEvents = Array.isArray(sessionResult) ? sessionResult : [sessionResult];
393 expect(sessionEvents.map((event) => event.type)).toEqual([
394 "thread.unsettled",
395 "thread.session-set",
396 ]);
397 }),
398 );
399
400 it.effect("clears a keep-active pin on real activity", () =>
401 Effect.gen(function* () {
402 const turnResult = yield* decideOrchestrationCommand({
403 command: {
404 type: "thread.turn.start",
405 commandId: CommandId.make("cmd-active-turn-start"),
406 threadId: ThreadId.make("thread-1"),
407 message: {
408 messageId: MessageId.make("message-active"),
409 role: "user",
410 text: "Continue",
411 attachments: [],
412 },
413 runtimeMode: "full-access",
414 interactionMode: "default",
415 createdAt: NOW,
416 },
417 readModel: makeReadModel("active"),
418 });
419 const turnEvents = Array.isArray(turnResult) ? turnResult : [turnResult];
420 // The pin exists to suppress AUTO-settle, not to survive real work:
421 // activity resets it to neutral, restoring the default lifecycle.
422 expect(turnEvents.map((event) => event.type)).toEqual([
423 "thread.unsettled",
424 "thread.message-sent",
425 "thread.turn-start-requested",
426 ]);
427
428 const activityResult = yield* decideOrchestrationCommand({
429 command: {
430 type: "thread.activity.append",
431 commandId: CommandId.make("cmd-active-approval"),
432 threadId: ThreadId.make("thread-1"),
433 activity: {
434 id: EventId.make("activity-active"),
435 tone: "approval",
436 kind: "approval.requested",
437 summary: "Command approval requested",
438 payload: null,
439 turnId: null,
440 createdAt: NOW,
441 },
442 createdAt: NOW,
443 },
444 readModel: makeReadModel("active"),
445 });
446 const activityEvents = Array.isArray(activityResult) ? activityResult : [activityResult];
447 expect(activityEvents.map((event) => event.type)).toEqual([
448 "thread.unsettled",
449 "thread.activity-appended",
450 ]);
451 }),
452 );
453
454 it.effect("does not unsettle for session stop/error status writes", () =>
455 Effect.gen(function* () {
456 for (const status of ["stopped", "error", "ready", "idle"] as const) {
457 const result = yield* decideOrchestrationCommand({
458 command: {
459 type: "thread.session.set",
460 commandId: CommandId.make(`cmd-session-${status}`),
461 threadId: ThreadId.make("thread-1"),
462 session: makeSession(status),
463 createdAt: NOW,
464 },
465 readModel: makeReadModel("settled"),
466 });
467 const events = Array.isArray(result) ? result : [result];
468 expect(events.map((event) => event.type)).toEqual(["thread.session-set"]);
469 }
470 }),
471 );
472
473 it.effect("unsettles for approval and user-input activities but not others", () =>
474 Effect.gen(function* () {
475 const approvalResult = yield* decideOrchestrationCommand({
476 command: {
477 type: "thread.activity.append",
478 commandId: CommandId.make("cmd-activity-approval"),
479 threadId: ThreadId.make("thread-1"),
480 activity: {
481 id: EventId.make("activity-1"),
482 tone: "approval",
483 kind: "approval.requested",
484 summary: "Command approval requested",
485 payload: null,
486 turnId: null,
487 createdAt: NOW,
488 },
489 createdAt: NOW,
490 },
491 readModel: makeReadModel("settled"),
492 });
493 const approvalEvents = Array.isArray(approvalResult) ? approvalResult : [approvalResult];
494 expect(approvalEvents.map((event) => event.type)).toEqual([
495 "thread.unsettled",
496 "thread.activity-appended",
497 ]);
498
499 const routineResult = yield* decideOrchestrationCommand({
500 command: {
501 type: "thread.activity.append",
502 commandId: CommandId.make("cmd-activity-routine"),
503 threadId: ThreadId.make("thread-1"),
504 activity: {
505 id: EventId.make("activity-2"),
506 tone: "info",
507 kind: "tool.completed",
508 summary: "Tool completed",
509 payload: null,
510 turnId: null,
511 createdAt: NOW,
512 },
513 createdAt: NOW,
514 },
515 readModel: makeReadModel("settled"),
516 });
517 const routineEvents = Array.isArray(routineResult) ? routineResult : [routineResult];
518 expect(routineEvents.map((event) => event.type)).toEqual(["thread.activity-appended"]);
519 }),
520 );
521
522 it.effect("drops an onlyIfSettled session stop when the thread was re-engaged", () =>
523 Effect.gen(function* () {
524 const stopCommand = (commandId: string) =>
525 ({
526 type: "thread.session.stop",
527 commandId: CommandId.make(commandId),
528 threadId: ThreadId.make("thread-1"),
529 createdAt: NOW,
530 onlyIfSettled: true,
531 }) as const;
532
533 // Still settled with an idle session: the cleanup stop goes through.
534 const stopped = yield* decideOrchestrationCommand({
535 command: stopCommand("cmd-stop-settled-idle"),
536 readModel: makeReadModel("settled", null, makeSession("ready")),
537 });
538 const stoppedEvents = Array.isArray(stopped) ? stopped : [stopped];
539 expect(stoppedEvents.map((event) => event.type)).toEqual(["thread.session-stop-requested"]);
540
541 // Re-engaged before the stop was decided (a turn start unsettles the
542 // thread): the stale cleanup stop must not kill the new session.
543 const unsettledError = yield* decideOrchestrationCommand({
544 command: stopCommand("cmd-stop-unsettled"),
545 readModel: makeReadModel(null, null, makeSession("starting")),
546 }).pipe(Effect.flip);
547 expect(unsettledError._tag).toBe("OrchestrationCommandInvariantError");
548
549 // Still settled but the session is already coming alive: same drop.
550 const aliveError = yield* decideOrchestrationCommand({
551 command: stopCommand("cmd-stop-session-alive"),
552 readModel: makeReadModel("settled", null, makeSession("starting")),
553 }).pipe(Effect.flip);
554 expect(aliveError._tag).toBe("OrchestrationCommandInvariantError");
555
556 // Without the flag the stop stays unconditional (archive, stop button).
557 const unconditional = yield* decideOrchestrationCommand({
558 command: {
559 type: "thread.session.stop",
560 commandId: CommandId.make("cmd-stop-unconditional"),
561 threadId: ThreadId.make("thread-1"),
562 createdAt: NOW,
563 },
564 readModel: makeReadModel(null, null, makeSession("starting")),
565 });
566 const unconditionalEvents = Array.isArray(unconditional) ? unconditional : [unconditional];
567 expect(unconditionalEvents.map((event) => event.type)).toEqual([
568 "thread.session-stop-requested",
569 ]);
570 }),
571 );
572});