Open History to see the last commit
1import {
2 CommandId,
3 EventId,
4 MessageId,
5 ProjectId,
6 ProviderInstanceId,
7 ThreadId,
8 TurnId,
9 OrchestrationProposedPlanId,
10 type OrchestrationEvent,
11 type OrchestrationReadModel,
12 type OrchestrationSession,
13 type OrchestrationThread,
14} from "@t3tools/contracts";
15import * as NodeServices from "@effect/platform-node/NodeServices";
16import { expect, it } from "@effect/vitest";
17import * as Effect from "effect/Effect";
18
19import { decideOrchestrationCommand } from "./decider.ts";
20import { projectEvent } from "./projector.ts";
21
22const NOW = "2026-01-01T00:00:00.000Z";
23const SETTLED_AT = "2025-12-30T00:00:00.000Z";
24const SETTLE_BLOCKED_MESSAGE =
25 "This thread still needs attention. Resolve or interrupt it first, then try again.";
26
27function makeReadModel(
28 settledOverride: OrchestrationThread["settledOverride"],
29 archivedAt: string | null = null,
30 session: OrchestrationSession | null = null,
31 activities: OrchestrationThread["activities"] = [],
32 messages: OrchestrationThread["messages"] = [],
33 lifecycle: {
34 readonly pinnedAt?: string | null;
35 readonly snoozedUntil?: string | null;
36 readonly snoozedAt?: string | null;
37 } = {},
38 latestTurn: OrchestrationThread["latestTurn"] = null,
39): OrchestrationReadModel {
40 return {
41 snapshotSequence: 0,
42 projects: [],
43 threads: [
44 {
45 id: ThreadId.make("thread-1"),
46 projectId: ProjectId.make("project-1"),
47 title: "Thread",
48 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
49 runtimeMode: "full-access",
50 interactionMode: "default",
51 branch: null,
52 worktreePath: null,
53 pullRequests: [],
54 latestTurn,
55 createdAt: NOW,
56 updatedAt: NOW,
57 archivedAt,
58 settledOverride,
59 settledAt: settledOverride === "settled" ? SETTLED_AT : null,
60 snoozedUntil: lifecycle.snoozedUntil ?? null,
61 snoozedAt: lifecycle.snoozedAt ?? (lifecycle.snoozedUntil != null ? SETTLED_AT : null),
62 pinnedAt: lifecycle.pinnedAt ?? null,
63 deletedAt: null,
64 messages,
65 proposedPlans: [],
66 activities,
67 checkpoints: [],
68 session,
69 },
70 ],
71 updatedAt: NOW,
72 };
73}
74
75function makeSession(status: OrchestrationSession["status"]): OrchestrationSession {
76 return {
77 threadId: ThreadId.make("thread-1"),
78 status,
79 providerName: "Codex",
80 runtimeMode: "full-access",
81 activeTurnId: null,
82 lastError: null,
83 updatedAt: NOW,
84 };
85}
86
87const projectQueuedTurnStart = Effect.fn("projectQueuedTurnStart")(function* (
88 messageId: MessageId,
89 createdAt: string,
90) {
91 let readModel = makeReadModel(null);
92 const result = yield* decideOrchestrationCommand({
93 command: {
94 type: "thread.turn.start",
95 commandId: CommandId.make(`cmd-start-${messageId}`),
96 threadId: ThreadId.make("thread-1"),
97 message: {
98 messageId,
99 role: "user",
100 text: "Continue",
101 attachments: [],
102 },
103 runtimeMode: "full-access",
104 interactionMode: "default",
105 createdAt,
106 },
107 readModel,
108 });
109 const events = Array.isArray(result) ? result : [result];
110 for (const [index, event] of events.entries()) {
111 readModel = yield* projectEvent(readModel, { ...event, sequence: index + 1 });
112 }
113 return readModel;
114});
115
116it.layer(NodeServices.layer)("settled thread decider", (it) => {
117 it.effect("preserves the activity stamp when automatically settling", () =>
118 Effect.gen(function* () {
119 const result = yield* decideOrchestrationCommand({
120 command: {
121 type: "thread.auto-settle",
122 commandId: CommandId.make("cmd-auto-settle-inactive"),
123 threadId: ThreadId.make("thread-1"),
124 snapshotSequence: 0,
125 settledAt: SETTLED_AT,
126 },
127 readModel: makeReadModel(null),
128 });
129 const events = Array.isArray(result) ? result : [result];
130 const settled = events.find((event) => event.type === "thread.settled");
131 expect(settled?.payload.settledAt).toBe(SETTLED_AT);
132 // updatedAt stays the command time so the row still moves on settle.
133 expect(settled?.payload.updatedAt).toBe(settled?.occurredAt);
134 expect(settled?.payload.updatedAt).not.toBe(SETTLED_AT);
135 }),
136 );
137
138 it.effect("rejects an automatic settle when the thread is pinned active", () =>
139 Effect.gen(function* () {
140 const command = {
141 type: "thread.auto-settle" as const,
142 commandId: CommandId.make("cmd-auto-settle"),
143 threadId: ThreadId.make("thread-1"),
144 snapshotSequence: 0,
145 settledAt: SETTLED_AT,
146 };
147 const pinnedActive = yield* decideOrchestrationCommand({
148 command,
149 readModel: makeReadModel("active"),
150 }).pipe(Effect.flip);
151 expect(pinnedActive._tag).toBe("OrchestrationCommandInvariantError");
152 }),
153 );
154
155 it.effect("settles awake threads without a redundant wake and re-emits idempotently", () =>
156 Effect.gen(function* () {
157 const event = yield* decideOrchestrationCommand({
158 command: {
159 type: "thread.settle",
160 commandId: CommandId.make("cmd-settle"),
161 threadId: ThreadId.make("thread-1"),
162 },
163 readModel: makeReadModel(null),
164 });
165 const events = Array.isArray(event) ? event : [event];
166 expect(events).toHaveLength(1);
167 expect(events[0]?.type).toBe("thread.settled");
168 if (events[0]?.type === "thread.settled") {
169 expect(events[0].payload.settledAt).toBe(events[0].payload.updatedAt);
170 }
171
172 // Already settled: the engine rejects zero-event commands, so idempotency
173 // is by re-emission — preserving the original settledAt.
174 const reEmit = yield* decideOrchestrationCommand({
175 command: {
176 type: "thread.settle",
177 commandId: CommandId.make("cmd-settle-again"),
178 threadId: ThreadId.make("thread-1"),
179 },
180 readModel: makeReadModel("settled"),
181 });
182 const reEmitEvents = Array.isArray(reEmit) ? reEmit : [reEmit];
183 expect(reEmitEvents).toHaveLength(1);
184 expect(reEmitEvents[0]?.type).toBe("thread.settled");
185 if (reEmitEvents[0]?.type === "thread.settled") {
186 expect(reEmitEvents[0].payload.settledAt).toBe(SETTLED_AT);
187 // updatedAt must NOT rewind to the historical settledAt: sorting and
188 // relative-time labels key on it.
189 expect(reEmitEvents[0].payload.updatedAt).not.toBe(SETTLED_AT);
190 }
191 }),
192 );
193
194 it.effect("settling a snoozed thread also wakes it", () =>
195 Effect.gen(function* () {
196 const result = yield* decideOrchestrationCommand({
197 command: {
198 type: "thread.settle",
199 commandId: CommandId.make("cmd-settle-snoozed"),
200 threadId: ThreadId.make("thread-1"),
201 },
202 readModel: makeReadModel(null, null, null, [], [], {
203 snoozedUntil: "1970-01-02T09:00:00.000Z",
204 }),
205 });
206 const events = Array.isArray(result) ? result : [result];
207 expect(events.map((entry) => entry.type)).toEqual(["thread.settled", "thread.unsnoozed"]);
208 const settled = events.find((entry) => entry.type === "thread.settled");
209 const unsnoozed = events.find((entry) => entry.type === "thread.unsnoozed");
210 if (settled?.type === "thread.settled" && unsnoozed?.type === "thread.unsnoozed") {
211 expect(unsnoozed.payload.reason).toBe("user");
212 expect(unsnoozed.payload.updatedAt).toBe(settled.payload.updatedAt);
213 }
214 }),
215 );
216
217 it.effect("repeated settle repairs legacy settled and snoozed state", () =>
218 Effect.gen(function* () {
219 const result = yield* decideOrchestrationCommand({
220 command: {
221 type: "thread.settle",
222 commandId: CommandId.make("cmd-settle-snoozed-again"),
223 threadId: ThreadId.make("thread-1"),
224 },
225 readModel: makeReadModel("settled", null, null, [], [], {
226 snoozedUntil: "1970-01-02T09:00:00.000Z",
227 }),
228 });
229 const events = Array.isArray(result) ? result : [result];
230 expect(events.map((entry) => entry.type)).toEqual(["thread.settled", "thread.unsnoozed"]);
231 const settled = events.find((entry) => entry.type === "thread.settled");
232 const unsnoozed = events.find((entry) => entry.type === "thread.unsnoozed");
233 if (settled?.type === "thread.settled" && unsnoozed?.type === "thread.unsnoozed") {
234 expect(settled.payload.settledAt).toBe(SETTLED_AT);
235 expect(settled.payload.updatedAt).toBe(NOW);
236 expect(unsnoozed.payload.updatedAt).not.toBe(NOW);
237 }
238 }),
239 );
240
241 it.effect("settling a pinned and snoozed thread clears the pin and snooze", () =>
242 Effect.gen(function* () {
243 const result = yield* decideOrchestrationCommand({
244 command: {
245 type: "thread.settle",
246 commandId: CommandId.make("cmd-settle-pinned-snoozed"),
247 threadId: ThreadId.make("thread-1"),
248 },
249 readModel: makeReadModel(null, null, null, [], [], {
250 pinnedAt: SETTLED_AT,
251 snoozedUntil: "1970-01-02T09:00:00.000Z",
252 }),
253 });
254 const events = Array.isArray(result) ? result : [result];
255 expect(events.map((entry) => entry.type)).toEqual([
256 "thread.settled",
257 "thread.unpinned",
258 "thread.unsnoozed",
259 ]);
260 }),
261 );
262
263 it.effect("rejects settling a thread with a live session", () =>
264 Effect.gen(function* () {
265 for (const status of ["starting", "running"] as const) {
266 const error = yield* decideOrchestrationCommand({
267 command: {
268 type: "thread.settle",
269 commandId: CommandId.make(`cmd-settle-live-${status}`),
270 threadId: ThreadId.make("thread-1"),
271 },
272 readModel: makeReadModel(null, null, makeSession(status)),
273 }).pipe(Effect.flip);
274 expect(error).toMatchObject({
275 _tag: "OrchestrationThreadSettleBlockedError",
276 threadId: ThreadId.make("thread-1"),
277 message: SETTLE_BLOCKED_MESSAGE,
278 });
279 }
280 // Stopped/error sessions are settleable — only live work is protected.
281 const settled = yield* decideOrchestrationCommand({
282 command: {
283 type: "thread.settle",
284 commandId: CommandId.make("cmd-settle-stopped"),
285 threadId: ThreadId.make("thread-1"),
286 },
287 readModel: makeReadModel(null, null, makeSession("stopped")),
288 });
289 const settledEvents = Array.isArray(settled) ? settled : [settled];
290 expect(settledEvents[0]?.type).toBe("thread.settled");
291 }),
292 );
293
294 it.effect("rejects settling a thread with an open approval or user-input request", () =>
295 Effect.gen(function* () {
296 const requestActivity = (kind: string, requestId: string, at: string) =>
297 ({
298 id: EventId.make(`activity-${requestId}-${kind}`),
299 tone: "approval" as const,
300 kind,
301 summary: kind,
302 payload: { requestId },
303 turnId: null,
304 createdAt: at,
305 }) as OrchestrationThread["activities"][number];
306
307 // Open approval request: settle rejected.
308 const openError = yield* decideOrchestrationCommand({
309 command: {
310 type: "thread.settle",
311 commandId: CommandId.make("cmd-settle-pending"),
312 threadId: ThreadId.make("thread-1"),
313 },
314 readModel: makeReadModel(null, null, null, [
315 requestActivity("approval.requested", "req-1", NOW),
316 ]),
317 }).pipe(Effect.flip);
318 expect(openError).toMatchObject({
319 _tag: "OrchestrationThreadSettleBlockedError",
320 threadId: ThreadId.make("thread-1"),
321 message: SETTLE_BLOCKED_MESSAGE,
322 });
323
324 // Same request later resolved: settleable again.
325 const settled = yield* decideOrchestrationCommand({
326 command: {
327 type: "thread.settle",
328 commandId: CommandId.make("cmd-settle-resolved"),
329 threadId: ThreadId.make("thread-1"),
330 },
331 readModel: makeReadModel(null, null, null, [
332 requestActivity("approval.requested", "req-1", NOW),
333 requestActivity("approval.resolved", "req-1", NOW),
334 ]),
335 });
336 const settledEvents = Array.isArray(settled) ? settled : [settled];
337 expect(settledEvents[0]?.type).toBe("thread.settled");
338
339 // Open user-input request: also rejected.
340 const inputError = yield* decideOrchestrationCommand({
341 command: {
342 type: "thread.settle",
343 commandId: CommandId.make("cmd-settle-pending-input"),
344 threadId: ThreadId.make("thread-1"),
345 },
346 readModel: makeReadModel(null, null, null, [
347 requestActivity("user-input.requested", "req-2", NOW),
348 ]),
349 }).pipe(Effect.flip);
350 expect(inputError).toMatchObject({
351 _tag: "OrchestrationThreadSettleBlockedError",
352 threadId: ThreadId.make("thread-1"),
353 message: SETTLE_BLOCKED_MESSAGE,
354 });
355 }),
356 );
357
358 it.effect("manual settlement dismisses async questions without starting a turn", () =>
359 Effect.gen(function* () {
360 const question = (requestId: string): OrchestrationThread["activities"][number] => ({
361 id: EventId.make(requestId),
362 kind: "user-input.requested",
363 summary: "Question",
364 tone: "approval",
365 turnId: null,
366 createdAt: "1969-12-31T00:00:00.000Z",
367 payload: { requestId, responseMode: "message" },
368 });
369 const readModel = makeReadModel(null, null, makeSession("ready"), [
370 question("first"),
371 question("second"),
372 question("answered"),
373 {
374 ...question("answered"),
375 id: EventId.make("answer"),
376 createdAt: "1969-12-31T01:00:00.000Z",
377 kind: "user-input.resolved",
378 },
379 ]);
380 const command = {
381 type: "thread.settle" as const,
382 commandId: CommandId.make("settle-async"),
383 threadId: ThreadId.make("thread-1"),
384 };
385 const result = yield* decideOrchestrationCommand({ command, readModel });
386 const events = Array.isArray(result) ? result : [result];
387 expect(events.map((event) => event.type)).toEqual([
388 "thread.settled",
389 "thread.activity-appended",
390 "thread.activity-appended",
391 ]);
392 expect(events.slice(1).map((event) => event.payload)).toEqual(
393 ["first", "second"].map((requestId) => ({
394 threadId: command.threadId,
395 activity: expect.objectContaining({
396 kind: "user-input.resolved",
397 summary: "User input dismissed",
398 payload: { requestId, responseMode: "message" },
399 }),
400 })),
401 );
402 let projected = readModel;
403 for (const [index, event] of events.entries()) {
404 projected = yield* projectEvent(projected, { ...event, sequence: index + 1 });
405 }
406 expect(projected.threads[0]?.settledOverride).toBe("settled");
407 expect(projected.threads[0]?.messages).toEqual([]);
408 const repeated = yield* decideOrchestrationCommand({ command, readModel: projected });
409 expect(repeated).toMatchObject({ type: "thread.settled" });
410 }),
411 );
412
413 it.effect("async questions do not bypass automatic settlement or other blockers", () =>
414 Effect.gen(function* () {
415 const question: OrchestrationThread["activities"][number] = {
416 id: EventId.make("async-question"),
417 kind: "user-input.requested",
418 summary: "Question",
419 tone: "approval",
420 turnId: null,
421 createdAt: NOW,
422 payload: { requestId: "async-question", responseMode: "message" },
423 };
424 for (const blocker of ["auto", "running", "starting", "approval", "native"] as const) {
425 const error = yield* decideOrchestrationCommand({
426 command:
427 blocker === "auto"
428 ? {
429 type: "thread.auto-settle",
430 commandId: CommandId.make(`settle-${blocker}`),
431 threadId: ThreadId.make("thread-1"),
432 snapshotSequence: 0,
433 settledAt: NOW,
434 }
435 : {
436 type: "thread.settle",
437 commandId: CommandId.make(`settle-${blocker}`),
438 threadId: ThreadId.make("thread-1"),
439 },
440 readModel: makeReadModel(
441 null,
442 null,
443 makeSession(blocker === "running" || blocker === "starting" ? blocker : "ready"),
444 [
445 question,
446 ...(blocker === "approval" || blocker === "native"
447 ? [
448 {
449 ...question,
450 id: EventId.make("blocking-request"),
451 kind: blocker === "approval" ? "approval.requested" : "user-input.requested",
452 payload: { requestId: "blocking-request" },
453 },
454 ]
455 : []),
456 ],
457 ),
458 }).pipe(Effect.flip);
459 expect(error).toMatchObject({ _tag: "OrchestrationThreadSettleBlockedError" });
460 }
461 }),
462 );
463
464 it.effect("clears an open request when its respond failure marks it stale", () =>
465 Effect.gen(function* () {
466 const activity = (
467 kind: string,
468 requestId: string,
469 payload: Record<string, unknown>,
470 ): OrchestrationThread["activities"][number] =>
471 ({
472 id: EventId.make(`activity-${requestId}-${kind}`),
473 tone: "approval" as const,
474 kind,
475 summary: kind,
476 payload: { requestId, ...payload },
477 turnId: null,
478 createdAt: NOW,
479 }) as OrchestrationThread["activities"][number];
480
481 // Stale-failure details clear the request, matching the projection flags.
482 const settled = yield* decideOrchestrationCommand({
483 command: {
484 type: "thread.settle",
485 commandId: CommandId.make("cmd-settle-stale-failed"),
486 threadId: ThreadId.make("thread-1"),
487 },
488 readModel: makeReadModel(null, null, null, [
489 activity("approval.requested", "req-1", {}),
490 activity("provider.approval.respond.failed", "req-1", {
491 detail: "Unknown pending approval request req-1",
492 }),
493 activity("user-input.requested", "req-2", {}),
494 activity("provider.user-input.respond.failed", "req-2", {
495 detail: "stale pending user-input request req-2",
496 }),
497 ]),
498 });
499 const settledEvents = Array.isArray(settled) ? settled : [settled];
500 expect(settledEvents[0]?.type).toBe("thread.settled");
501
502 // A non-stale respond failure (transient provider error) keeps the
503 // request open: the user can retry, so it is still blocked-on-you.
504 const stillOpen = yield* decideOrchestrationCommand({
505 command: {
506 type: "thread.settle",
507 commandId: CommandId.make("cmd-settle-transient-failed"),
508 threadId: ThreadId.make("thread-1"),
509 },
510 readModel: makeReadModel(null, null, null, [
511 activity("approval.requested", "req-3", {}),
512 activity("provider.approval.respond.failed", "req-3", {
513 detail: "provider connection reset",
514 }),
515 ]),
516 }).pipe(Effect.flip);
517 expect(stillOpen).toMatchObject({
518 _tag: "OrchestrationThreadSettleBlockedError",
519 threadId: ThreadId.make("thread-1"),
520 message: SETTLE_BLOCKED_MESSAGE,
521 });
522 }),
523 );
524
525 it.effect("bounds the queued-turn grace window against client clock skew", () =>
526 Effect.gen(function* () {
527 const userMessage = (createdAt: string): OrchestrationThread["messages"][number] => ({
528 id: MessageId.make("message-queued"),
529 role: "user",
530 text: "Continue",
531 turnId: null,
532 streaming: false,
533 createdAt,
534 updatedAt: createdAt,
535 });
536
537 // The decider's clock is the Effect test clock, pinned to the epoch:
538 // timestamps here are relative to 1970-01-01T00:00:00.000Z.
539
540 // Within the grace window: genuinely queued, settle rejected.
541 const queuedError = yield* decideOrchestrationCommand({
542 command: {
543 type: "thread.settle",
544 commandId: CommandId.make("cmd-settle-queued"),
545 threadId: ThreadId.make("thread-1"),
546 },
547 readModel: makeReadModel(null, null, null, [], [userMessage("1969-12-31T23:59:30.000Z")]),
548 }).pipe(Effect.flip);
549 expect(queuedError).toMatchObject({
550 _tag: "OrchestrationThreadSettleBlockedError",
551 threadId: ThreadId.make("thread-1"),
552 message: SETTLE_BLOCKED_MESSAGE,
553 });
554
555 // Message timestamp far in the FUTURE (client clock ahead of server):
556 // a negative age must not read as queued forever — past the grace
557 // bound in either direction the thread is settleable.
558 const skewed = yield* decideOrchestrationCommand({
559 command: {
560 type: "thread.settle",
561 commandId: CommandId.make("cmd-settle-skewed"),
562 threadId: ThreadId.make("thread-1"),
563 },
564 readModel: makeReadModel(null, null, null, [], [userMessage("1970-01-01T01:00:00.000Z")]),
565 });
566 const skewedEvents = Array.isArray(skewed) ? skewed : [skewed];
567 expect(skewedEvents[0]?.type).toBe("thread.settled");
568 }),
569 );
570
571 it.effect("rejects settling and unsettling archived threads", () =>
572 Effect.gen(function* () {
573 const settleError = yield* decideOrchestrationCommand({
574 command: {
575 type: "thread.settle",
576 commandId: CommandId.make("cmd-settle-archived"),
577 threadId: ThreadId.make("thread-1"),
578 },
579 readModel: makeReadModel(null, NOW),
580 }).pipe(Effect.flip);
581 expect(settleError._tag).toBe("OrchestrationCommandInvariantError");
582
583 const unsettleError = yield* decideOrchestrationCommand({
584 command: {
585 type: "thread.unsettle",
586 commandId: CommandId.make("cmd-unsettle-archived"),
587 threadId: ThreadId.make("thread-1"),
588 reason: "user",
589 },
590 readModel: makeReadModel("settled", NOW),
591 }).pipe(Effect.flip);
592 expect(unsettleError._tag).toBe("OrchestrationCommandInvariantError");
593 }),
594 );
595
596 it.effect("maps unsettle reasons to overrides and re-emits idempotently", () =>
597 Effect.gen(function* () {
598 const userEvent = yield* decideOrchestrationCommand({
599 command: {
600 type: "thread.unsettle",
601 commandId: CommandId.make("cmd-unsettle-user"),
602 threadId: ThreadId.make("thread-1"),
603 reason: "user",
604 },
605 readModel: makeReadModel("settled"),
606 });
607 const userEvents = Array.isArray(userEvent) ? userEvent : [userEvent];
608 expect(userEvents).toHaveLength(1);
609 expect(userEvents[0]?.type).toBe("thread.unsettled");
610 if (userEvents[0]?.type === "thread.unsettled") {
611 expect(userEvents[0].payload.reason).toBe("user");
612 }
613
614 // Re-dispatching against the already-reached state re-emits rather than
615 // producing zero events (the engine rejects empty commands).
616 const userAgain = yield* decideOrchestrationCommand({
617 command: {
618 type: "thread.unsettle",
619 commandId: CommandId.make("cmd-unsettle-user-again"),
620 threadId: ThreadId.make("thread-1"),
621 reason: "user",
622 },
623 readModel: makeReadModel("active"),
624 });
625 const userAgainEvents = Array.isArray(userAgain) ? userAgain : [userAgain];
626 expect(userAgainEvents).toHaveLength(1);
627 expect(userAgainEvents[0]?.type).toBe("thread.unsettled");
628 }),
629 );
630
631 // Command-to-projection: an accepted un-settle must land as the re-entry
632 // stamp clients sort by (max of createdAt and unsettledAt, see
633 // activeThreadAnchorTimestampMs in client-runtime), so the thread surfaces
634 // above threads created after it. The projector tests feed events directly;
635 // this one proves the decider actually emits what they consume.
636 it.effect("an accepted un-settle re-anchors the thread for the active list", () =>
637 Effect.gen(function* () {
638 const readModel = makeReadModel("settled");
639 const result = yield* decideOrchestrationCommand({
640 command: {
641 type: "thread.unsettle",
642 commandId: CommandId.make("cmd-unsettle-anchor"),
643 threadId: ThreadId.make("thread-1"),
644 reason: "user",
645 },
646 readModel,
647 });
648 const events = Array.isArray(result) ? result : [result];
649 const unsettled = events[0]!;
650 expect(unsettled.type).toBe("thread.unsettled");
651
652 const projected = yield* projectEvent(readModel, {
653 ...unsettled,
654 sequence: readModel.snapshotSequence + 1,
655 } as OrchestrationEvent);
656 const thread = projected.threads[0]!;
657 expect(thread.settledOverride).toBe("active");
658 // The stamp is the decider's accept time: every thread created before
659 // the un-settle anchors below it.
660 expect(thread.unsettledAt).toBe(unsettled.occurredAt);
661 if (unsettled.type === "thread.unsettled") {
662 expect(thread.unsettledAt).toBe(unsettled.payload.updatedAt);
663 }
664 }),
665 );
666
667 it.effect("prepends activity unsets for turn starts and live session updates", () =>
668 Effect.gen(function* () {
669 const turnResult = yield* decideOrchestrationCommand({
670 command: {
671 type: "thread.turn.start",
672 commandId: CommandId.make("cmd-turn-start"),
673 threadId: ThreadId.make("thread-1"),
674 message: {
675 messageId: MessageId.make("message-1"),
676 role: "user",
677 text: "Continue",
678 attachments: [],
679 },
680 runtimeMode: "full-access",
681 interactionMode: "default",
682 createdAt: NOW,
683 },
684 readModel: makeReadModel("settled"),
685 });
686 const turnEvents = Array.isArray(turnResult) ? turnResult : [turnResult];
687 expect(turnEvents.map((event) => event.type)).toEqual([
688 "thread.unsettled",
689 "thread.message-sent",
690 "thread.turn-start-requested",
691 ]);
692
693 const sessionResult = yield* decideOrchestrationCommand({
694 command: {
695 type: "thread.session.set",
696 commandId: CommandId.make("cmd-session-set"),
697 threadId: ThreadId.make("thread-1"),
698 session: makeSession("running"),
699 createdAt: NOW,
700 },
701 // A keep-active pin is also an override: real activity clears it
702 // back to neutral so auto-settle can apply again later.
703 readModel: makeReadModel("active"),
704 });
705 const sessionEvents = Array.isArray(sessionResult) ? sessionResult : [sessionResult];
706 expect(sessionEvents.map((event) => event.type)).toEqual([
707 "thread.unsettled",
708 "thread.session-set",
709 ]);
710 }),
711 );
712
713 it.effect("clears a keep-active pin on real activity", () =>
714 Effect.gen(function* () {
715 const turnResult = yield* decideOrchestrationCommand({
716 command: {
717 type: "thread.turn.start",
718 commandId: CommandId.make("cmd-active-turn-start"),
719 threadId: ThreadId.make("thread-1"),
720 message: {
721 messageId: MessageId.make("message-active"),
722 role: "user",
723 text: "Continue",
724 attachments: [],
725 },
726 runtimeMode: "full-access",
727 interactionMode: "default",
728 createdAt: NOW,
729 },
730 readModel: makeReadModel("active"),
731 });
732 const turnEvents = Array.isArray(turnResult) ? turnResult : [turnResult];
733 // The pin exists to suppress AUTO-settle, not to survive real work:
734 // activity resets it to neutral, restoring the default lifecycle.
735 expect(turnEvents.map((event) => event.type)).toEqual([
736 "thread.unsettled",
737 "thread.message-sent",
738 "thread.turn-start-requested",
739 ]);
740
741 const activityResult = yield* decideOrchestrationCommand({
742 command: {
743 type: "thread.activity.append",
744 commandId: CommandId.make("cmd-active-approval"),
745 threadId: ThreadId.make("thread-1"),
746 activity: {
747 id: EventId.make("activity-active"),
748 tone: "approval",
749 kind: "approval.requested",
750 summary: "Command approval requested",
751 payload: null,
752 turnId: null,
753 createdAt: NOW,
754 },
755 createdAt: NOW,
756 },
757 readModel: makeReadModel("active"),
758 });
759 const activityEvents = Array.isArray(activityResult) ? activityResult : [activityResult];
760 expect(activityEvents.map((event) => event.type)).toEqual([
761 "thread.unsettled",
762 "thread.activity-appended",
763 ]);
764 }),
765 );
766
767 it.effect("does not unsettle for session stop/error status writes", () =>
768 Effect.gen(function* () {
769 for (const status of ["stopped", "error", "ready", "idle"] as const) {
770 const result = yield* decideOrchestrationCommand({
771 command: {
772 type: "thread.session.set",
773 commandId: CommandId.make(`cmd-session-${status}`),
774 threadId: ThreadId.make("thread-1"),
775 session: makeSession(status),
776 createdAt: NOW,
777 },
778 readModel: makeReadModel("settled"),
779 });
780 const events = Array.isArray(result) ? result : [result];
781 expect(events.map((event) => event.type)).toEqual(["thread.session-set"]);
782 }
783 }),
784 );
785
786 it.effect("unsettles for approval and user-input activities but not others", () =>
787 Effect.gen(function* () {
788 const approvalResult = yield* decideOrchestrationCommand({
789 command: {
790 type: "thread.activity.append",
791 commandId: CommandId.make("cmd-activity-approval"),
792 threadId: ThreadId.make("thread-1"),
793 activity: {
794 id: EventId.make("activity-1"),
795 tone: "approval",
796 kind: "approval.requested",
797 summary: "Command approval requested",
798 payload: null,
799 turnId: null,
800 createdAt: NOW,
801 },
802 createdAt: NOW,
803 },
804 readModel: makeReadModel("settled"),
805 });
806 const approvalEvents = Array.isArray(approvalResult) ? approvalResult : [approvalResult];
807 expect(approvalEvents.map((event) => event.type)).toEqual([
808 "thread.unsettled",
809 "thread.activity-appended",
810 ]);
811
812 const routineResult = yield* decideOrchestrationCommand({
813 command: {
814 type: "thread.activity.append",
815 commandId: CommandId.make("cmd-activity-routine"),
816 threadId: ThreadId.make("thread-1"),
817 activity: {
818 id: EventId.make("activity-2"),
819 tone: "info",
820 kind: "tool.completed",
821 summary: "Tool completed",
822 payload: null,
823 turnId: null,
824 createdAt: NOW,
825 },
826 createdAt: NOW,
827 },
828 readModel: makeReadModel("settled"),
829 });
830 const routineEvents = Array.isArray(routineResult) ? routineResult : [routineResult];
831 expect(routineEvents.map((event) => event.type)).toEqual(["thread.activity-appended"]);
832 }),
833 );
834
835 it.effect("drops an onlyIfSettled session stop when the thread was re-engaged", () =>
836 Effect.gen(function* () {
837 const stopCommand = (commandId: string) =>
838 ({
839 type: "thread.session.stop",
840 commandId: CommandId.make(commandId),
841 threadId: ThreadId.make("thread-1"),
842 createdAt: NOW,
843 onlyIfSettled: true,
844 }) as const;
845
846 // Still settled with an idle session: the cleanup stop goes through.
847 const stopped = yield* decideOrchestrationCommand({
848 command: stopCommand("cmd-stop-settled-idle"),
849 readModel: makeReadModel("settled", null, makeSession("ready")),
850 });
851 const stoppedEvents = Array.isArray(stopped) ? stopped : [stopped];
852 expect(stoppedEvents.map((event) => event.type)).toEqual(["thread.session-stop-requested"]);
853
854 // Re-engaged before the stop was decided (a turn start unsettles the
855 // thread): the stale cleanup stop must not kill the new session.
856 const unsettledError = yield* decideOrchestrationCommand({
857 command: stopCommand("cmd-stop-unsettled"),
858 readModel: makeReadModel(null, null, makeSession("starting")),
859 }).pipe(Effect.flip);
860 expect(unsettledError._tag).toBe("OrchestrationCommandInvariantError");
861
862 // Still settled but the session is already coming alive: same drop.
863 const aliveError = yield* decideOrchestrationCommand({
864 command: stopCommand("cmd-stop-session-alive"),
865 readModel: makeReadModel("settled", null, makeSession("starting")),
866 }).pipe(Effect.flip);
867 expect(aliveError._tag).toBe("OrchestrationCommandInvariantError");
868
869 // Without the flag the stop stays unconditional (archive, stop button).
870 const unconditional = yield* decideOrchestrationCommand({
871 command: {
872 type: "thread.session.stop",
873 commandId: CommandId.make("cmd-stop-unconditional"),
874 threadId: ThreadId.make("thread-1"),
875 createdAt: NOW,
876 },
877 readModel: makeReadModel(null, null, makeSession("starting")),
878 });
879 const unconditionalEvents = Array.isArray(unconditional) ? unconditional : [unconditional];
880 expect(unconditionalEvents.map((event) => event.type)).toEqual([
881 "thread.session-stop-requested",
882 ]);
883 }),
884 );
885
886 it.effect("rejects checkpoint reverts while a turn is active or queued", () =>
887 Effect.gen(function* () {
888 for (const status of ["starting", "running"] as const) {
889 const error = yield* decideOrchestrationCommand({
890 command: {
891 type: "thread.checkpoint.revert",
892 commandId: CommandId.make(`cmd-revert-${status}`),
893 threadId: ThreadId.make("thread-1"),
894 turnCount: 0,
895 createdAt: NOW,
896 },
897 readModel: makeReadModel(null, null, makeSession(status)),
898 }).pipe(Effect.flip);
899 expect(error).toMatchObject({
900 _tag: "OrchestrationCommandInvariantError",
901 detail: "Interrupt the current turn before reverting checkpoints.",
902 });
903 }
904
905 const latestTurnError = yield* decideOrchestrationCommand({
906 command: {
907 type: "thread.checkpoint.revert",
908 commandId: CommandId.make("cmd-revert-active-turn"),
909 threadId: ThreadId.make("thread-1"),
910 turnCount: 0,
911 createdAt: NOW,
912 },
913 readModel: makeReadModel(
914 null,
915 null,
916 makeSession("ready"),
917 [],
918 [],
919 {},
920 {
921 turnId: TurnId.make("turn-1"),
922 state: "running",
923 requestedAt: NOW,
924 startedAt: NOW,
925 completedAt: null,
926 assistantMessageId: null,
927 },
928 ),
929 }).pipe(Effect.flip);
930 expect(latestTurnError._tag).toBe("OrchestrationCommandInvariantError");
931
932 const pendingMessageId = MessageId.make("message-revert-queued");
933 const queuedReadModel = yield* projectQueuedTurnStart(
934 pendingMessageId,
935 "2025-12-31T23:55:00.000Z",
936 );
937 const queuedError = yield* decideOrchestrationCommand({
938 command: {
939 type: "thread.checkpoint.revert",
940 commandId: CommandId.make("cmd-revert-queued-turn"),
941 threadId: ThreadId.make("thread-1"),
942 turnCount: 0,
943 createdAt: NOW,
944 },
945 readModel: queuedReadModel,
946 }).pipe(Effect.flip);
947 expect(queuedError._tag).toBe("OrchestrationCommandInvariantError");
948
949 const acknowledgement = yield* decideOrchestrationCommand({
950 command: {
951 type: "thread.turn.start.acknowledge",
952 commandId: CommandId.make("cmd-acknowledge-queued-turn"),
953 threadId: ThreadId.make("thread-1"),
954 messageId: pendingMessageId,
955 turnId: TurnId.make("turn-acknowledged-before-running"),
956 },
957 readModel: queuedReadModel,
958 });
959 let acknowledgedReadModel = yield* projectEvent(queuedReadModel, {
960 ...(Array.isArray(acknowledgement) ? acknowledgement[0]! : acknowledgement),
961 sequence: queuedReadModel.snapshotSequence + 1,
962 });
963 for (const [status, activeTurnId] of [
964 ["running", TurnId.make("turn-unrelated-running")],
965 ["ready", null],
966 ] as const) {
967 const sessionSet = yield* decideOrchestrationCommand({
968 command: {
969 type: "thread.session.set",
970 commandId: CommandId.make(`cmd-session-${status}-after-acknowledgement`),
971 threadId: ThreadId.make("thread-1"),
972 session: {
973 ...makeSession(status),
974 activeTurnId,
975 },
976 createdAt: NOW,
977 },
978 readModel: acknowledgedReadModel,
979 });
980 for (const event of Array.isArray(sessionSet) ? sessionSet : [sessionSet]) {
981 acknowledgedReadModel = yield* projectEvent(acknowledgedReadModel, {
982 ...event,
983 sequence: acknowledgedReadModel.snapshotSequence + 1,
984 });
985 }
986 }
987 expect(acknowledgedReadModel.threads[0]?.pendingTurnStartMessageId).toBeNull();
988 expect(acknowledgedReadModel.threads[0]?.submittedTurnStarts).toEqual([
989 {
990 messageId: pendingMessageId,
991 turnId: TurnId.make("turn-acknowledged-before-running"),
992 },
993 ]);
994 const acknowledgedError = yield* decideOrchestrationCommand({
995 command: {
996 type: "thread.checkpoint.revert",
997 commandId: CommandId.make("cmd-revert-acknowledged-before-running"),
998 threadId: ThreadId.make("thread-1"),
999 turnCount: 0,
1000 createdAt: NOW,
1001 },
1002 readModel: acknowledgedReadModel,
1003 }).pipe(Effect.flip);
1004 expect(acknowledgedError._tag).toBe("OrchestrationCommandInvariantError");
1005 }),
1006 );
1007
1008 it.effect("marks the source plan when the acknowledgement lands after its turn surfaced", () =>
1009 Effect.gen(function* () {
1010 const sourceThread: OrchestrationThread = {
1011 ...makeReadModel(null).threads[0]!,
1012 id: ThreadId.make("thread-source"),
1013 proposedPlans: [
1014 {
1015 id: OrchestrationProposedPlanId.make("plan-1"),
1016 turnId: TurnId.make("turn-source"),
1017 planMarkdown: "plan",
1018 createdAt: NOW,
1019 implementedAt: null,
1020 implementationThreadId: null,
1021 updatedAt: NOW,
1022 },
1023 ],
1024 };
1025 const baseReadModel = makeReadModel(
1026 null,
1027 null,
1028 makeSession("running"),
1029 [],
1030 [],
1031 {},
1032 {
1033 turnId: TurnId.make("turn-late"),
1034 state: "running",
1035 requestedAt: NOW,
1036 startedAt: NOW,
1037 completedAt: null,
1038 assistantMessageId: null,
1039 },
1040 );
1041 const readModel: OrchestrationReadModel = {
1042 ...baseReadModel,
1043 threads: [...baseReadModel.threads, sourceThread],
1044 };
1045
1046 const result = yield* decideOrchestrationCommand({
1047 command: {
1048 type: "thread.turn.start.acknowledge",
1049 commandId: CommandId.make("cmd-late-ack"),
1050 threadId: ThreadId.make("thread-1"),
1051 messageId: MessageId.make("message-late"),
1052 turnId: TurnId.make("turn-late"),
1053 sourceProposedPlan: {
1054 threadId: sourceThread.id,
1055 planId: sourceThread.proposedPlans[0]!.id,
1056 },
1057 },
1058 readModel,
1059 });
1060 const events = Array.isArray(result) ? result : [result];
1061 expect(events.map((event) => event.type)).toEqual([
1062 "thread.meta-updated",
1063 "thread.proposed-plan-upserted",
1064 ]);
1065 const upsert = events[1]!;
1066 expect(upsert.aggregateId).toBe(sourceThread.id);
1067 if (upsert.type === "thread.proposed-plan-upserted") {
1068 expect(upsert.payload.proposedPlan.implementedAt).not.toBeNull();
1069 expect(upsert.payload.proposedPlan.implementationThreadId).toBe("thread-1");
1070 }
1071
1072 // An acknowledgement for a turn that never surfaced leaves the plan open.
1073 const early = yield* decideOrchestrationCommand({
1074 command: {
1075 type: "thread.turn.start.acknowledge",
1076 commandId: CommandId.make("cmd-early-ack"),
1077 threadId: ThreadId.make("thread-1"),
1078 messageId: MessageId.make("message-early"),
1079 turnId: TurnId.make("turn-not-yet"),
1080 sourceProposedPlan: {
1081 threadId: sourceThread.id,
1082 planId: sourceThread.proposedPlans[0]!.id,
1083 },
1084 },
1085 readModel,
1086 });
1087 const earlyEvents = Array.isArray(early) ? early : [early];
1088 expect(earlyEvents.map((event) => event.type)).toEqual(["thread.meta-updated"]);
1089 }),
1090 );
1091
1092 it.effect("preserves a pending turn start when its client clock is behind", () =>
1093 Effect.gen(function* () {
1094 const pendingMessageId = MessageId.make("message-revert-clock-skew");
1095 const readModel = yield* projectQueuedTurnStart(pendingMessageId, "2025-12-31T23:55:00.000Z");
1096 const result = yield* decideOrchestrationCommand({
1097 command: {
1098 type: "thread.revert.complete",
1099 commandId: CommandId.make("cmd-revert-complete-clock-skew"),
1100 threadId: ThreadId.make("thread-1"),
1101 turnCount: 0,
1102 createdAt: "2026-01-01T00:00:13.000Z",
1103 },
1104 readModel,
1105 });
1106
1107 expect(result).toMatchObject({
1108 type: "thread.reverted",
1109 payload: { preservedMessageIds: [pendingMessageId] },
1110 });
1111 }),
1112 );
1113});