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

decider.ts

1,388 lines46.6 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 // Project creation has no user model choice. Older clients sent an
223 // automatic seed here, but only a metadata update records an
224 // explicit project default.
225 defaultModelSelection: null,
226 faviconPath: null,
227 scripts: [],
228 createdAt: command.createdAt,
229 updatedAt: command.createdAt,
230 },
231 };
232 }
233​
234 case "project.meta.update": {
235 yield* requireProject({
236 readModel,
237 command,
238 projectId: command.projectId,
239 });
240 if (command.workspaceRoot !== undefined) {
241 yield* requireActiveProjectWorkspaceRootAbsent({
242 readModel,
243 command,
244 workspaceRoot: command.workspaceRoot,
245 exceptProjectId: command.projectId,
246 });
247 }
248 const occurredAt = yield* nowIso;
249 return {
250 ...(yield* withEventBase({
251 aggregateKind: "project",
252 aggregateId: command.projectId,
253 occurredAt,
254 commandId: command.commandId,
255 })),
256 type: "project.meta-updated",
257 payload: {
258 projectId: command.projectId,
259 ...(command.title !== undefined ? { title: command.title } : {}),
260 ...(command.workspaceRoot !== undefined ? { workspaceRoot: command.workspaceRoot } : {}),
261 ...(command.defaultModelSelection !== undefined
262 ? { defaultModelSelection: command.defaultModelSelection }
263 : {}),
264 ...(command.defaultThreadEnvMode !== undefined
265 ? { defaultThreadEnvMode: command.defaultThreadEnvMode }
266 : {}),
267 ...(command.autoPull !== undefined ? { autoPull: command.autoPull } : {}),
268 ...(command.faviconPath !== undefined ? { faviconPath: command.faviconPath } : {}),
269 ...(command.scripts !== undefined ? { scripts: command.scripts } : {}),
270 updatedAt: occurredAt,
271 },
272 };
273 }
274​
275 case "project.delete": {
276 yield* requireProject({
277 readModel,
278 command,
279 projectId: command.projectId,
280 });
281 const activeThreads = listThreadsByProjectId(readModel, command.projectId).filter(
282 (thread) => thread.deletedAt === null,
283 );
284 if (activeThreads.length > 0 && command.force !== true) {
285 return yield* new OrchestrationCommandInvariantError({
286 commandType: command.type,
287 detail: `Project '${command.projectId}' is not empty and cannot be deleted without force=true.`,
288 });
289 }
290 if (activeThreads.length > 0) {
291 return yield* decideCommandSequence({
292 readModel,
293 commands: [
294 ...activeThreads.map(
295 (thread): Extract<OrchestrationCommand, { type: "thread.delete" }> => ({
296 type: "thread.delete",
297 commandId: command.commandId,
298 threadId: thread.id,
299 }),
300 ),
301 {
302 type: "project.delete",
303 commandId: command.commandId,
304 projectId: command.projectId,
305 },
306 ],
307 });
308 }
309​
310 const occurredAt = yield* nowIso;
311 return {
312 ...(yield* withEventBase({
313 aggregateKind: "project",
314 aggregateId: command.projectId,
315 occurredAt,
316 commandId: command.commandId,
317 })),
318 type: "project.deleted" as const,
319 payload: {
320 projectId: command.projectId,
321 deletedAt: occurredAt,
322 },
323 };
324 }
325​
326 case "thread.create": {
327 yield* requireProject({
328 readModel,
329 command,
330 projectId: command.projectId,
331 });
332 yield* requireThreadAbsent({
333 readModel,
334 command,
335 threadId: command.threadId,
336 });
337 return {
338 ...(yield* withEventBase({
339 aggregateKind: "thread",
340 aggregateId: command.threadId,
341 occurredAt: command.createdAt,
342 commandId: command.commandId,
343 })),
344 type: "thread.created",
345 payload: {
346 threadId: command.threadId,
347 projectId: command.projectId,
348 title: command.title,
349 modelSelection: command.modelSelection,
350 runtimeMode: command.runtimeMode,
351 interactionMode: command.interactionMode,
352 branch: command.branch,
353 worktreePath: command.worktreePath,
354 createdAt: command.createdAt,
355 updatedAt: command.createdAt,
356 },
357 };
358 }
359​
360 case "thread.delete": {
361 yield* requireThread({
362 readModel,
363 command,
364 threadId: command.threadId,
365 });
366 const occurredAt = yield* nowIso;
367 return {
368 ...(yield* withEventBase({
369 aggregateKind: "thread",
370 aggregateId: command.threadId,
371 occurredAt,
372 commandId: command.commandId,
373 })),
374 type: "thread.deleted",
375 payload: {
376 threadId: command.threadId,
377 deletedAt: occurredAt,
378 },
379 };
380 }
381​
382 case "thread.archive": {
383 yield* requireThreadNotArchived({
384 readModel,
385 command,
386 threadId: command.threadId,
387 });
388 const occurredAt = yield* nowIso;
389 return {
390 ...(yield* withEventBase({
391 aggregateKind: "thread",
392 aggregateId: command.threadId,
393 occurredAt,
394 commandId: command.commandId,
395 })),
396 type: "thread.archived",
397 payload: {
398 threadId: command.threadId,
399 archivedAt: occurredAt,
400 updatedAt: occurredAt,
401 },
402 };
403 }
404​
405 case "thread.unarchive": {
406 yield* requireThreadArchived({
407 readModel,
408 command,
409 threadId: command.threadId,
410 });
411 const occurredAt = yield* nowIso;
412 return {
413 ...(yield* withEventBase({
414 aggregateKind: "thread",
415 aggregateId: command.threadId,
416 occurredAt,
417 commandId: command.commandId,
418 })),
419 type: "thread.unarchived",
420 payload: {
421 threadId: command.threadId,
422 updatedAt: occurredAt,
423 },
424 };
425 }
426​
427 case "thread.settle":
428 case "thread.auto-settle": {
429 const thread = yield* requireThreadNotArchived({
430 readModel,
431 command,
432 threadId: command.threadId,
433 });
434 if (command.type === "thread.auto-settle" && thread.settledOverride !== null) {
435 return yield* Effect.fail(
436 new OrchestrationCommandInvariantError({
437 commandType: command.type,
438 detail: `thread ${command.threadId} changed before automatic settlement`,
439 }),
440 );
441 }
442 // The server owns settle eligibility. A stale command must not settle
443 // a thread whose session is coming alive or working.
444 if (thread.session?.status === "starting" || thread.session?.status === "running") {
445 return yield* new OrchestrationThreadSettleBlockedError({ threadId: command.threadId });
446 }
447 // Pending approval / user-input requests are blocked-on-you work: a
448 // raced or stale client must not park them behind a settled override
449 // that would surface only after the request resolves.
450 if (hasOpenBlockingRequest(thread)) {
451 return yield* new OrchestrationThreadSettleBlockedError({ threadId: command.threadId });
452 }
453 const occurredAt = yield* nowIso;
454 // Settling inside the adoption window would hide just-requested work.
455 if (hasQueuedTurnStartForThread(thread, occurredAt)) {
456 return yield* new OrchestrationThreadSettleBlockedError({ threadId: command.threadId });
457 }
458 // Settling an already-settled thread re-emits with the original
459 // settledAt: the engine rejects zero-event commands, and bulk-settle /
460 // double-click must stay silent no-ops rather than surface errors.
461 const alreadySettled = thread.settledOverride === "settled" && thread.settledAt !== null;
462 const settledEvent = {
463 ...(yield* withEventBase({
464 aggregateKind: "thread",
465 aggregateId: command.threadId,
466 occurredAt,
467 commandId: command.commandId,
468 })),
469 type: "thread.settled" as const,
470 payload: {
471 threadId: command.threadId,
472 settledAt: alreadySettled
473 ? thread.settledAt
474 : command.type === "thread.auto-settle"
475 ? command.settledAt
476 : occurredAt,
477 // A re-emission is a projected no-op: keep the existing updatedAt
478 // so duplicate settles neither rewind nor churn ordering. A fresh
479 // settle stamps the command time.
480 updatedAt: alreadySettled ? thread.updatedAt : occurredAt,
481 },
482 };
483 // Settling is "I'm done with this": clear states that would keep the
484 // row pinned or snoozed instead of showing the new settled state.
485 const companionEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];
486 if (thread.pinnedAt != null) {
487 companionEvents.push({
488 ...(yield* withEventBase({
489 aggregateKind: "thread",
490 aggregateId: command.threadId,
491 occurredAt,
492 commandId: command.commandId,
493 })),
494 type: "thread.unpinned" as const,
495 payload: {
496 threadId: command.threadId,
497 updatedAt: occurredAt,
498 },
499 });
500 }
501 if (thread.snoozedUntil != null) {
502 companionEvents.push({
503 ...(yield* withEventBase({
504 aggregateKind: "thread",
505 aggregateId: command.threadId,
506 occurredAt,
507 commandId: command.commandId,
508 })),
509 type: "thread.unsnoozed",
510 payload: {
511 threadId: command.threadId,
512 reason: "user",
513 updatedAt: occurredAt,
514 },
515 });
516 }
517 return companionEvents.length > 0 ? [settledEvent, ...companionEvents] : settledEvent;
518 }
519​
520 case "thread.unsettle": {
521 const thread = yield* requireThreadNotArchived({
522 readModel,
523 command,
524 threadId: command.threadId,
525 });
526 // Idempotent by re-emission (see thread.settle): reducing the event a
527 // second time lands on the same override state. A re-emission keeps
528 // the existing updatedAt so duplicates do not churn ordering.
529 const alreadyPinnedActive = thread.settledOverride === "active";
530 const occurredAt = yield* nowIso;
531 return {
532 ...(yield* withEventBase({
533 aggregateKind: "thread",
534 aggregateId: command.threadId,
535 occurredAt,
536 commandId: command.commandId,
537 })),
538 type: "thread.unsettled",
539 payload: {
540 threadId: command.threadId,
541 reason: command.reason,
542 updatedAt: alreadyPinnedActive ? thread.updatedAt : occurredAt,
543 },
544 };
545 }
546​
547 case "thread.snooze": {
548 const thread = yield* requireThreadNotArchived({
549 readModel,
550 command,
551 threadId: command.threadId,
552 });
553 const occurredAt = yield* nowIso;
554 // A wake time in the past would create a thread that is snoozed and
555 // woken at once — the row would never leave the inbox but still carry
556 // snooze state. Reject instead of silently normalizing. The negated
557 // comparison also catches unparseable wake times (IsoDateTime is
558 // structurally just a string): NaN fails every comparison, and an
559 // unparseable snoozedUntil must never persist.
560 if (!(Date.parse(command.snoozedUntil) > Date.parse(occurredAt))) {
561 return yield* Effect.fail(
562 new OrchestrationCommandInvariantError({
563 commandType: command.type,
564 detail: `thread ${command.threadId} snooze wake time ${command.snoozedUntil} is not in the future`,
565 }),
566 );
567 }
568 // Blocked-on-you work must not be snoozed away: a pending approval or
569 // user-input request is the agent waiting on the user, and hiding it
570 // defeats the request. (A running session IS snoozable — snooze only
571 // affects visibility, never the agent.)
572 if (hasOpenBlockingRequest(thread)) {
573 return yield* Effect.fail(
574 new OrchestrationCommandInvariantError({
575 commandType: command.type,
576 detail: `thread ${command.threadId} has a pending approval or user-input request and cannot be snoozed`,
577 }),
578 );
579 }
580 // A queued turn start — a user message no turn has adopted yet — is
581 // invisible pending work: no session, no pending flags. Snoozing in
582 // that window would hide a just-requested turn exactly the way settle
583 // would.
584 if (hasQueuedTurnStartForThread(thread, occurredAt)) {
585 return yield* Effect.fail(
586 new OrchestrationCommandInvariantError({
587 commandType: command.type,
588 detail: `thread ${command.threadId} has a queued turn start and cannot be snoozed`,
589 }),
590 );
591 }
592 // Re-snoozing an already-snoozed thread to the SAME wake time is a
593 // duplicate (double-click, raced clients): re-emit with the original
594 // timestamps so the projection is a no-op. A different wake time is a
595 // real change and stamps fresh.
596 const existingSnoozedAt =
597 thread.snoozedUntil === command.snoozedUntil && thread.snoozedAt != null
598 ? thread.snoozedAt
599 : null;
600 return {
601 ...(yield* withEventBase({
602 aggregateKind: "thread",
603 aggregateId: command.threadId,
604 occurredAt,
605 commandId: command.commandId,
606 })),
607 type: "thread.snoozed",
608 payload: {
609 threadId: command.threadId,
610 snoozedUntil: command.snoozedUntil,
611 snoozedAt: existingSnoozedAt ?? occurredAt,
612 updatedAt: existingSnoozedAt !== null ? thread.updatedAt : occurredAt,
613 },
614 };
615 }
616​
617 case "thread.unsnooze": {
618 const thread = yield* requireThreadNotArchived({
619 readModel,
620 command,
621 threadId: command.threadId,
622 });
623 // Idempotent by re-emission (see thread.settle): waking a thread that
624 // is not snoozed lands on the same null state without churning
625 // updatedAt.
626 const alreadyAwake = thread.snoozedUntil == null;
627 const occurredAt = yield* nowIso;
628 return {
629 ...(yield* withEventBase({
630 aggregateKind: "thread",
631 aggregateId: command.threadId,
632 occurredAt,
633 commandId: command.commandId,
634 })),
635 type: "thread.unsnoozed",
636 payload: {
637 threadId: command.threadId,
638 reason: command.reason,
639 updatedAt: alreadyAwake ? thread.updatedAt : occurredAt,
640 },
641 };
642 }
643​
644 case "thread.pin": {
645 const thread = yield* requireThreadNotArchived({
646 readModel,
647 command,
648 threadId: command.threadId,
649 });
650 const occurredAt = yield* nowIso;
651 // Re-pinning an already-pinned thread is a duplicate (double-click,
652 // raced clients): re-emit with the original timestamps so the
653 // projection is a no-op. Pinning has no lifecycle invariants — a pin
654 // only ever promotes visibility, so it can never hide pending work.
655 const existingPinnedAt = thread.pinnedAt ?? null;
656 const pinnedEvent = {
657 ...(yield* withEventBase({
658 aggregateKind: "thread",
659 aggregateId: command.threadId,
660 occurredAt,
661 commandId: command.commandId,
662 })),
663 type: "thread.pinned" as const,
664 payload: {
665 threadId: command.threadId,
666 pinnedAt: existingPinnedAt ?? occurredAt,
667 // A fresh pin takes the client's slot in the arranged order; on a
668 // re-pin the existing key wins so raced duplicates cannot move a
669 // thread the user already placed.
670 ...(existingPinnedAt === null && command.orderKey !== undefined
671 ? { pinOrderKey: command.orderKey }
672 : {}),
673 updatedAt: existingPinnedAt !== null ? thread.updatedAt : occurredAt,
674 },
675 };
676 // Pinning is a promotion: it clears the parked states rather than
677 // silently outranking them. An explicit settle un-settles (reason
678 // "user", same override the un-settle button stamps), and a snooze's
679 // return ticket is spent — the thread is on top NOW, not on Tuesday.
680 const promotionEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];
681 if (thread.settledOverride === "settled") {
682 promotionEvents.push({
683 ...(yield* withEventBase({
684 aggregateKind: "thread",
685 aggregateId: command.threadId,
686 occurredAt,
687 commandId: command.commandId,
688 })),
689 type: "thread.unsettled",
690 payload: {
691 threadId: command.threadId,
692 reason: "user",
693 updatedAt: occurredAt,
694 },
695 });
696 }
697 if (thread.snoozedUntil != null) {
698 promotionEvents.push({
699 ...(yield* withEventBase({
700 aggregateKind: "thread",
701 aggregateId: command.threadId,
702 occurredAt,
703 commandId: command.commandId,
704 })),
705 type: "thread.unsnoozed",
706 payload: {
707 threadId: command.threadId,
708 reason: "user",
709 updatedAt: occurredAt,
710 },
711 });
712 }
713 return promotionEvents.length > 0 ? [pinnedEvent, ...promotionEvents] : pinnedEvent;
714 }
715​
716 case "thread.unpin": {
717 const thread = yield* requireThreadNotArchived({
718 readModel,
719 command,
720 threadId: command.threadId,
721 });
722 // Idempotent by re-emission (see thread.settle): unpinning a thread
723 // that is not pinned lands on the same null state without churning
724 // updatedAt.
725 const alreadyUnpinned = thread.pinnedAt == null;
726 const occurredAt = yield* nowIso;
727 return {
728 ...(yield* withEventBase({
729 aggregateKind: "thread",
730 aggregateId: command.threadId,
731 occurredAt,
732 commandId: command.commandId,
733 })),
734 type: "thread.unpinned",
735 payload: {
736 threadId: command.threadId,
737 updatedAt: alreadyUnpinned ? thread.updatedAt : occurredAt,
738 },
739 };
740 }
741​
742 case "thread.pin.reorder": {
743 const thread = yield* requireThreadNotArchived({
744 readModel,
745 command,
746 threadId: command.threadId,
747 });
748 // Only pinned threads have a slot in the arranged order. Rejecting
749 // (rather than silently pinning) keeps a raced reorder-after-unpin
750 // from resurrecting a pin the user just cleared.
751 if (thread.pinnedAt == null) {
752 return yield* Effect.fail(
753 new OrchestrationCommandInvariantError({
754 commandType: command.type,
755 detail: `thread ${command.threadId} is not pinned and cannot be reordered`,
756 }),
757 );
758 }
759 // Idempotent by re-emission (see thread.settle): a duplicate drop on
760 // the same slot keeps the existing updatedAt so it projects as a no-op.
761 const keyUnchanged = thread.pinOrderKey === command.orderKey;
762 const occurredAt = yield* nowIso;
763 return {
764 ...(yield* withEventBase({
765 aggregateKind: "thread",
766 aggregateId: command.threadId,
767 occurredAt,
768 commandId: command.commandId,
769 })),
770 type: "thread.pin-reordered",
771 payload: {
772 threadId: command.threadId,
773 orderKey: command.orderKey,
774 updatedAt: keyUnchanged ? thread.updatedAt : occurredAt,
775 },
776 };
777 }
778​
779 case "thread.meta.update": {
780 const thread = yield* requireThread({
781 readModel,
782 command,
783 threadId: command.threadId,
784 });
785 const branch =
786 command.branch !== undefined &&
787 command.expectedBranch !== undefined &&
788 thread.branch !== command.expectedBranch
789 ? thread.branch
790 : command.branch;
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.meta-updated",
800 payload: {
801 threadId: command.threadId,
802 ...(command.title !== undefined ? { title: command.title } : {}),
803 ...(command.regenerateTitle === true
804 ? {
805 regenerateTitle: true as const,
806 previousTitle: thread.title,
807 titleRegeneration: {
808 requestId: command.commandId,
809 startedAt: occurredAt,
810 },
811 }
812 : {}),
813 ...(command.title !== undefined && thread.titleRegeneration != null
814 ? { titleRegeneration: null }
815 : {}),
816 ...(command.modelSelection !== undefined
817 ? { modelSelection: command.modelSelection }
818 : {}),
819 ...(branch !== undefined ? { branch } : {}),
820 ...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),
821 ...(command.linkedPullRequest !== undefined
822 ? { linkedPullRequest: command.linkedPullRequest }
823 : {}),
824 updatedAt: occurredAt,
825 },
826 };
827 }
828​
829 case "thread.title.regeneration.complete": {
830 const thread = yield* requireThread({
831 readModel,
832 command,
833 threadId: command.threadId,
834 });
835 const requestIsCurrent = thread.titleRegeneration?.requestId === command.requestId;
836 const occurredAt = yield* nowIso;
837 return {
838 ...(yield* withEventBase({
839 aggregateKind: "thread",
840 aggregateId: command.threadId,
841 occurredAt,
842 commandId: command.commandId,
843 })),
844 type: "thread.meta-updated",
845 payload: {
846 threadId: command.threadId,
847 ...(requestIsCurrent && command.title !== undefined ? { title: command.title } : {}),
848 ...(requestIsCurrent ? { titleRegeneration: null } : {}),
849 updatedAt: requestIsCurrent ? occurredAt : thread.updatedAt,
850 },
851 };
852 }
853​
854 case "thread.runtime-mode.set": {
855 yield* requireThread({
856 readModel,
857 command,
858 threadId: command.threadId,
859 });
860 const occurredAt = yield* nowIso;
861 return {
862 ...(yield* withEventBase({
863 aggregateKind: "thread",
864 aggregateId: command.threadId,
865 occurredAt,
866 commandId: command.commandId,
867 })),
868 type: "thread.runtime-mode-set",
869 payload: {
870 threadId: command.threadId,
871 runtimeMode: command.runtimeMode,
872 updatedAt: occurredAt,
873 },
874 };
875 }
876​
877 case "thread.interaction-mode.set": {
878 yield* requireThread({
879 readModel,
880 command,
881 threadId: command.threadId,
882 });
883 const occurredAt = yield* nowIso;
884 return {
885 ...(yield* withEventBase({
886 aggregateKind: "thread",
887 aggregateId: command.threadId,
888 occurredAt,
889 commandId: command.commandId,
890 })),
891 type: "thread.interaction-mode-set",
892 payload: {
893 threadId: command.threadId,
894 interactionMode: command.interactionMode,
895 updatedAt: occurredAt,
896 },
897 };
898 }
899​
900 case "thread.turn.start": {
901 const targetThread = yield* requireThread({
902 readModel,
903 command,
904 threadId: command.threadId,
905 });
906 const sourceProposedPlan = command.sourceProposedPlan;
907 const sourceThread = sourceProposedPlan
908 ? yield* requireThread({
909 readModel,
910 command,
911 threadId: sourceProposedPlan.threadId,
912 })
913 : null;
914 const sourcePlan =
915 sourceProposedPlan && sourceThread
916 ? sourceThread.proposedPlans.find((entry) => entry.id === sourceProposedPlan.planId)
917 : null;
918 if (sourceProposedPlan && !sourcePlan) {
919 return yield* new OrchestrationCommandInvariantError({
920 commandType: command.type,
921 detail: `Proposed plan '${sourceProposedPlan.planId}' does not exist on thread '${sourceProposedPlan.threadId}'.`,
922 });
923 }
924 if (sourceThread && sourceThread.projectId !== targetThread.projectId) {
925 return yield* new OrchestrationCommandInvariantError({
926 commandType: command.type,
927 detail: `Proposed plan '${sourceProposedPlan?.planId}' belongs to thread '${sourceThread.id}' in a different project.`,
928 });
929 }
930 const userMessageEvent: Omit<OrchestrationEvent, "sequence"> = {
931 ...(yield* withEventBase({
932 aggregateKind: "thread",
933 aggregateId: command.threadId,
934 occurredAt: command.createdAt,
935 commandId: command.commandId,
936 })),
937 type: "thread.message-sent",
938 payload: {
939 threadId: command.threadId,
940 messageId: command.message.messageId,
941 role: "user",
942 text: command.message.text,
943 attachments: command.message.attachments,
944 turnId: null,
945 streaming: false,
946 createdAt: command.createdAt,
947 updatedAt: command.createdAt,
948 },
949 };
950 const turnStartRequestedEvent: Omit<OrchestrationEvent, "sequence"> = {
951 ...(yield* withEventBase({
952 aggregateKind: "thread",
953 aggregateId: command.threadId,
954 occurredAt: command.createdAt,
955 commandId: command.commandId,
956 })),
957 causationEventId: userMessageEvent.eventId,
958 type: "thread.turn-start-requested",
959 payload: {
960 threadId: command.threadId,
961 messageId: command.message.messageId,
962 ...(command.modelSelection !== undefined
963 ? { modelSelection: command.modelSelection }
964 : {}),
965 ...(command.titleSeed !== undefined ? { titleSeed: command.titleSeed } : {}),
966 runtimeMode: targetThread.runtimeMode,
967 interactionMode: targetThread.interactionMode,
968 ...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),
969 createdAt: command.createdAt,
970 },
971 };
972 // Real activity resets ANY override: it wakes an explicitly settled
973 // thread, and it clears a keep-active pin back to neutral so the
974 // thread can auto-settle again after this burst of work goes stale.
975 // A snooze clears the same way — sending a message to a snoozed
976 // thread is the user re-engaging, so the return ticket is spent.
977 const lifecycleResetEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];
978 if (targetThread.settledOverride !== null) {
979 lifecycleResetEvents.push({
980 ...(yield* withEventBase({
981 aggregateKind: "thread",
982 aggregateId: command.threadId,
983 occurredAt: command.createdAt,
984 commandId: command.commandId,
985 })),
986 type: "thread.unsettled",
987 payload: {
988 threadId: command.threadId,
989 reason: "activity",
990 updatedAt: command.createdAt,
991 },
992 });
993 }
994 if (targetThread.snoozedUntil != null) {
995 lifecycleResetEvents.push({
996 ...(yield* withEventBase({
997 aggregateKind: "thread",
998 aggregateId: command.threadId,
999 occurredAt: command.createdAt,
1000 commandId: command.commandId,
1001 })),
1002 type: "thread.unsnoozed",
1003 payload: {
1004 threadId: command.threadId,
1005 reason: "activity",
1006 updatedAt: command.createdAt,
1007 },
1008 });
1010 return [...lifecycleResetEvents, userMessageEvent, turnStartRequestedEvent];
1012​
1013 case "thread.turn.interrupt": {
1014 yield* requireThread({
1015 readModel,
1016 command,
1017 threadId: command.threadId,
1018 });
1019 return {
1020 ...(yield* withEventBase({
1021 aggregateKind: "thread",
1022 aggregateId: command.threadId,
1023 occurredAt: command.createdAt,
1024 commandId: command.commandId,
1025 })),
1026 type: "thread.turn-interrupt-requested",
1027 payload: {
1028 threadId: command.threadId,
1029 ...(command.turnId !== undefined ? { turnId: command.turnId } : {}),
1030 createdAt: command.createdAt,
1031 },
1032 };
1034​
1035 case "thread.approval.respond": {
1036 yield* requireThread({
1037 readModel,
1038 command,
1039 threadId: command.threadId,
1040 });
1041 return {
1042 ...(yield* withEventBase({
1043 aggregateKind: "thread",
1044 aggregateId: command.threadId,
1045 occurredAt: command.createdAt,
1046 commandId: command.commandId,
1047 metadata: {
1048 requestId: command.requestId,
1049 },
1050 })),
1051 type: "thread.approval-response-requested",
1052 payload: {
1053 threadId: command.threadId,
1054 requestId: command.requestId,
1055 decision: command.decision,
1056 createdAt: command.createdAt,
1057 },
1058 };
1060​
1061 case "thread.user-input.respond": {
1062 yield* requireThread({
1063 readModel,
1064 command,
1065 threadId: command.threadId,
1066 });
1067 return {
1068 ...(yield* withEventBase({
1069 aggregateKind: "thread",
1070 aggregateId: command.threadId,
1071 occurredAt: command.createdAt,
1072 commandId: command.commandId,
1073 metadata: {
1074 requestId: command.requestId,
1075 },
1076 })),
1077 type: "thread.user-input-response-requested",
1078 payload: {
1079 threadId: command.threadId,
1080 requestId: command.requestId,
1081 answers: command.answers,
1082 createdAt: command.createdAt,
1083 },
1084 };
1086​
1087 case "thread.checkpoint.revert": {
1088 yield* requireThread({
1089 readModel,
1090 command,
1091 threadId: command.threadId,
1092 });
1093 return {
1094 ...(yield* withEventBase({
1095 aggregateKind: "thread",
1096 aggregateId: command.threadId,
1097 occurredAt: command.createdAt,
1098 commandId: command.commandId,
1099 })),
1100 type: "thread.checkpoint-revert-requested",
1101 payload: {
1102 threadId: command.threadId,
1103 turnCount: command.turnCount,
1104 createdAt: command.createdAt,
1105 },
1106 };
1108​
1109 case "thread.session.stop": {
1110 const thread = yield* requireThread({
1111 readModel,
1112 command,
1113 threadId: command.threadId,
1114 });
1115 // Settle-cleanup stops are conditional: between the settle landing and
1116 // this command, another client may have re-engaged the thread (a turn
1117 // start unsettles it and brings the session alive). Commands are
1118 // decided serially against this read model, so checking here — not in
1119 // the dispatcher's pre-settle snapshot — closes that race.
1120 if (command.onlyIfSettled === true) {
1121 const sessionComingAlive =
1122 thread.session?.status === "starting" || thread.session?.status === "running";
1123 if (
1124 thread.settledOverride !== "settled" ||
1125 sessionComingAlive ||
1126 hasQueuedTurnStartForThread(thread, command.createdAt)
1127 ) {
1128 return yield* Effect.fail(
1129 new OrchestrationCommandInvariantError({
1130 commandType: command.type,
1131 detail: `thread ${command.threadId} was re-engaged after settle; skipping session stop`,
1132 }),
1133 );
1136 return {
1137 ...(yield* withEventBase({
1138 aggregateKind: "thread",
1139 aggregateId: command.threadId,
1140 occurredAt: command.createdAt,
1141 commandId: command.commandId,
1142 })),
1143 type: "thread.session-stop-requested",
1144 payload: {
1145 threadId: command.threadId,
1146 createdAt: command.createdAt,
1147 },
1148 };
1150​
1151 case "thread.session.set": {
1152 const thread = yield* requireThread({
1153 readModel,
1154 command,
1155 threadId: command.threadId,
1156 });
1157 const sessionSetEvent: Omit<OrchestrationEvent, "sequence"> = {
1158 ...(yield* withEventBase({
1159 aggregateKind: "thread",
1160 aggregateId: command.threadId,
1161 occurredAt: command.createdAt,
1162 commandId: command.commandId,
1163 metadata: {},
1164 })),
1165 type: "thread.session-set",
1166 payload: {
1167 threadId: command.threadId,
1168 session: command.session,
1169 },
1170 };
1171 // Only a session coming alive is activity worth waking a settled thread
1172 // for — status writes like ready/stopped/error arrive after the fact and
1173 // must not fight a user's explicit settle. Snooze is deliberately NOT
1174 // cleared here: snooze never pauses the agent, so its session starting
1175 // or erroring is not the user re-engaging. Blocked/failed work still
1176 // surfaces immediately — effectiveSnoozed refuses to classify a thread
1177 // with a raised hand (approval / input / failure / fresh completion)
1178 // as snoozed, without spending the return ticket.
1179 const isSessionActivity =
1180 command.session.status === "starting" || command.session.status === "running";
1181 // Real activity resets ANY override (settled wakes, active unpins).
1182 if (thread.settledOverride === null || !isSessionActivity) {
1183 return sessionSetEvent;
1185 const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
1186 ...(yield* withEventBase({
1187 aggregateKind: "thread",
1188 aggregateId: command.threadId,
1189 occurredAt: command.createdAt,
1190 commandId: command.commandId,
1191 })),
1192 type: "thread.unsettled",
1193 payload: {
1194 threadId: command.threadId,
1195 reason: "activity",
1196 updatedAt: command.createdAt,
1197 },
1198 };
1199 return [unsettledEvent, sessionSetEvent];
1201​
1202 case "thread.message.assistant.delta": {
1203 yield* requireThread({
1204 readModel,
1205 command,
1206 threadId: command.threadId,
1207 });
1208 return {
1209 ...(yield* withEventBase({
1210 aggregateKind: "thread",
1211 aggregateId: command.threadId,
1212 occurredAt: command.createdAt,
1213 commandId: command.commandId,
1214 })),
1215 type: "thread.message-sent",
1216 payload: {
1217 threadId: command.threadId,
1218 messageId: command.messageId,
1219 role: "assistant",
1220 text: command.delta,
1221 turnId: command.turnId ?? null,
1222 streaming: true,
1223 createdAt: command.createdAt,
1224 updatedAt: command.createdAt,
1225 },
1226 };
1228​
1229 case "thread.message.assistant.complete": {
1230 yield* requireThread({
1231 readModel,
1232 command,
1233 threadId: command.threadId,
1234 });
1235 return {
1236 ...(yield* withEventBase({
1237 aggregateKind: "thread",
1238 aggregateId: command.threadId,
1239 occurredAt: command.createdAt,
1240 commandId: command.commandId,
1241 })),
1242 type: "thread.message-sent",
1243 payload: {
1244 threadId: command.threadId,
1245 messageId: command.messageId,
1246 role: "assistant",
1247 text: "",
1248 turnId: command.turnId ?? null,
1249 streaming: false,
1250 createdAt: command.createdAt,
1251 updatedAt: command.createdAt,
1252 },
1253 };
1255​
1256 case "thread.proposed-plan.upsert": {
1257 yield* requireThread({
1258 readModel,
1259 command,
1260 threadId: command.threadId,
1261 });
1262 return {
1263 ...(yield* withEventBase({
1264 aggregateKind: "thread",
1265 aggregateId: command.threadId,
1266 occurredAt: command.createdAt,
1267 commandId: command.commandId,
1268 })),
1269 type: "thread.proposed-plan-upserted",
1270 payload: {
1271 threadId: command.threadId,
1272 proposedPlan: command.proposedPlan,
1273 },
1274 };
1276​
1277 case "thread.turn.diff.complete": {
1278 yield* requireThread({
1279 readModel,
1280 command,
1281 threadId: command.threadId,
1282 });
1283 return {
1284 ...(yield* withEventBase({
1285 aggregateKind: "thread",
1286 aggregateId: command.threadId,
1287 occurredAt: command.createdAt,
1288 commandId: command.commandId,
1289 })),
1290 type: "thread.turn-diff-completed",
1291 payload: {
1292 threadId: command.threadId,
1293 turnId: command.turnId,
1294 checkpointTurnCount: command.checkpointTurnCount,
1295 checkpointRef: command.checkpointRef,
1296 status: command.status,
1297 files: command.files,
1298 assistantMessageId: command.assistantMessageId ?? null,
1299 completedAt: command.completedAt,
1300 },
1301 };
1303​
1304 case "thread.revert.complete": {
1305 yield* requireThread({
1306 readModel,
1307 command,
1308 threadId: command.threadId,
1309 });
1310 return {
1311 ...(yield* withEventBase({
1312 aggregateKind: "thread",
1313 aggregateId: command.threadId,
1314 occurredAt: command.createdAt,
1315 commandId: command.commandId,
1316 })),
1317 type: "thread.reverted",
1318 payload: {
1319 threadId: command.threadId,
1320 turnCount: command.turnCount,
1321 },
1322 };
1324​
1325 case "thread.activity.append": {
1326 const thread = yield* requireThread({
1327 readModel,
1328 command,
1329 threadId: command.threadId,
1330 });
1331 const requestId =
1332 typeof command.activity.payload === "object" &&
1333 command.activity.payload !== null &&
1334 "requestId" in command.activity.payload &&
1335 typeof (command.activity.payload as { requestId?: unknown }).requestId === "string"
1336 ? ((command.activity.payload as { requestId: string })
1337 .requestId as OrchestrationEvent["metadata"]["requestId"])
1338 : undefined;
1339 const activityAppendedEvent: Omit<OrchestrationEvent, "sequence"> = {
1340 ...(yield* withEventBase({
1341 aggregateKind: "thread",
1342 aggregateId: command.threadId,
1343 occurredAt: command.createdAt,
1344 commandId: command.commandId,
1345 ...(requestId !== undefined ? { metadata: { requestId } } : {}),
1346 })),
1347 type: "thread.activity-appended",
1348 payload: {
1349 threadId: command.threadId,
1350 activity: command.activity,
1351 },
1352 };
1353 // An approval or user-input request is blocked-on-you work — it must
1354 // never stay hidden inside a settled slim row.
1355 const wakesSettledThread =
1356 command.activity.kind === "approval.requested" ||
1357 command.activity.kind === "user-input.requested";
1358 // Real activity resets ANY override (settled wakes, active unpins).
1359 if (thread.settledOverride === null || !wakesSettledThread) {
1360 return activityAppendedEvent;
1362 const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
1363 ...(yield* withEventBase({
1364 aggregateKind: "thread",
1365 aggregateId: command.threadId,
1366 occurredAt: command.createdAt,
1367 commandId: command.commandId,
1368 })),
1369 type: "thread.unsettled",
1370 payload: {
1371 threadId: command.threadId,
1372 reason: "activity",
1373 updatedAt: command.createdAt,
1374 },
1375 };
1376 return [unsettledEvent, activityAppendedEvent];
1378​
1379 default: {
1380 command satisfies never;
1381 const fallback = command as never as { type: string };
1382 return yield* new OrchestrationCommandInvariantError({
1383 commandType: fallback.type,
1384 detail: `Unknown command type: ${fallback.type}`,
1385 });
1388});