Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

decider.ts

1,380 lines46.3 KB

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