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

decider.ts

1,414 lines47.7 KB

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