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