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

decider.ts

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