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

decider.ts

1,257 lines43.7 KB

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