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

decider.ts

1,460 lines49.3 KB

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