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