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

decider.ts

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