Open History to see the last commit
1import { EventId } from "@t3tools/contracts";
2import {
3 type OrchestrationCommand,
4 type OrchestrationEvent,
5 type OrchestrationReadModel,
6} from "@t3tools/contracts/legacy-orchestration";
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: command.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": clear states that would keep the
513 // row pinned or snoozed instead of showing the new settled state.
514 const companionEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];
515 if (thread.pinnedAt != null) {
516 companionEvents.push({
517 ...(yield* withEventBase({
518 aggregateKind: "thread",
519 aggregateId: command.threadId,
520 occurredAt,
521 commandId: command.commandId,
522 })),
523 type: "thread.unpinned" as const,
524 payload: {
525 threadId: command.threadId,
526 updatedAt: occurredAt,
527 },
528 });
529 }
530 if (thread.snoozedUntil != null) {
531 companionEvents.push({
532 ...(yield* withEventBase({
533 aggregateKind: "thread",
534 aggregateId: command.threadId,
535 occurredAt,
536 commandId: command.commandId,
537 })),
538 type: "thread.unsnoozed",
539 payload: {
540 threadId: command.threadId,
541 reason: "user",
542 updatedAt: occurredAt,
543 },
544 });
545 }
546 return companionEvents.length > 0 ? [settledEvent, ...companionEvents] : settledEvent;
547 }
548
549 case "thread.unsettle": {
550 const thread = yield* requireThreadNotArchived({
551 readModel,
552 command,
553 threadId: command.threadId,
554 });
555 // Idempotent by re-emission (see thread.settle): reducing the event a
556 // second time lands on the same override state. A re-emission keeps
557 // the existing updatedAt so duplicates do not churn ordering.
558 const alreadyPinnedActive = thread.settledOverride === "active";
559 const occurredAt = yield* nowIso;
560 return {
561 ...(yield* withEventBase({
562 aggregateKind: "thread",
563 aggregateId: command.threadId,
564 occurredAt,
565 commandId: command.commandId,
566 })),
567 type: "thread.unsettled",
568 payload: {
569 threadId: command.threadId,
570 reason: command.reason,
571 updatedAt: alreadyPinnedActive ? thread.updatedAt : occurredAt,
572 },
573 };
574 }
575
576 case "thread.snooze": {
577 const thread = yield* requireThreadNotArchived({
578 readModel,
579 command,
580 threadId: command.threadId,
581 });
582 const occurredAt = yield* nowIso;
583 // A wake time in the past would create a thread that is snoozed and
584 // woken at once — the row would never leave the inbox but still carry
585 // snooze state. Reject instead of silently normalizing. The negated
586 // comparison also catches unparseable wake times (IsoDateTime is
587 // structurally just a string): NaN fails every comparison, and an
588 // unparseable snoozedUntil must never persist.
589 if (!(Date.parse(command.snoozedUntil) > Date.parse(occurredAt))) {
590 return yield* Effect.fail(
591 new OrchestrationCommandInvariantError({
592 commandType: command.type,
593 detail: `thread ${command.threadId} snooze wake time ${command.snoozedUntil} is not in the future`,
594 }),
595 );
596 }
597 // Blocked-on-you work must not be snoozed away: a pending approval or
598 // user-input request is the agent waiting on the user, and hiding it
599 // defeats the request. (A running session IS snoozable — snooze only
600 // affects visibility, never the agent.)
601 if (hasOpenBlockingRequest(thread)) {
602 return yield* Effect.fail(
603 new OrchestrationCommandInvariantError({
604 commandType: command.type,
605 detail: `thread ${command.threadId} has a pending approval or user-input request and cannot be snoozed`,
606 }),
607 );
608 }
609 // A queued turn start — a user message no turn has adopted yet — is
610 // invisible pending work: no session, no pending flags. Snoozing in
611 // that window would hide a just-requested turn exactly the way settle
612 // would.
613 if (threadHasQueuedTurnStart(thread, occurredAt)) {
614 return yield* Effect.fail(
615 new OrchestrationCommandInvariantError({
616 commandType: command.type,
617 detail: `thread ${command.threadId} has a queued turn start and cannot be snoozed`,
618 }),
619 );
620 }
621 // Re-snoozing an already-snoozed thread to the SAME wake time is a
622 // duplicate (double-click, raced clients): re-emit with the original
623 // timestamps so the projection is a no-op. A different wake time is a
624 // real change and stamps fresh.
625 const existingSnoozedAt =
626 thread.snoozedUntil === command.snoozedUntil && thread.snoozedAt != null
627 ? thread.snoozedAt
628 : null;
629 return {
630 ...(yield* withEventBase({
631 aggregateKind: "thread",
632 aggregateId: command.threadId,
633 occurredAt,
634 commandId: command.commandId,
635 })),
636 type: "thread.snoozed",
637 payload: {
638 threadId: command.threadId,
639 snoozedUntil: command.snoozedUntil,
640 snoozedAt: existingSnoozedAt ?? occurredAt,
641 updatedAt: existingSnoozedAt !== null ? thread.updatedAt : occurredAt,
642 },
643 };
644 }
645
646 case "thread.unsnooze": {
647 const thread = yield* requireThreadNotArchived({
648 readModel,
649 command,
650 threadId: command.threadId,
651 });
652 // Idempotent by re-emission (see thread.settle): waking a thread that
653 // is not snoozed lands on the same null state without churning
654 // updatedAt.
655 const alreadyAwake = thread.snoozedUntil == null;
656 const occurredAt = yield* nowIso;
657 return {
658 ...(yield* withEventBase({
659 aggregateKind: "thread",
660 aggregateId: command.threadId,
661 occurredAt,
662 commandId: command.commandId,
663 })),
664 type: "thread.unsnoozed",
665 payload: {
666 threadId: command.threadId,
667 reason: command.reason,
668 updatedAt: alreadyAwake ? thread.updatedAt : occurredAt,
669 },
670 };
671 }
672
673 case "thread.pin": {
674 const thread = yield* requireThreadNotArchived({
675 readModel,
676 command,
677 threadId: command.threadId,
678 });
679 const occurredAt = yield* nowIso;
680 // Re-pinning an already-pinned thread is a duplicate (double-click,
681 // raced clients): re-emit with the original timestamps so the
682 // projection is a no-op. Pinning has no lifecycle invariants — a pin
683 // only ever promotes visibility, so it can never hide pending work.
684 const existingPinnedAt = thread.pinnedAt ?? null;
685 const pinnedEvent = {
686 ...(yield* withEventBase({
687 aggregateKind: "thread",
688 aggregateId: command.threadId,
689 occurredAt,
690 commandId: command.commandId,
691 })),
692 type: "thread.pinned" as const,
693 payload: {
694 threadId: command.threadId,
695 pinnedAt: existingPinnedAt ?? occurredAt,
696 // A fresh pin takes the client's slot in the arranged order; on a
697 // re-pin the existing key wins so raced duplicates cannot move a
698 // thread the user already placed.
699 ...(existingPinnedAt === null && command.orderKey !== undefined
700 ? { pinOrderKey: command.orderKey }
701 : {}),
702 updatedAt: existingPinnedAt !== null ? thread.updatedAt : occurredAt,
703 },
704 };
705 // Pinning is a promotion: it clears the parked states rather than
706 // silently outranking them. An explicit settle un-settles (reason
707 // "user", same override the un-settle button stamps), and a snooze's
708 // return ticket is spent — the thread is on top NOW, not on Tuesday.
709 const promotionEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];
710 if (thread.settledOverride === "settled") {
711 promotionEvents.push({
712 ...(yield* withEventBase({
713 aggregateKind: "thread",
714 aggregateId: command.threadId,
715 occurredAt,
716 commandId: command.commandId,
717 })),
718 type: "thread.unsettled",
719 payload: {
720 threadId: command.threadId,
721 reason: "user",
722 updatedAt: occurredAt,
723 },
724 });
725 }
726 if (thread.snoozedUntil != null) {
727 promotionEvents.push({
728 ...(yield* withEventBase({
729 aggregateKind: "thread",
730 aggregateId: command.threadId,
731 occurredAt,
732 commandId: command.commandId,
733 })),
734 type: "thread.unsnoozed",
735 payload: {
736 threadId: command.threadId,
737 reason: "user",
738 updatedAt: occurredAt,
739 },
740 });
741 }
742 return promotionEvents.length > 0 ? [pinnedEvent, ...promotionEvents] : pinnedEvent;
743 }
744
745 case "thread.unpin": {
746 const thread = yield* requireThreadNotArchived({
747 readModel,
748 command,
749 threadId: command.threadId,
750 });
751 // Idempotent by re-emission (see thread.settle): unpinning a thread
752 // that is not pinned lands on the same null state without churning
753 // updatedAt.
754 const alreadyUnpinned = thread.pinnedAt == null;
755 const occurredAt = yield* nowIso;
756 return {
757 ...(yield* withEventBase({
758 aggregateKind: "thread",
759 aggregateId: command.threadId,
760 occurredAt,
761 commandId: command.commandId,
762 })),
763 type: "thread.unpinned",
764 payload: {
765 threadId: command.threadId,
766 updatedAt: alreadyUnpinned ? thread.updatedAt : occurredAt,
767 },
768 };
769 }
770
771 case "thread.pin.reorder": {
772 const thread = yield* requireThreadNotArchived({
773 readModel,
774 command,
775 threadId: command.threadId,
776 });
777 // Only pinned threads have a slot in the arranged order. Rejecting
778 // (rather than silently pinning) keeps a raced reorder-after-unpin
779 // from resurrecting a pin the user just cleared.
780 if (thread.pinnedAt == null) {
781 return yield* Effect.fail(
782 new OrchestrationCommandInvariantError({
783 commandType: command.type,
784 detail: `thread ${command.threadId} is not pinned and cannot be reordered`,
785 }),
786 );
787 }
788 // Idempotent by re-emission (see thread.settle): a duplicate drop on
789 // the same slot keeps the existing updatedAt so it projects as a no-op.
790 const keyUnchanged = thread.pinOrderKey === command.orderKey;
791 const occurredAt = yield* nowIso;
792 return {
793 ...(yield* withEventBase({
794 aggregateKind: "thread",
795 aggregateId: command.threadId,
796 occurredAt,
797 commandId: command.commandId,
798 })),
799 type: "thread.pin-reordered",
800 payload: {
801 threadId: command.threadId,
802 orderKey: command.orderKey,
803 updatedAt: keyUnchanged ? thread.updatedAt : occurredAt,
804 },
805 };
806 }
807
808 case "thread.meta.update": {
809 const thread = yield* requireThread({
810 readModel,
811 command,
812 threadId: command.threadId,
813 });
814 const branch =
815 command.branch !== undefined &&
816 command.expectedBranch !== undefined &&
817 thread.branch !== command.expectedBranch
818 ? thread.branch
819 : command.branch;
820 const occurredAt = yield* nowIso;
821 return {
822 ...(yield* withEventBase({
823 aggregateKind: "thread",
824 aggregateId: command.threadId,
825 occurredAt,
826 commandId: command.commandId,
827 })),
828 type: "thread.meta-updated",
829 payload: {
830 threadId: command.threadId,
831 ...(command.title !== undefined ? { title: command.title } : {}),
832 ...(command.regenerateTitle === true
833 ? {
834 regenerateTitle: true as const,
835 previousTitle: thread.title,
836 titleRegeneration: {
837 requestId: command.commandId,
838 startedAt: occurredAt,
839 },
840 }
841 : {}),
842 ...(command.title !== undefined && thread.titleRegeneration != null
843 ? { titleRegeneration: null }
844 : {}),
845 ...(command.modelSelection !== undefined
846 ? { modelSelection: command.modelSelection }
847 : {}),
848 ...(branch !== undefined ? { branch } : {}),
849 ...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),
850 ...(command.linkedPullRequest !== undefined
851 ? { linkedPullRequest: command.linkedPullRequest }
852 : {}),
853 updatedAt: occurredAt,
854 },
855 };
856 }
857
858 case "thread.title.regeneration.complete": {
859 const thread = yield* requireThread({
860 readModel,
861 command,
862 threadId: command.threadId,
863 });
864 const requestIsCurrent = thread.titleRegeneration?.requestId === command.requestId;
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.meta-updated",
874 payload: {
875 threadId: command.threadId,
876 ...(requestIsCurrent && command.title !== undefined ? { title: command.title } : {}),
877 ...(requestIsCurrent ? { titleRegeneration: null } : {}),
878 updatedAt: requestIsCurrent ? occurredAt : thread.updatedAt,
879 },
880 };
881 }
882
883 case "thread.runtime-mode.set": {
884 yield* requireThread({
885 readModel,
886 command,
887 threadId: command.threadId,
888 });
889 const occurredAt = yield* nowIso;
890 return {
891 ...(yield* withEventBase({
892 aggregateKind: "thread",
893 aggregateId: command.threadId,
894 occurredAt,
895 commandId: command.commandId,
896 })),
897 type: "thread.runtime-mode-set",
898 payload: {
899 threadId: command.threadId,
900 runtimeMode: command.runtimeMode,
901 updatedAt: occurredAt,
902 },
903 };
904 }
905
906 case "thread.interaction-mode.set": {
907 yield* requireThread({
908 readModel,
909 command,
910 threadId: command.threadId,
911 });
912 const occurredAt = yield* nowIso;
913 return {
914 ...(yield* withEventBase({
915 aggregateKind: "thread",
916 aggregateId: command.threadId,
917 occurredAt,
918 commandId: command.commandId,
919 })),
920 type: "thread.interaction-mode-set",
921 payload: {
922 threadId: command.threadId,
923 interactionMode: command.interactionMode,
924 updatedAt: occurredAt,
925 },
926 };
927 }
928
929 case "thread.turn.start": {
930 const targetThread = yield* requireThread({
931 readModel,
932 command,
933 threadId: command.threadId,
934 });
935 const sourceProposedPlan = command.sourceProposedPlan;
936 const sourceThread = sourceProposedPlan
937 ? yield* requireThread({
938 readModel,
939 command,
940 threadId: sourceProposedPlan.threadId,
941 })
942 : null;
943 const sourcePlan =
944 sourceProposedPlan && sourceThread
945 ? sourceThread.proposedPlans.find((entry) => entry.id === sourceProposedPlan.planId)
946 : null;
947 if (sourceProposedPlan && !sourcePlan) {
948 return yield* new OrchestrationCommandInvariantError({
949 commandType: command.type,
950 detail: `Proposed plan '${sourceProposedPlan.planId}' does not exist on thread '${sourceProposedPlan.threadId}'.`,
951 });
952 }
953 if (sourceThread && sourceThread.projectId !== targetThread.projectId) {
954 return yield* new OrchestrationCommandInvariantError({
955 commandType: command.type,
956 detail: `Proposed plan '${sourceProposedPlan?.planId}' belongs to thread '${sourceThread.id}' in a different project.`,
957 });
958 }
959 const userMessageEvent: Omit<OrchestrationEvent, "sequence"> = {
960 ...(yield* withEventBase({
961 aggregateKind: "thread",
962 aggregateId: command.threadId,
963 occurredAt: command.createdAt,
964 commandId: command.commandId,
965 })),
966 type: "thread.message-sent",
967 payload: {
968 threadId: command.threadId,
969 messageId: command.message.messageId,
970 role: "user",
971 text: command.message.text,
972 attachments: command.message.attachments,
973 turnId: null,
974 streaming: false,
975 createdAt: command.createdAt,
976 updatedAt: command.createdAt,
977 },
978 };
979 const turnStartRequestedEvent: Omit<OrchestrationEvent, "sequence"> = {
980 ...(yield* withEventBase({
981 aggregateKind: "thread",
982 aggregateId: command.threadId,
983 occurredAt: command.createdAt,
984 commandId: command.commandId,
985 })),
986 causationEventId: userMessageEvent.eventId,
987 type: "thread.turn-start-requested",
988 payload: {
989 threadId: command.threadId,
990 messageId: command.message.messageId,
991 ...(command.modelSelection !== undefined
992 ? { modelSelection: command.modelSelection }
993 : {}),
994 ...(command.titleSeed !== undefined ? { titleSeed: command.titleSeed } : {}),
995 runtimeMode: targetThread.runtimeMode,
996 interactionMode: targetThread.interactionMode,
997 ...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),
998 createdAt: command.createdAt,
999 },
1000 };
1001 // Real activity resets ANY override: it wakes an explicitly settled
1002 // thread, and it clears a keep-active pin back to neutral so the
1003 // thread can auto-settle again after this burst of work goes stale.
1004 // A snooze clears the same way — sending a message to a snoozed
1005 // thread is the user re-engaging, so the return ticket is spent.
1006 const lifecycleResetEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];
1007 if (targetThread.settledOverride !== null) {
1008 lifecycleResetEvents.push({
1009 ...(yield* withEventBase({
1010 aggregateKind: "thread",
1011 aggregateId: command.threadId,
1012 occurredAt: command.createdAt,
1013 commandId: command.commandId,
1014 })),
1015 type: "thread.unsettled",
1016 payload: {
1017 threadId: command.threadId,
1018 reason: "activity",
1019 updatedAt: command.createdAt,
1020 },
1021 });
1022 }
1023 if (targetThread.snoozedUntil != null) {
1024 lifecycleResetEvents.push({
1025 ...(yield* withEventBase({
1026 aggregateKind: "thread",
1027 aggregateId: command.threadId,
1028 occurredAt: command.createdAt,
1029 commandId: command.commandId,
1030 })),
1031 type: "thread.unsnoozed",
1032 payload: {
1033 threadId: command.threadId,
1034 reason: "activity",
1035 updatedAt: command.createdAt,
1036 },
1037 });
1038 }
1039 return [...lifecycleResetEvents, userMessageEvent, turnStartRequestedEvent];
1040 }
1041
1042 case "thread.turn.interrupt": {
1043 yield* requireThread({
1044 readModel,
1045 command,
1046 threadId: command.threadId,
1047 });
1048 return {
1049 ...(yield* withEventBase({
1050 aggregateKind: "thread",
1051 aggregateId: command.threadId,
1052 occurredAt: command.createdAt,
1053 commandId: command.commandId,
1054 })),
1055 type: "thread.turn-interrupt-requested",
1056 payload: {
1057 threadId: command.threadId,
1058 ...(command.turnId !== undefined ? { turnId: command.turnId } : {}),
1059 createdAt: command.createdAt,
1060 },
1061 };
1062 }
1063
1064 case "thread.approval.respond": {
1065 yield* requireThread({
1066 readModel,
1067 command,
1068 threadId: command.threadId,
1069 });
1070 return {
1071 ...(yield* withEventBase({
1072 aggregateKind: "thread",
1073 aggregateId: command.threadId,
1074 occurredAt: command.createdAt,
1075 commandId: command.commandId,
1076 metadata: {
1077 requestId: command.requestId,
1078 },
1079 })),
1080 type: "thread.approval-response-requested",
1081 payload: {
1082 threadId: command.threadId,
1083 requestId: command.requestId,
1084 decision: command.decision,
1085 createdAt: command.createdAt,
1086 },
1087 };
1088 }
1089
1090 case "thread.user-input.respond": {
1091 yield* requireThread({
1092 readModel,
1093 command,
1094 threadId: command.threadId,
1095 });
1096 return {
1097 ...(yield* withEventBase({
1098 aggregateKind: "thread",
1099 aggregateId: command.threadId,
1100 occurredAt: command.createdAt,
1101 commandId: command.commandId,
1102 metadata: {
1103 requestId: command.requestId,
1104 },
1105 })),
1106 type: "thread.user-input-response-requested",
1107 payload: {
1108 threadId: command.threadId,
1109 requestId: command.requestId,
1110 answers: command.answers,
1111 createdAt: command.createdAt,
1112 },
1113 };
1114 }
1115
1116 case "thread.checkpoint.revert": {
1117 yield* requireThread({
1118 readModel,
1119 command,
1120 threadId: command.threadId,
1121 });
1122 return {
1123 ...(yield* withEventBase({
1124 aggregateKind: "thread",
1125 aggregateId: command.threadId,
1126 occurredAt: command.createdAt,
1127 commandId: command.commandId,
1128 })),
1129 type: "thread.checkpoint-revert-requested",
1130 payload: {
1131 threadId: command.threadId,
1132 turnCount: command.turnCount,
1133 createdAt: command.createdAt,
1134 },
1135 };
1136 }
1137
1138 case "thread.session.stop": {
1139 const thread = yield* requireThread({
1140 readModel,
1141 command,
1142 threadId: command.threadId,
1143 });
1144 // Settle-cleanup stops are conditional: between the settle landing and
1145 // this command, another client may have re-engaged the thread (a turn
1146 // start unsettles it and brings the session alive). Commands are
1147 // decided serially against this read model, so checking here — not in
1148 // the dispatcher's pre-settle snapshot — closes that race.
1149 if (command.onlyIfSettled === true) {
1150 const sessionComingAlive =
1151 thread.session?.status === "starting" || thread.session?.status === "running";
1152 if (
1153 thread.settledOverride !== "settled" ||
1154 sessionComingAlive ||
1155 threadHasQueuedTurnStart(thread, command.createdAt)
1156 ) {
1157 return yield* Effect.fail(
1158 new OrchestrationCommandInvariantError({
1159 commandType: command.type,
1160 detail: `thread ${command.threadId} was re-engaged after settle; skipping session stop`,
1161 }),
1162 );
1163 }
1164 }
1165 return {
1166 ...(yield* withEventBase({
1167 aggregateKind: "thread",
1168 aggregateId: command.threadId,
1169 occurredAt: command.createdAt,
1170 commandId: command.commandId,
1171 })),
1172 type: "thread.session-stop-requested",
1173 payload: {
1174 threadId: command.threadId,
1175 createdAt: command.createdAt,
1176 },
1177 };
1178 }
1179
1180 case "thread.session.set": {
1181 const thread = yield* requireThread({
1182 readModel,
1183 command,
1184 threadId: command.threadId,
1185 });
1186 const sessionSetEvent: Omit<OrchestrationEvent, "sequence"> = {
1187 ...(yield* withEventBase({
1188 aggregateKind: "thread",
1189 aggregateId: command.threadId,
1190 occurredAt: command.createdAt,
1191 commandId: command.commandId,
1192 metadata: {},
1193 })),
1194 type: "thread.session-set",
1195 payload: {
1196 threadId: command.threadId,
1197 session: command.session,
1198 },
1199 };
1200 // Only a session coming alive is activity worth waking a settled thread
1201 // for — status writes like ready/stopped/error arrive after the fact and
1202 // must not fight a user's explicit settle. Snooze is deliberately NOT
1203 // cleared here: snooze never pauses the agent, so its session starting
1204 // or erroring is not the user re-engaging. Blocked/failed work still
1205 // surfaces immediately — effectiveSnoozed refuses to classify a thread
1206 // with a raised hand (approval / input / failure / fresh completion)
1207 // as snoozed, without spending the return ticket.
1208 const isSessionActivity =
1209 command.session.status === "starting" || command.session.status === "running";
1210 // Real activity resets ANY override (settled wakes, active unpins).
1211 if (thread.settledOverride === null || !isSessionActivity) {
1212 return sessionSetEvent;
1213 }
1214 const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
1215 ...(yield* withEventBase({
1216 aggregateKind: "thread",
1217 aggregateId: command.threadId,
1218 occurredAt: command.createdAt,
1219 commandId: command.commandId,
1220 })),
1221 type: "thread.unsettled",
1222 payload: {
1223 threadId: command.threadId,
1224 reason: "activity",
1225 updatedAt: command.createdAt,
1226 },
1227 };
1228 return [unsettledEvent, sessionSetEvent];
1229 }
1230
1231 case "thread.message.assistant.delta": {
1232 yield* requireThread({
1233 readModel,
1234 command,
1235 threadId: command.threadId,
1236 });
1237 return {
1238 ...(yield* withEventBase({
1239 aggregateKind: "thread",
1240 aggregateId: command.threadId,
1241 occurredAt: command.createdAt,
1242 commandId: command.commandId,
1243 })),
1244 type: "thread.message-sent",
1245 payload: {
1246 threadId: command.threadId,
1247 messageId: command.messageId,
1248 role: "assistant",
1249 text: command.delta,
1250 turnId: command.turnId ?? null,
1251 streaming: true,
1252 createdAt: command.createdAt,
1253 updatedAt: command.createdAt,
1254 },
1255 };
1256 }
1257
1258 case "thread.message.assistant.complete": {
1259 yield* requireThread({
1260 readModel,
1261 command,
1262 threadId: command.threadId,
1263 });
1264 return {
1265 ...(yield* withEventBase({
1266 aggregateKind: "thread",
1267 aggregateId: command.threadId,
1268 occurredAt: command.createdAt,
1269 commandId: command.commandId,
1270 })),
1271 type: "thread.message-sent",
1272 payload: {
1273 threadId: command.threadId,
1274 messageId: command.messageId,
1275 role: "assistant",
1276 text: "",
1277 turnId: command.turnId ?? null,
1278 streaming: false,
1279 createdAt: command.createdAt,
1280 updatedAt: command.createdAt,
1281 },
1282 };
1283 }
1284
1285 case "thread.proposed-plan.upsert": {
1286 yield* requireThread({
1287 readModel,
1288 command,
1289 threadId: command.threadId,
1290 });
1291 return {
1292 ...(yield* withEventBase({
1293 aggregateKind: "thread",
1294 aggregateId: command.threadId,
1295 occurredAt: command.createdAt,
1296 commandId: command.commandId,
1297 })),
1298 type: "thread.proposed-plan-upserted",
1299 payload: {
1300 threadId: command.threadId,
1301 proposedPlan: command.proposedPlan,
1302 },
1303 };
1304 }
1305
1306 case "thread.turn.diff.complete": {
1307 yield* requireThread({
1308 readModel,
1309 command,
1310 threadId: command.threadId,
1311 });
1312 return {
1313 ...(yield* withEventBase({
1314 aggregateKind: "thread",
1315 aggregateId: command.threadId,
1316 occurredAt: command.createdAt,
1317 commandId: command.commandId,
1318 })),
1319 type: "thread.turn-diff-completed",
1320 payload: {
1321 threadId: command.threadId,
1322 turnId: command.turnId,
1323 checkpointTurnCount: command.checkpointTurnCount,
1324 checkpointRef: command.checkpointRef,
1325 status: command.status,
1326 files: command.files,
1327 assistantMessageId: command.assistantMessageId ?? null,
1328 completedAt: command.completedAt,
1329 },
1330 };
1331 }
1332
1333 case "thread.revert.complete": {
1334 yield* requireThread({
1335 readModel,
1336 command,
1337 threadId: command.threadId,
1338 });
1339 return {
1340 ...(yield* withEventBase({
1341 aggregateKind: "thread",
1342 aggregateId: command.threadId,
1343 occurredAt: command.createdAt,
1344 commandId: command.commandId,
1345 })),
1346 type: "thread.reverted",
1347 payload: {
1348 threadId: command.threadId,
1349 turnCount: command.turnCount,
1350 },
1351 };
1352 }
1353
1354 case "thread.activity.append": {
1355 const thread = yield* requireThread({
1356 readModel,
1357 command,
1358 threadId: command.threadId,
1359 });
1360 const requestId =
1361 typeof command.activity.payload === "object" &&
1362 command.activity.payload !== null &&
1363 "requestId" in command.activity.payload &&
1364 typeof (command.activity.payload as { requestId?: unknown }).requestId === "string"
1365 ? ((command.activity.payload as { requestId: string })
1366 .requestId as OrchestrationEvent["metadata"]["requestId"])
1367 : undefined;
1368 const activityAppendedEvent: Omit<OrchestrationEvent, "sequence"> = {
1369 ...(yield* withEventBase({
1370 aggregateKind: "thread",
1371 aggregateId: command.threadId,
1372 occurredAt: command.createdAt,
1373 commandId: command.commandId,
1374 ...(requestId !== undefined ? { metadata: { requestId } } : {}),
1375 })),
1376 type: "thread.activity-appended",
1377 payload: {
1378 threadId: command.threadId,
1379 activity: command.activity,
1380 },
1381 };
1382 // An approval or user-input request is blocked-on-you work — it must
1383 // never stay hidden inside a settled slim row.
1384 const wakesSettledThread =
1385 command.activity.kind === "approval.requested" ||
1386 command.activity.kind === "user-input.requested";
1387 // Real activity resets ANY override (settled wakes, active unpins).
1388 if (thread.settledOverride === null || !wakesSettledThread) {
1389 return activityAppendedEvent;
1390 }
1391 const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
1392 ...(yield* withEventBase({
1393 aggregateKind: "thread",
1394 aggregateId: command.threadId,
1395 occurredAt: command.createdAt,
1396 commandId: command.commandId,
1397 })),
1398 type: "thread.unsettled",
1399 payload: {
1400 threadId: command.threadId,
1401 reason: "activity",
1402 updatedAt: command.createdAt,
1403 },
1404 };
1405 return [unsettledEvent, activityAppendedEvent];
1406 }
1407
1408 default: {
1409 command satisfies never;
1410 const fallback = command as never as { type: string };
1411 return yield* new OrchestrationCommandInvariantError({
1412 commandType: fallback.type,
1413 detail: `Unknown command type: ${fallback.type}`,
1414 });
1415 }
1416 }
1417});