Open History to see the last commit
1import {
2 EventId,
3 type OrchestrationCommand,
4 type OrchestrationEvent,
5 type OrchestrationReadModel,
6 type OrchestrationThread,
7} from "@t3tools/contracts";
8import * as DateTime from "effect/DateTime";
9import * as Crypto from "effect/Crypto";
10import * as Effect from "effect/Effect";
11import type * as PlatformError from "effect/PlatformError";
12
13import {
14 OrchestrationCommandInvariantError,
15 OrchestrationThreadSettleBlockedError,
16 type OrchestrationCommandRejection,
17} from "./Errors.ts";
18import {
19 listThreadsByProjectId,
20 requireActiveProjectWorkspaceRootAbsent,
21 requireProject,
22 requireProjectAbsent,
23 requireThread,
24 requireThreadArchived,
25 requireThreadAbsent,
26 requireThreadNotArchived,
27} from "./commandInvariants.ts";
28import { projectEvent } from "./projector.ts";
29import { threadHasQueuedTurnStart } from "./ThreadSettlementPolicy.ts";
30
31const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
32
33/**
34 * Blocked-on-you work derived from the thread's retained activities: an
35 * approval or user-input request with no later resolution for the same
36 * requestId. The server-side twin of the shell's hasPendingApprovals /
37 * hasPendingUserInput flags, which the decider read model does not carry.
38 * The clearing rules MUST match ProjectionPipeline's pending accounting —
39 * resolved activities always clear, respond.failed clears only when the
40 * failure detail marks the request stale/unknown — or settle would be
41 * rejected on threads whose shell flags read as clear.
42 */
43function isStaleRequestFailureDetail(payload: Record<string, unknown> | null): boolean {
44 const detail = typeof payload?.detail === "string" ? payload.detail.toLowerCase() : null;
45 if (detail === null) return false;
46 return (
47 detail.includes("stale pending approval request") ||
48 detail.includes("unknown pending approval request") ||
49 detail.includes("unknown pending permission request") ||
50 detail.includes("stale pending user-input request") ||
51 detail.includes("unknown pending user-input request") ||
52 detail.includes("unknown pending user input request") ||
53 detail.includes("unknown pending codex user input request")
54 );
55}
56
57// Scans the read model's activities, which the projector caps at the most
58// recent 500. That bound is safe here: an OPEN approval/user-input request
59// blocks its turn, so the thread cannot accumulate hundreds of later
60// activities while one is outstanding — a request that has scrolled out of
61// the window is one whose turn kept running, i.e. it was resolved or went
62// stale. (The projection pipeline's pendingApprovalCount reads the same
63// capped stream and stays consistent with this view.)
64function hasOpenBlockingRequest(thread: {
65 readonly activities: ReadonlyArray<{ readonly kind: string; readonly payload: unknown }>;
66}): boolean {
67 const openRequestIds = new Set<string>();
68 for (const activity of thread.activities) {
69 const payload =
70 typeof activity.payload === "object" && activity.payload !== null
71 ? (activity.payload as Record<string, unknown>)
72 : null;
73 const requestId = typeof payload?.requestId === "string" ? payload.requestId : null;
74 if (requestId === null) continue;
75 if (activity.kind === "approval.requested" || activity.kind === "user-input.requested") {
76 openRequestIds.add(requestId);
77 } else if (activity.kind === "approval.resolved" || activity.kind === "user-input.resolved") {
78 openRequestIds.delete(requestId);
79 } else if (
80 (activity.kind === "provider.approval.respond.failed" ||
81 activity.kind === "provider.user-input.respond.failed") &&
82 isStaleRequestFailureDetail(payload)
83 ) {
84 openRequestIds.delete(requestId);
85 }
86 }
87 return openRequestIds.size > 0;
88}
89
90/** Apply the shared shell-level rule to the detailed command read model. */
91function hasQueuedTurnStartForThread(
92 thread: Pick<OrchestrationThread, "messages" | "latestTurn" | "session">,
93 now: string,
94): boolean {
95 let latestUserMessageAt: string | null = null;
96 let latestUserMessageAtMs = Number.NEGATIVE_INFINITY;
97 for (const message of thread.messages) {
98 if (message.role !== "user") continue;
99 const messageAtMs = Date.parse(message.createdAt);
100 latestUserMessageAtMs = Math.max(latestUserMessageAtMs, messageAtMs);
101 if (messageAtMs === latestUserMessageAtMs) {
102 latestUserMessageAt = message.createdAt;
103 }
104 }
105 return threadHasQueuedTurnStart(
106 {
107 latestUserMessageAt: Number.isFinite(latestUserMessageAtMs) ? latestUserMessageAt : null,
108 latestTurn: thread.latestTurn,
109 session: thread.session,
110 },
111 now,
112 );
113}
114
115function withEventBase(
116 input: Pick<OrchestrationCommand, "commandId"> & {
117 readonly aggregateKind: OrchestrationEvent["aggregateKind"];
118 readonly aggregateId: OrchestrationEvent["aggregateId"];
119 readonly occurredAt: string;
120 readonly metadata?: OrchestrationEvent["metadata"];
121 },
122): Effect.Effect<
123 Omit<OrchestrationEvent, "sequence" | "type" | "payload">,
124 PlatformError.PlatformError,
125 Crypto.Crypto
126> {
127 return Crypto.Crypto.pipe(
128 Effect.flatMap((crypto) =>
129 crypto.randomUUIDv4.pipe(
130 Effect.map((eventId) => ({
131 eventId: EventId.make(eventId),
132 aggregateKind: input.aggregateKind,
133 aggregateId: input.aggregateId,
134 occurredAt: input.occurredAt,
135 commandId: input.commandId,
136 causationEventId: null,
137 correlationId: input.commandId,
138 metadata: input.metadata ?? {},
139 })),
140 ),
141 ),
142 );
143}
144
145type PlannedOrchestrationEvent = Omit<OrchestrationEvent, "sequence">;
146
147type DecideOrchestrationCommandResult =
148 | PlannedOrchestrationEvent
149 | ReadonlyArray<PlannedOrchestrationEvent>;
150
151const decideCommandSequence = Effect.fn("decideCommandSequence")(function* ({
152 commands,
153 readModel,
154}: {
155 readonly commands: ReadonlyArray<OrchestrationCommand>;
156 readonly readModel: OrchestrationReadModel;
157}): Effect.fn.Return<
158 ReadonlyArray<PlannedOrchestrationEvent>,
159 OrchestrationCommandRejection | PlatformError.PlatformError,
160 Crypto.Crypto
161> {
162 let nextReadModel = readModel;
163 let nextSequence = readModel.snapshotSequence;
164 const plannedEvents: PlannedOrchestrationEvent[] = [];
165
166 for (const nextCommand of commands) {
167 const decided = yield* decideOrchestrationCommand({
168 command: nextCommand,
169 readModel: nextReadModel,
170 });
171 const nextEvents = Array.isArray(decided) ? decided : [decided];
172 for (const nextEvent of nextEvents) {
173 plannedEvents.push(nextEvent);
174 nextSequence += 1;
175 nextReadModel = yield* projectEvent(nextReadModel, {
176 ...nextEvent,
177 sequence: nextSequence,
178 }).pipe(Effect.orDie);
179 }
180 }
181
182 return plannedEvents;
183});
184
185export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand")(function* ({
186 command,
187 readModel,
188}: {
189 readonly command: OrchestrationCommand;
190 readonly readModel: OrchestrationReadModel;
191}): Effect.fn.Return<
192 DecideOrchestrationCommandResult,
193 OrchestrationCommandRejection | PlatformError.PlatformError,
194 Crypto.Crypto
195> {
196 switch (command.type) {
197 case "project.create": {
198 yield* requireProjectAbsent({
199 readModel,
200 command,
201 projectId: command.projectId,
202 });
203 yield* requireActiveProjectWorkspaceRootAbsent({
204 readModel,
205 command,
206 workspaceRoot: command.workspaceRoot,
207 exceptProjectId: command.projectId,
208 });
209
210 return {
211 ...(yield* withEventBase({
212 aggregateKind: "project",
213 aggregateId: command.projectId,
214 occurredAt: command.createdAt,
215 commandId: command.commandId,
216 })),
217 type: "project.created",
218 payload: {
219 projectId: command.projectId,
220 title: command.title,
221 workspaceRoot: command.workspaceRoot,
222 // Project creation has no user model choice. Older clients sent an
223 // automatic seed here, but only a metadata update records an
224 // explicit project default.
225 defaultModelSelection: null,
226 faviconPath: null,
227 scripts: [],
228 createdAt: command.createdAt,
229 updatedAt: command.createdAt,
230 },
231 };
232 }
233
234 case "project.meta.update": {
235 yield* requireProject({
236 readModel,
237 command,
238 projectId: command.projectId,
239 });
240 if (command.workspaceRoot !== undefined) {
241 yield* requireActiveProjectWorkspaceRootAbsent({
242 readModel,
243 command,
244 workspaceRoot: command.workspaceRoot,
245 exceptProjectId: command.projectId,
246 });
247 }
248 const occurredAt = yield* nowIso;
249 return {
250 ...(yield* withEventBase({
251 aggregateKind: "project",
252 aggregateId: command.projectId,
253 occurredAt,
254 commandId: command.commandId,
255 })),
256 type: "project.meta-updated",
257 payload: {
258 projectId: command.projectId,
259 ...(command.title !== undefined ? { title: command.title } : {}),
260 ...(command.workspaceRoot !== undefined ? { workspaceRoot: command.workspaceRoot } : {}),
261 ...(command.defaultModelSelection !== undefined
262 ? { defaultModelSelection: command.defaultModelSelection }
263 : {}),
264 ...(command.defaultThreadEnvMode !== undefined
265 ? { defaultThreadEnvMode: command.defaultThreadEnvMode }
266 : {}),
267 ...(command.faviconPath !== undefined ? { faviconPath: command.faviconPath } : {}),
268 ...(command.scripts !== undefined ? { scripts: command.scripts } : {}),
269 updatedAt: occurredAt,
270 },
271 };
272 }
273
274 case "project.delete": {
275 yield* requireProject({
276 readModel,
277 command,
278 projectId: command.projectId,
279 });
280 const activeThreads = listThreadsByProjectId(readModel, command.projectId).filter(
281 (thread) => thread.deletedAt === null,
282 );
283 if (activeThreads.length > 0 && command.force !== true) {
284 return yield* new OrchestrationCommandInvariantError({
285 commandType: command.type,
286 detail: `Project '${command.projectId}' is not empty and cannot be deleted without force=true.`,
287 });
288 }
289 if (activeThreads.length > 0) {
290 return yield* decideCommandSequence({
291 readModel,
292 commands: [
293 ...activeThreads.map(
294 (thread): Extract<OrchestrationCommand, { type: "thread.delete" }> => ({
295 type: "thread.delete",
296 commandId: command.commandId,
297 threadId: thread.id,
298 }),
299 ),
300 {
301 type: "project.delete",
302 commandId: command.commandId,
303 projectId: command.projectId,
304 },
305 ],
306 });
307 }
308
309 const occurredAt = yield* nowIso;
310 return {
311 ...(yield* withEventBase({
312 aggregateKind: "project",
313 aggregateId: command.projectId,
314 occurredAt,
315 commandId: command.commandId,
316 })),
317 type: "project.deleted" as const,
318 payload: {
319 projectId: command.projectId,
320 deletedAt: occurredAt,
321 },
322 };
323 }
324
325 case "thread.create": {
326 yield* requireProject({
327 readModel,
328 command,
329 projectId: command.projectId,
330 });
331 yield* requireThreadAbsent({
332 readModel,
333 command,
334 threadId: command.threadId,
335 });
336 return {
337 ...(yield* withEventBase({
338 aggregateKind: "thread",
339 aggregateId: command.threadId,
340 occurredAt: command.createdAt,
341 commandId: command.commandId,
342 })),
343 type: "thread.created",
344 payload: {
345 threadId: command.threadId,
346 projectId: command.projectId,
347 title: command.title,
348 modelSelection: command.modelSelection,
349 runtimeMode: command.runtimeMode,
350 interactionMode: command.interactionMode,
351 branch: command.branch,
352 worktreePath: command.worktreePath,
353 createdAt: command.createdAt,
354 updatedAt: command.createdAt,
355 },
356 };
357 }
358
359 case "thread.delete": {
360 yield* requireThread({
361 readModel,
362 command,
363 threadId: command.threadId,
364 });
365 const occurredAt = yield* nowIso;
366 return {
367 ...(yield* withEventBase({
368 aggregateKind: "thread",
369 aggregateId: command.threadId,
370 occurredAt,
371 commandId: command.commandId,
372 })),
373 type: "thread.deleted",
374 payload: {
375 threadId: command.threadId,
376 deletedAt: occurredAt,
377 },
378 };
379 }
380
381 case "thread.archive": {
382 yield* requireThreadNotArchived({
383 readModel,
384 command,
385 threadId: command.threadId,
386 });
387 const occurredAt = yield* nowIso;
388 return {
389 ...(yield* withEventBase({
390 aggregateKind: "thread",
391 aggregateId: command.threadId,
392 occurredAt,
393 commandId: command.commandId,
394 })),
395 type: "thread.archived",
396 payload: {
397 threadId: command.threadId,
398 archivedAt: occurredAt,
399 updatedAt: occurredAt,
400 },
401 };
402 }
403
404 case "thread.unarchive": {
405 yield* requireThreadArchived({
406 readModel,
407 command,
408 threadId: command.threadId,
409 });
410 const occurredAt = yield* nowIso;
411 return {
412 ...(yield* withEventBase({
413 aggregateKind: "thread",
414 aggregateId: command.threadId,
415 occurredAt,
416 commandId: command.commandId,
417 })),
418 type: "thread.unarchived",
419 payload: {
420 threadId: command.threadId,
421 updatedAt: occurredAt,
422 },
423 };
424 }
425
426 case "thread.settle":
427 case "thread.auto-settle": {
428 const thread = yield* requireThreadNotArchived({
429 readModel,
430 command,
431 threadId: command.threadId,
432 });
433 if (command.type === "thread.auto-settle" && thread.settledOverride !== null) {
434 return yield* Effect.fail(
435 new OrchestrationCommandInvariantError({
436 commandType: command.type,
437 detail: `thread ${command.threadId} changed before automatic settlement`,
438 }),
439 );
440 }
441 // The server owns settle eligibility. A stale command must not settle
442 // a thread whose session is coming alive or working.
443 if (thread.session?.status === "starting" || thread.session?.status === "running") {
444 return yield* new OrchestrationThreadSettleBlockedError({ threadId: command.threadId });
445 }
446 // Pending approval / user-input requests are blocked-on-you work: a
447 // raced or stale client must not park them behind a settled override
448 // that would surface only after the request resolves.
449 if (hasOpenBlockingRequest(thread)) {
450 return yield* new OrchestrationThreadSettleBlockedError({ threadId: command.threadId });
451 }
452 const occurredAt = yield* nowIso;
453 // Settling inside the adoption window would hide just-requested work.
454 if (hasQueuedTurnStartForThread(thread, occurredAt)) {
455 return yield* new OrchestrationThreadSettleBlockedError({ threadId: command.threadId });
456 }
457 // Settling an already-settled thread re-emits with the original
458 // settledAt: the engine rejects zero-event commands, and bulk-settle /
459 // double-click must stay silent no-ops rather than surface errors.
460 const alreadySettled = thread.settledOverride === "settled" && thread.settledAt !== null;
461 const settledEvent = {
462 ...(yield* withEventBase({
463 aggregateKind: "thread",
464 aggregateId: command.threadId,
465 occurredAt,
466 commandId: command.commandId,
467 })),
468 type: "thread.settled" as const,
469 payload: {
470 threadId: command.threadId,
471 settledAt: alreadySettled ? thread.settledAt : occurredAt,
472 // A re-emission is a projected no-op: keep the existing updatedAt
473 // so duplicate settles neither rewind nor churn ordering. A fresh
474 // settle stamps the command time.
475 updatedAt: alreadySettled ? thread.updatedAt : occurredAt,
476 },
477 };
478 // Settling is "I'm done with this": clear states that would keep the
479 // row pinned or snoozed instead of showing the new settled state.
480 const companionEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];
481 if (thread.pinnedAt != null) {
482 companionEvents.push({
483 ...(yield* withEventBase({
484 aggregateKind: "thread",
485 aggregateId: command.threadId,
486 occurredAt,
487 commandId: command.commandId,
488 })),
489 type: "thread.unpinned" as const,
490 payload: {
491 threadId: command.threadId,
492 updatedAt: occurredAt,
493 },
494 });
495 }
496 if (thread.snoozedUntil != null) {
497 companionEvents.push({
498 ...(yield* withEventBase({
499 aggregateKind: "thread",
500 aggregateId: command.threadId,
501 occurredAt,
502 commandId: command.commandId,
503 })),
504 type: "thread.unsnoozed",
505 payload: {
506 threadId: command.threadId,
507 reason: "user",
508 updatedAt: occurredAt,
509 },
510 });
511 }
512 return companionEvents.length > 0 ? [settledEvent, ...companionEvents] : settledEvent;
513 }
514
515 case "thread.unsettle": {
516 const thread = yield* requireThreadNotArchived({
517 readModel,
518 command,
519 threadId: command.threadId,
520 });
521 // Idempotent by re-emission (see thread.settle): reducing the event a
522 // second time lands on the same override state. A re-emission keeps
523 // the existing updatedAt so duplicates do not churn ordering.
524 const alreadyPinnedActive = thread.settledOverride === "active";
525 const occurredAt = yield* nowIso;
526 return {
527 ...(yield* withEventBase({
528 aggregateKind: "thread",
529 aggregateId: command.threadId,
530 occurredAt,
531 commandId: command.commandId,
532 })),
533 type: "thread.unsettled",
534 payload: {
535 threadId: command.threadId,
536 reason: command.reason,
537 updatedAt: alreadyPinnedActive ? thread.updatedAt : occurredAt,
538 },
539 };
540 }
541
542 case "thread.snooze": {
543 const thread = yield* requireThreadNotArchived({
544 readModel,
545 command,
546 threadId: command.threadId,
547 });
548 const occurredAt = yield* nowIso;
549 // A wake time in the past would create a thread that is snoozed and
550 // woken at once — the row would never leave the inbox but still carry
551 // snooze state. Reject instead of silently normalizing. The negated
552 // comparison also catches unparseable wake times (IsoDateTime is
553 // structurally just a string): NaN fails every comparison, and an
554 // unparseable snoozedUntil must never persist.
555 if (!(Date.parse(command.snoozedUntil) > Date.parse(occurredAt))) {
556 return yield* Effect.fail(
557 new OrchestrationCommandInvariantError({
558 commandType: command.type,
559 detail: `thread ${command.threadId} snooze wake time ${command.snoozedUntil} is not in the future`,
560 }),
561 );
562 }
563 // Blocked-on-you work must not be snoozed away: a pending approval or
564 // user-input request is the agent waiting on the user, and hiding it
565 // defeats the request. (A running session IS snoozable — snooze only
566 // affects visibility, never the agent.)
567 if (hasOpenBlockingRequest(thread)) {
568 return yield* Effect.fail(
569 new OrchestrationCommandInvariantError({
570 commandType: command.type,
571 detail: `thread ${command.threadId} has a pending approval or user-input request and cannot be snoozed`,
572 }),
573 );
574 }
575 // A queued turn start — a user message no turn has adopted yet — is
576 // invisible pending work: no session, no pending flags. Snoozing in
577 // that window would hide a just-requested turn exactly the way settle
578 // would.
579 if (hasQueuedTurnStartForThread(thread, occurredAt)) {
580 return yield* Effect.fail(
581 new OrchestrationCommandInvariantError({
582 commandType: command.type,
583 detail: `thread ${command.threadId} has a queued turn start and cannot be snoozed`,
584 }),
585 );
586 }
587 // Re-snoozing an already-snoozed thread to the SAME wake time is a
588 // duplicate (double-click, raced clients): re-emit with the original
589 // timestamps so the projection is a no-op. A different wake time is a
590 // real change and stamps fresh.
591 const existingSnoozedAt =
592 thread.snoozedUntil === command.snoozedUntil && thread.snoozedAt != null
593 ? thread.snoozedAt
594 : null;
595 return {
596 ...(yield* withEventBase({
597 aggregateKind: "thread",
598 aggregateId: command.threadId,
599 occurredAt,
600 commandId: command.commandId,
601 })),
602 type: "thread.snoozed",
603 payload: {
604 threadId: command.threadId,
605 snoozedUntil: command.snoozedUntil,
606 snoozedAt: existingSnoozedAt ?? occurredAt,
607 updatedAt: existingSnoozedAt !== null ? thread.updatedAt : occurredAt,
608 },
609 };
610 }
611
612 case "thread.unsnooze": {
613 const thread = yield* requireThreadNotArchived({
614 readModel,
615 command,
616 threadId: command.threadId,
617 });
618 // Idempotent by re-emission (see thread.settle): waking a thread that
619 // is not snoozed lands on the same null state without churning
620 // updatedAt.
621 const alreadyAwake = thread.snoozedUntil == null;
622 const occurredAt = yield* nowIso;
623 return {
624 ...(yield* withEventBase({
625 aggregateKind: "thread",
626 aggregateId: command.threadId,
627 occurredAt,
628 commandId: command.commandId,
629 })),
630 type: "thread.unsnoozed",
631 payload: {
632 threadId: command.threadId,
633 reason: command.reason,
634 updatedAt: alreadyAwake ? thread.updatedAt : occurredAt,
635 },
636 };
637 }
638
639 case "thread.pin": {
640 const thread = yield* requireThreadNotArchived({
641 readModel,
642 command,
643 threadId: command.threadId,
644 });
645 const occurredAt = yield* nowIso;
646 // Re-pinning an already-pinned thread is a duplicate (double-click,
647 // raced clients): re-emit with the original timestamps so the
648 // projection is a no-op. Pinning has no lifecycle invariants — a pin
649 // only ever promotes visibility, so it can never hide pending work.
650 const existingPinnedAt = thread.pinnedAt ?? null;
651 const pinnedEvent = {
652 ...(yield* withEventBase({
653 aggregateKind: "thread",
654 aggregateId: command.threadId,
655 occurredAt,
656 commandId: command.commandId,
657 })),
658 type: "thread.pinned" as const,
659 payload: {
660 threadId: command.threadId,
661 pinnedAt: existingPinnedAt ?? occurredAt,
662 // A fresh pin takes the client's slot in the arranged order; on a
663 // re-pin the existing key wins so raced duplicates cannot move a
664 // thread the user already placed.
665 ...(existingPinnedAt === null && command.orderKey !== undefined
666 ? { pinOrderKey: command.orderKey }
667 : {}),
668 updatedAt: existingPinnedAt !== null ? thread.updatedAt : occurredAt,
669 },
670 };
671 // Pinning is a promotion: it clears the parked states rather than
672 // silently outranking them. An explicit settle un-settles (reason
673 // "user", same override the un-settle button stamps), and a snooze's
674 // return ticket is spent — the thread is on top NOW, not on Tuesday.
675 const promotionEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];
676 if (thread.settledOverride === "settled") {
677 promotionEvents.push({
678 ...(yield* withEventBase({
679 aggregateKind: "thread",
680 aggregateId: command.threadId,
681 occurredAt,
682 commandId: command.commandId,
683 })),
684 type: "thread.unsettled",
685 payload: {
686 threadId: command.threadId,
687 reason: "user",
688 updatedAt: occurredAt,
689 },
690 });
691 }
692 if (thread.snoozedUntil != null) {
693 promotionEvents.push({
694 ...(yield* withEventBase({
695 aggregateKind: "thread",
696 aggregateId: command.threadId,
697 occurredAt,
698 commandId: command.commandId,
699 })),
700 type: "thread.unsnoozed",
701 payload: {
702 threadId: command.threadId,
703 reason: "user",
704 updatedAt: occurredAt,
705 },
706 });
707 }
708 return promotionEvents.length > 0 ? [pinnedEvent, ...promotionEvents] : pinnedEvent;
709 }
710
711 case "thread.unpin": {
712 const thread = yield* requireThreadNotArchived({
713 readModel,
714 command,
715 threadId: command.threadId,
716 });
717 // Idempotent by re-emission (see thread.settle): unpinning a thread
718 // that is not pinned lands on the same null state without churning
719 // updatedAt.
720 const alreadyUnpinned = thread.pinnedAt == null;
721 const occurredAt = yield* nowIso;
722 return {
723 ...(yield* withEventBase({
724 aggregateKind: "thread",
725 aggregateId: command.threadId,
726 occurredAt,
727 commandId: command.commandId,
728 })),
729 type: "thread.unpinned",
730 payload: {
731 threadId: command.threadId,
732 updatedAt: alreadyUnpinned ? thread.updatedAt : occurredAt,
733 },
734 };
735 }
736
737 case "thread.pin.reorder": {
738 const thread = yield* requireThreadNotArchived({
739 readModel,
740 command,
741 threadId: command.threadId,
742 });
743 // Only pinned threads have a slot in the arranged order. Rejecting
744 // (rather than silently pinning) keeps a raced reorder-after-unpin
745 // from resurrecting a pin the user just cleared.
746 if (thread.pinnedAt == null) {
747 return yield* Effect.fail(
748 new OrchestrationCommandInvariantError({
749 commandType: command.type,
750 detail: `thread ${command.threadId} is not pinned and cannot be reordered`,
751 }),
752 );
753 }
754 // Idempotent by re-emission (see thread.settle): a duplicate drop on
755 // the same slot keeps the existing updatedAt so it projects as a no-op.
756 const keyUnchanged = thread.pinOrderKey === command.orderKey;
757 const occurredAt = yield* nowIso;
758 return {
759 ...(yield* withEventBase({
760 aggregateKind: "thread",
761 aggregateId: command.threadId,
762 occurredAt,
763 commandId: command.commandId,
764 })),
765 type: "thread.pin-reordered",
766 payload: {
767 threadId: command.threadId,
768 orderKey: command.orderKey,
769 updatedAt: keyUnchanged ? thread.updatedAt : occurredAt,
770 },
771 };
772 }
773
774 case "thread.meta.update": {
775 const thread = yield* requireThread({
776 readModel,
777 command,
778 threadId: command.threadId,
779 });
780 const branch =
781 command.branch !== undefined &&
782 command.expectedBranch !== undefined &&
783 thread.branch !== command.expectedBranch
784 ? thread.branch
785 : command.branch;
786 const occurredAt = yield* nowIso;
787 return {
788 ...(yield* withEventBase({
789 aggregateKind: "thread",
790 aggregateId: command.threadId,
791 occurredAt,
792 commandId: command.commandId,
793 })),
794 type: "thread.meta-updated",
795 payload: {
796 threadId: command.threadId,
797 ...(command.title !== undefined ? { title: command.title } : {}),
798 ...(command.regenerateTitle === true
799 ? {
800 regenerateTitle: true as const,
801 previousTitle: thread.title,
802 titleRegeneration: {
803 requestId: command.commandId,
804 startedAt: occurredAt,
805 },
806 }
807 : {}),
808 ...(command.title !== undefined && thread.titleRegeneration != null
809 ? { titleRegeneration: null }
810 : {}),
811 ...(command.modelSelection !== undefined
812 ? { modelSelection: command.modelSelection }
813 : {}),
814 ...(branch !== undefined ? { branch } : {}),
815 ...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),
816 ...(command.linkedPullRequest !== undefined
817 ? { linkedPullRequest: command.linkedPullRequest }
818 : {}),
819 updatedAt: occurredAt,
820 },
821 };
822 }
823
824 case "thread.title.regeneration.complete": {
825 const thread = yield* requireThread({
826 readModel,
827 command,
828 threadId: command.threadId,
829 });
830 const requestIsCurrent = thread.titleRegeneration?.requestId === command.requestId;
831 const occurredAt = yield* nowIso;
832 return {
833 ...(yield* withEventBase({
834 aggregateKind: "thread",
835 aggregateId: command.threadId,
836 occurredAt,
837 commandId: command.commandId,
838 })),
839 type: "thread.meta-updated",
840 payload: {
841 threadId: command.threadId,
842 ...(requestIsCurrent && command.title !== undefined ? { title: command.title } : {}),
843 ...(requestIsCurrent ? { titleRegeneration: null } : {}),
844 updatedAt: requestIsCurrent ? occurredAt : thread.updatedAt,
845 },
846 };
847 }
848
849 case "thread.runtime-mode.set": {
850 yield* requireThread({
851 readModel,
852 command,
853 threadId: command.threadId,
854 });
855 const occurredAt = yield* nowIso;
856 return {
857 ...(yield* withEventBase({
858 aggregateKind: "thread",
859 aggregateId: command.threadId,
860 occurredAt,
861 commandId: command.commandId,
862 })),
863 type: "thread.runtime-mode-set",
864 payload: {
865 threadId: command.threadId,
866 runtimeMode: command.runtimeMode,
867 updatedAt: occurredAt,
868 },
869 };
870 }
871
872 case "thread.interaction-mode.set": {
873 yield* requireThread({
874 readModel,
875 command,
876 threadId: command.threadId,
877 });
878 const occurredAt = yield* nowIso;
879 return {
880 ...(yield* withEventBase({
881 aggregateKind: "thread",
882 aggregateId: command.threadId,
883 occurredAt,
884 commandId: command.commandId,
885 })),
886 type: "thread.interaction-mode-set",
887 payload: {
888 threadId: command.threadId,
889 interactionMode: command.interactionMode,
890 updatedAt: occurredAt,
891 },
892 };
893 }
894
895 case "thread.turn.start": {
896 const targetThread = yield* requireThread({
897 readModel,
898 command,
899 threadId: command.threadId,
900 });
901 const sourceProposedPlan = command.sourceProposedPlan;
902 const sourceThread = sourceProposedPlan
903 ? yield* requireThread({
904 readModel,
905 command,
906 threadId: sourceProposedPlan.threadId,
907 })
908 : null;
909 const sourcePlan =
910 sourceProposedPlan && sourceThread
911 ? sourceThread.proposedPlans.find((entry) => entry.id === sourceProposedPlan.planId)
912 : null;
913 if (sourceProposedPlan && !sourcePlan) {
914 return yield* new OrchestrationCommandInvariantError({
915 commandType: command.type,
916 detail: `Proposed plan '${sourceProposedPlan.planId}' does not exist on thread '${sourceProposedPlan.threadId}'.`,
917 });
918 }
919 if (sourceThread && sourceThread.projectId !== targetThread.projectId) {
920 return yield* new OrchestrationCommandInvariantError({
921 commandType: command.type,
922 detail: `Proposed plan '${sourceProposedPlan?.planId}' belongs to thread '${sourceThread.id}' in a different project.`,
923 });
924 }
925 const userMessageEvent: Omit<OrchestrationEvent, "sequence"> = {
926 ...(yield* withEventBase({
927 aggregateKind: "thread",
928 aggregateId: command.threadId,
929 occurredAt: command.createdAt,
930 commandId: command.commandId,
931 })),
932 type: "thread.message-sent",
933 payload: {
934 threadId: command.threadId,
935 messageId: command.message.messageId,
936 role: "user",
937 text: command.message.text,
938 attachments: command.message.attachments,
939 turnId: null,
940 streaming: false,
941 createdAt: command.createdAt,
942 updatedAt: command.createdAt,
943 },
944 };
945 const turnStartRequestedEvent: Omit<OrchestrationEvent, "sequence"> = {
946 ...(yield* withEventBase({
947 aggregateKind: "thread",
948 aggregateId: command.threadId,
949 occurredAt: command.createdAt,
950 commandId: command.commandId,
951 })),
952 causationEventId: userMessageEvent.eventId,
953 type: "thread.turn-start-requested",
954 payload: {
955 threadId: command.threadId,
956 messageId: command.message.messageId,
957 ...(command.modelSelection !== undefined
958 ? { modelSelection: command.modelSelection }
959 : {}),
960 ...(command.titleSeed !== undefined ? { titleSeed: command.titleSeed } : {}),
961 runtimeMode: targetThread.runtimeMode,
962 interactionMode: targetThread.interactionMode,
963 ...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),
964 createdAt: command.createdAt,
965 },
966 };
967 // Real activity resets ANY override: it wakes an explicitly settled
968 // thread, and it clears a keep-active pin back to neutral so the
969 // thread can auto-settle again after this burst of work goes stale.
970 // A snooze clears the same way — sending a message to a snoozed
971 // thread is the user re-engaging, so the return ticket is spent.
972 const lifecycleResetEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];
973 if (targetThread.settledOverride !== null) {
974 lifecycleResetEvents.push({
975 ...(yield* withEventBase({
976 aggregateKind: "thread",
977 aggregateId: command.threadId,
978 occurredAt: command.createdAt,
979 commandId: command.commandId,
980 })),
981 type: "thread.unsettled",
982 payload: {
983 threadId: command.threadId,
984 reason: "activity",
985 updatedAt: command.createdAt,
986 },
987 });
988 }
989 if (targetThread.snoozedUntil != null) {
990 lifecycleResetEvents.push({
991 ...(yield* withEventBase({
992 aggregateKind: "thread",
993 aggregateId: command.threadId,
994 occurredAt: command.createdAt,
995 commandId: command.commandId,
996 })),
997 type: "thread.unsnoozed",
998 payload: {
999 threadId: command.threadId,
1000 reason: "activity",
1001 updatedAt: command.createdAt,
1002 },
1003 });
1004 }
1005 return [...lifecycleResetEvents, userMessageEvent, turnStartRequestedEvent];
1006 }
1007
1008 case "thread.turn.interrupt": {
1009 yield* requireThread({
1010 readModel,
1011 command,
1012 threadId: command.threadId,
1013 });
1014 return {
1015 ...(yield* withEventBase({
1016 aggregateKind: "thread",
1017 aggregateId: command.threadId,
1018 occurredAt: command.createdAt,
1019 commandId: command.commandId,
1020 })),
1021 type: "thread.turn-interrupt-requested",
1022 payload: {
1023 threadId: command.threadId,
1024 ...(command.turnId !== undefined ? { turnId: command.turnId } : {}),
1025 createdAt: command.createdAt,
1026 },
1027 };
1028 }
1029
1030 case "thread.approval.respond": {
1031 yield* requireThread({
1032 readModel,
1033 command,
1034 threadId: command.threadId,
1035 });
1036 return {
1037 ...(yield* withEventBase({
1038 aggregateKind: "thread",
1039 aggregateId: command.threadId,
1040 occurredAt: command.createdAt,
1041 commandId: command.commandId,
1042 metadata: {
1043 requestId: command.requestId,
1044 },
1045 })),
1046 type: "thread.approval-response-requested",
1047 payload: {
1048 threadId: command.threadId,
1049 requestId: command.requestId,
1050 decision: command.decision,
1051 createdAt: command.createdAt,
1052 },
1053 };
1054 }
1055
1056 case "thread.user-input.respond": {
1057 yield* requireThread({
1058 readModel,
1059 command,
1060 threadId: command.threadId,
1061 });
1062 return {
1063 ...(yield* withEventBase({
1064 aggregateKind: "thread",
1065 aggregateId: command.threadId,
1066 occurredAt: command.createdAt,
1067 commandId: command.commandId,
1068 metadata: {
1069 requestId: command.requestId,
1070 },
1071 })),
1072 type: "thread.user-input-response-requested",
1073 payload: {
1074 threadId: command.threadId,
1075 requestId: command.requestId,
1076 answers: command.answers,
1077 createdAt: command.createdAt,
1078 },
1079 };
1080 }
1081
1082 case "thread.checkpoint.revert": {
1083 yield* requireThread({
1084 readModel,
1085 command,
1086 threadId: command.threadId,
1087 });
1088 return {
1089 ...(yield* withEventBase({
1090 aggregateKind: "thread",
1091 aggregateId: command.threadId,
1092 occurredAt: command.createdAt,
1093 commandId: command.commandId,
1094 })),
1095 type: "thread.checkpoint-revert-requested",
1096 payload: {
1097 threadId: command.threadId,
1098 turnCount: command.turnCount,
1099 createdAt: command.createdAt,
1100 },
1101 };
1102 }
1103
1104 case "thread.session.stop": {
1105 const thread = yield* requireThread({
1106 readModel,
1107 command,
1108 threadId: command.threadId,
1109 });
1110 // Settle-cleanup stops are conditional: between the settle landing and
1111 // this command, another client may have re-engaged the thread (a turn
1112 // start unsettles it and brings the session alive). Commands are
1113 // decided serially against this read model, so checking here — not in
1114 // the dispatcher's pre-settle snapshot — closes that race.
1115 if (command.onlyIfSettled === true) {
1116 const sessionComingAlive =
1117 thread.session?.status === "starting" || thread.session?.status === "running";
1118 if (
1119 thread.settledOverride !== "settled" ||
1120 sessionComingAlive ||
1121 hasQueuedTurnStartForThread(thread, command.createdAt)
1122 ) {
1123 return yield* Effect.fail(
1124 new OrchestrationCommandInvariantError({
1125 commandType: command.type,
1126 detail: `thread ${command.threadId} was re-engaged after settle; skipping session stop`,
1127 }),
1128 );
1129 }
1130 }
1131 return {
1132 ...(yield* withEventBase({
1133 aggregateKind: "thread",
1134 aggregateId: command.threadId,
1135 occurredAt: command.createdAt,
1136 commandId: command.commandId,
1137 })),
1138 type: "thread.session-stop-requested",
1139 payload: {
1140 threadId: command.threadId,
1141 createdAt: command.createdAt,
1142 },
1143 };
1144 }
1145
1146 case "thread.session.set": {
1147 const thread = yield* requireThread({
1148 readModel,
1149 command,
1150 threadId: command.threadId,
1151 });
1152 const sessionSetEvent: Omit<OrchestrationEvent, "sequence"> = {
1153 ...(yield* withEventBase({
1154 aggregateKind: "thread",
1155 aggregateId: command.threadId,
1156 occurredAt: command.createdAt,
1157 commandId: command.commandId,
1158 metadata: {},
1159 })),
1160 type: "thread.session-set",
1161 payload: {
1162 threadId: command.threadId,
1163 session: command.session,
1164 },
1165 };
1166 // Only a session coming alive is activity worth waking a settled thread
1167 // for — status writes like ready/stopped/error arrive after the fact and
1168 // must not fight a user's explicit settle. Snooze is deliberately NOT
1169 // cleared here: snooze never pauses the agent, so its session starting
1170 // or erroring is not the user re-engaging. Blocked/failed work still
1171 // surfaces immediately — effectiveSnoozed refuses to classify a thread
1172 // with a raised hand (approval / input / failure / fresh completion)
1173 // as snoozed, without spending the return ticket.
1174 const isSessionActivity =
1175 command.session.status === "starting" || command.session.status === "running";
1176 // Real activity resets ANY override (settled wakes, active unpins).
1177 if (thread.settledOverride === null || !isSessionActivity) {
1178 return sessionSetEvent;
1179 }
1180 const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
1181 ...(yield* withEventBase({
1182 aggregateKind: "thread",
1183 aggregateId: command.threadId,
1184 occurredAt: command.createdAt,
1185 commandId: command.commandId,
1186 })),
1187 type: "thread.unsettled",
1188 payload: {
1189 threadId: command.threadId,
1190 reason: "activity",
1191 updatedAt: command.createdAt,
1192 },
1193 };
1194 return [unsettledEvent, sessionSetEvent];
1195 }
1196
1197 case "thread.message.assistant.delta": {
1198 yield* requireThread({
1199 readModel,
1200 command,
1201 threadId: command.threadId,
1202 });
1203 return {
1204 ...(yield* withEventBase({
1205 aggregateKind: "thread",
1206 aggregateId: command.threadId,
1207 occurredAt: command.createdAt,
1208 commandId: command.commandId,
1209 })),
1210 type: "thread.message-sent",
1211 payload: {
1212 threadId: command.threadId,
1213 messageId: command.messageId,
1214 role: "assistant",
1215 text: command.delta,
1216 turnId: command.turnId ?? null,
1217 streaming: true,
1218 createdAt: command.createdAt,
1219 updatedAt: command.createdAt,
1220 },
1221 };
1222 }
1223
1224 case "thread.message.assistant.complete": {
1225 yield* requireThread({
1226 readModel,
1227 command,
1228 threadId: command.threadId,
1229 });
1230 return {
1231 ...(yield* withEventBase({
1232 aggregateKind: "thread",
1233 aggregateId: command.threadId,
1234 occurredAt: command.createdAt,
1235 commandId: command.commandId,
1236 })),
1237 type: "thread.message-sent",
1238 payload: {
1239 threadId: command.threadId,
1240 messageId: command.messageId,
1241 role: "assistant",
1242 text: "",
1243 turnId: command.turnId ?? null,
1244 streaming: false,
1245 createdAt: command.createdAt,
1246 updatedAt: command.createdAt,
1247 },
1248 };
1249 }
1250
1251 case "thread.proposed-plan.upsert": {
1252 yield* requireThread({
1253 readModel,
1254 command,
1255 threadId: command.threadId,
1256 });
1257 return {
1258 ...(yield* withEventBase({
1259 aggregateKind: "thread",
1260 aggregateId: command.threadId,
1261 occurredAt: command.createdAt,
1262 commandId: command.commandId,
1263 })),
1264 type: "thread.proposed-plan-upserted",
1265 payload: {
1266 threadId: command.threadId,
1267 proposedPlan: command.proposedPlan,
1268 },
1269 };
1270 }
1271
1272 case "thread.turn.diff.complete": {
1273 yield* requireThread({
1274 readModel,
1275 command,
1276 threadId: command.threadId,
1277 });
1278 return {
1279 ...(yield* withEventBase({
1280 aggregateKind: "thread",
1281 aggregateId: command.threadId,
1282 occurredAt: command.createdAt,
1283 commandId: command.commandId,
1284 })),
1285 type: "thread.turn-diff-completed",
1286 payload: {
1287 threadId: command.threadId,
1288 turnId: command.turnId,
1289 checkpointTurnCount: command.checkpointTurnCount,
1290 checkpointRef: command.checkpointRef,
1291 status: command.status,
1292 files: command.files,
1293 assistantMessageId: command.assistantMessageId ?? null,
1294 completedAt: command.completedAt,
1295 },
1296 };
1297 }
1298
1299 case "thread.revert.complete": {
1300 yield* requireThread({
1301 readModel,
1302 command,
1303 threadId: command.threadId,
1304 });
1305 return {
1306 ...(yield* withEventBase({
1307 aggregateKind: "thread",
1308 aggregateId: command.threadId,
1309 occurredAt: command.createdAt,
1310 commandId: command.commandId,
1311 })),
1312 type: "thread.reverted",
1313 payload: {
1314 threadId: command.threadId,
1315 turnCount: command.turnCount,
1316 },
1317 };
1318 }
1319
1320 case "thread.activity.append": {
1321 const thread = yield* requireThread({
1322 readModel,
1323 command,
1324 threadId: command.threadId,
1325 });
1326 const requestId =
1327 typeof command.activity.payload === "object" &&
1328 command.activity.payload !== null &&
1329 "requestId" in command.activity.payload &&
1330 typeof (command.activity.payload as { requestId?: unknown }).requestId === "string"
1331 ? ((command.activity.payload as { requestId: string })
1332 .requestId as OrchestrationEvent["metadata"]["requestId"])
1333 : undefined;
1334 const activityAppendedEvent: Omit<OrchestrationEvent, "sequence"> = {
1335 ...(yield* withEventBase({
1336 aggregateKind: "thread",
1337 aggregateId: command.threadId,
1338 occurredAt: command.createdAt,
1339 commandId: command.commandId,
1340 ...(requestId !== undefined ? { metadata: { requestId } } : {}),
1341 })),
1342 type: "thread.activity-appended",
1343 payload: {
1344 threadId: command.threadId,
1345 activity: command.activity,
1346 },
1347 };
1348 // An approval or user-input request is blocked-on-you work — it must
1349 // never stay hidden inside a settled slim row.
1350 const wakesSettledThread =
1351 command.activity.kind === "approval.requested" ||
1352 command.activity.kind === "user-input.requested";
1353 // Real activity resets ANY override (settled wakes, active unpins).
1354 if (thread.settledOverride === null || !wakesSettledThread) {
1355 return activityAppendedEvent;
1356 }
1357 const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
1358 ...(yield* withEventBase({
1359 aggregateKind: "thread",
1360 aggregateId: command.threadId,
1361 occurredAt: command.createdAt,
1362 commandId: command.commandId,
1363 })),
1364 type: "thread.unsettled",
1365 payload: {
1366 threadId: command.threadId,
1367 reason: "activity",
1368 updatedAt: command.createdAt,
1369 },
1370 };
1371 return [unsettledEvent, activityAppendedEvent];
1372 }
1373
1374 default: {
1375 command satisfies never;
1376 const fallback = command as never as { type: string };
1377 return yield* new OrchestrationCommandInvariantError({
1378 commandType: fallback.type,
1379 detail: `Unknown command type: ${fallback.type}`,
1380 });
1381 }
1382 }
1383});