From d0a5d75cd903c35d65eeba19727b379d7d4f2c53 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:44:10 +0000 Subject: [PATCH 1/3] feat(orchestration): standing manager mailbox batches queued work founder-first Port plan_dequeue from closura-agent-config lane_event_routing.py (CLO-1303). On standing threads the starting turn answers every waiting plain-text agent message, the founder's message goes first and the CEO's second, founder and CEO messages steer turns they outrank, and a manager turn longer than 300 s is logged. The Home conformance JSON is vendored and hash-pinned. Co-Authored-By: Claude Opus 5.5 --- .../src/orchestration-v2/Orchestrator.ts | 131 +++++++++++- .../ProviderTurnStartService.ts | 24 ++- .../orchestration-v2/StandingMailbox.test.ts | 168 ++++++++++++++++ .../src/orchestration-v2/StandingMailbox.ts | 187 ++++++++++++++++++ .../laneEventRouting.conformance.json | 126 ++++++++++++ packages/contracts/src/orchestrationV2.ts | 12 ++ vite.config.ts | 2 + 7 files changed, 634 insertions(+), 16 deletions(-) create mode 100644 apps/server/src/orchestration-v2/StandingMailbox.test.ts create mode 100644 apps/server/src/orchestration-v2/StandingMailbox.ts create mode 100644 apps/server/src/orchestration-v2/laneEventRouting.conformance.json diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index a2b36016d4467..6a16b38cecbe2 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -234,6 +234,15 @@ import { makeInterruptResultTurnItem } from "./runInterruptResult.ts"; import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts"; import { ProviderSwitchServiceV2 } from "./ProviderSwitchService.ts"; import { isAutomaticCompletionRun, queuedRunsInDeliveryOrder } from "./QueuedRunOrder.ts"; +import { + type MailboxRoles, + type MailboxSenderRole, + mailboxFold, + mailboxPriority, + mailboxSenderRole, + managerTurnOverBudget, + rankQueuedRunsByMailbox, +} from "./StandingMailbox.ts"; import { isRuntimePolicyAboveCeilingError, RuntimePolicyV2 } from "./RuntimePolicy.ts"; import { endOrphanedNativeSubagent, @@ -1152,10 +1161,13 @@ const TOOL_TURN_ITEM_TYPES: ReadonlySet = new Set([ /** Digests never start a turn, and when_idle messages wait behind every other queued one. */ function nextQueuedRun( projection: Pick, + roles?: MailboxRoles, ): OrchestrationV2Run | undefined { - const startable = queuedRunsInDeliveryOrder(projection).filter( + const ordered = queuedRunsInDeliveryOrder(projection).filter( (run) => run.queueHeld !== true && run.delivery?.class !== "digest", ); + // A standing manager answers the founder first, then the CEO (CLO-1303). + const startable = roles === undefined ? ordered : rankQueuedRunsByMailbox(ordered, roles); return startable.find((run) => run.delivery?.class !== "when_idle") ?? startable[0]; } @@ -2814,6 +2826,62 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); }); + // Standing manager mailbox (CLO-1303): who sent a message decides its place in the queue. + const messageSenderRole = ( + message: Pick< + OrchestrationV2ConversationMessage, + "createdBy" | "scheduledTaskId" | "senderThreadId" + >, + ) => + message.createdBy === "user" || message.senderThreadId === undefined + ? Effect.succeed(mailboxSenderRole(message, null)) + : projectionStore.getThreadShell(message.senderThreadId).pipe( + Effect.map((shell) => mailboxSenderRole(message, shell?.standing?.name)), + Effect.orElseSucceed((): MailboxSenderRole => "agent"), + ); + const standingMailboxRoles = Effect.fn("Orchestrator.standingMailboxRoles")(function* ( + projection: OrchestrationV2ThreadProjection, + ) { + if (projection.thread.standing == null) return undefined; + const roles = new Map(); + for (const run of projection.runs) { + if (run.status !== "queued") continue; + const message = projection.messages.find((candidate) => candidate.id === run.userMessageId); + if (message !== undefined) roles.set(message.id, yield* messageSenderRole(message)); + } + return roles as MailboxRoles; + }); + // Flag a standing-manager turn that ran past five minutes: managers dispatch, workers work. + const flaggedManagerTurns = new Set(); + const flagSlowManagerTurn = ( + projection: OrchestrationV2ThreadProjection, + runId: RunId | undefined, + ) => { + const run = projection.runs.find((candidate) => candidate.id === runId); + if ( + projection.thread.standing == null || + run?.startedAt == null || + run.completedAt == null || + flaggedManagerTurns.has(run.id) || + !managerTurnOverBudget( + DateTime.toEpochMillis(run.startedAt), + DateTime.toEpochMillis(run.completedAt), + ) + ) { + return Effect.void; + } + if (flaggedManagerTurns.size >= 1024) flaggedManagerTurns.clear(); + flaggedManagerTurns.add(run.id); + return Effect.logWarning("standing manager turn exceeded 300 seconds", { + threadId: projection.thread.id, + standing: projection.thread.standing.name, + runId: run.id, + providerInstanceId: run.providerInstanceId, + seconds: Math.round( + (DateTime.toEpochMillis(run.completedAt) - DateTime.toEpochMillis(run.startedAt)) / 1000, + ), + }); + }; const startNextQueuedRunOnce = Effect.fn("Orchestrator.startNextQueuedRun")( function* ( threadId: ThreadId, @@ -2827,6 +2895,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }, ) { let projection = yield* readCommandProjection(threadId); + yield* flagSlowManagerTurn( + projection, + options?.latestRunEnded === true + ? latestExecutedRun(projection.runs)?.id + : options?.endedRunId, + ); if ( projection.thread.archivedAt !== null || projection.thread.deletedAt !== null || @@ -2867,9 +2941,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio projection = yield* readCommandProjection(threadId); } if (!(yield* projectionStore.canStartQueuedRun(threadId))) return; + const mailboxRoles = yield* standingMailboxRoles(projection); let storedQueuedRun = options?.queuedRunId === undefined - ? nextQueuedRun(projection) + ? nextQueuedRun(projection, mailboxRoles) : projection.runs.find( (run) => run.id === options.queuedRunId && run.status === "queued", ); @@ -2904,7 +2979,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio queuedRunCancellationEvents(projection, storedQueuedRun, checkedAt), ); projection = yield* readCommandProjection(threadId); - storedQueuedRun = nextQueuedRun(projection); + storedQueuedRun = nextQueuedRun(projection, mailboxRoles); } if (storedQueuedRun !== undefined && currentWake !== undefined) { const now = yield* DateTime.now; @@ -3475,6 +3550,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const fold = carriesDigest(queuedRun, queuedMessage) ? digestFold(projection, now) : undefined; + // A standing manager answers every waiting agent message in this one turn (CLO-1303). + const mailbox = + mailboxRoles === undefined || fold === undefined || queuedRun.outputSchema !== undefined + ? undefined + : mailboxFold(projection, queuedRun, mailboxRoles, now); const startingRun: OrchestrationV2Run = { ...queuedRun, providerThreadId: queuedProviderThread.id, @@ -3484,6 +3564,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio startedAt: null, contextHandoffId: activeHandoff?.id ?? null, ...(fold === undefined || fold.digest.length === 0 ? {} : { digest: fold.digest }), + ...(mailbox === undefined || mailbox.mailbox.length === 0 + ? {} + : { mailbox: mailbox.mailbox }), ...wakeWorkStartedAt( projection, { @@ -3629,9 +3712,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio for (const expiredRun of fold?.expired ?? []) yield* logExpiredDelivery(expiredRun); yield* writeSystemEvents( [ - ...(fold === undefined ? [] : [...fold.folded, ...fold.expired]).flatMap((spent) => - queuedRunCancellationEvents(projection, spent, now), - ), + ...[ + ...(fold === undefined ? [] : [...fold.folded, ...fold.expired]), + ...(mailbox?.folded ?? []), + ].flatMap((spent) => queuedRunCancellationEvents(projection, spent, now)), ...(selectionChanged ? [ { @@ -8778,6 +8862,41 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio attachments: command.attachments, }) : resolveMessageDispatchIntent(projection, requestedMode, requestedIntent); + // Standing manager mailbox (CLO-1303): a founder message steers a turn it outranks, a CEO + // message steers only an agent-started turn, and agent messages wait. Steering only, never + // an interrupt-restart. + if ( + projection.thread.standing != null && + goalCommand === null && + deliveryClass === undefined && + requestedIntent === undefined && + dispatchMode.type === "queue_after_active" && + command.notification === undefined + ) { + const activeRun = projection.runs.findLast(isActiveRun); + const activeMessage = projection.messages.find( + (message) => message.id === activeRun?.userMessageId, + ); + if (activeMessage !== undefined) { + const senderPriority = mailboxPriority( + yield* messageSenderRole({ + createdBy: command.createdBy ?? "user", + scheduledTaskId: command.scheduledTaskId, + senderThreadId: command.senderThreadId, + }), + ); + const activePriority = mailboxPriority(yield* messageSenderRole(activeMessage)); + if (senderPriority < activePriority && senderPriority <= mailboxPriority("ceo")) { + const preempt = resolveMessageDispatch(projection, { + dispatchMode: requestedMode, + deliveryIntent: "auto", + text: command.text, + attachments: command.attachments, + }); + if (preempt.type === "steer_active") dispatchMode = preempt; + } + } + } if (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") { const targetRunId = dispatchMode.targetRunId; const target = projection.runs.find((run) => run.id === targetRunId); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 09a99b698af6f..de9b8a3c3e191 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -40,6 +40,7 @@ import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import * as ServerConfig from "../config.ts"; +import { formatMailboxForProvider } from "./StandingMailbox.ts"; import { CLAUDE_PROVIDER, CLAUDE_QUERY_ENDED_BEFORE_TURN_DETAIL, @@ -1156,19 +1157,22 @@ export const layer: Layer.Layer< ? (providerMessage.sentBy?.founder ?? null) : null; const messageText = formatDigestForProvider( - formatSeenMarkerForProvider( - formatSharedSenderForProvider( - withMessageSenderNote( - providerMessage, - projectComposerContextForProvider({ - text: providerMessage.text, - records: providerMessage.context?.records ?? [], - }), + formatMailboxForProvider( + formatSeenMarkerForProvider( + formatSharedSenderForProvider( + withMessageSenderNote( + providerMessage, + projectComposerContextForProvider({ + text: providerMessage.text, + records: providerMessage.context?.records ?? [], + }), + ), + sharedFounder, ), + providerMessage.seenMarker, sharedFounder, ), - providerMessage.seenMarker, - sharedFounder, + run.mailbox, ), run.digest, ); diff --git a/apps/server/src/orchestration-v2/StandingMailbox.test.ts b/apps/server/src/orchestration-v2/StandingMailbox.test.ts new file mode 100644 index 0000000000000..7571b52808e1b --- /dev/null +++ b/apps/server/src/orchestration-v2/StandingMailbox.test.ts @@ -0,0 +1,168 @@ +// @effect-diagnostics nodeBuiltinImport:off -- Hashes the vendored conformance bytes to pin them to the Home source. +import * as NodeCrypto from "node:crypto"; +import * as NodeFS from "node:fs"; +import * as DateTime from "effect/DateTime"; +import { describe, expect, it } from "vite-plus/test"; + +import { + type MailboxMessage, + type MailboxRoles, + formatMailboxForProvider, + mailboxFold, + managerTurnOverBudget, + mailboxSenderRole, + planDequeue, + rankQueuedRunsByMailbox, +} from "./StandingMailbox.ts"; + +const CONFORMANCE_URL = new URL("./laneEventRouting.conformance.json", import.meta.url); +// sha256 of closura-agent-config `config/lane-event-routing/conformance.json` at 40e39541c6. +// Re-vendor the file and update both together; a mismatch means the two sides drifted. +const CONFORMANCE_SHA256 = "e6460764fd173a4b7e4c3391f5b46f3e0ff8d0ac62a341ff41f025109c28a99f"; + +interface MailboxCase { + readonly name: string; + readonly queued: ReadonlyArray; + readonly current_priority?: number | null; + readonly expect: Record; +} + +const conformanceBytes = NodeFS.readFileSync(CONFORMANCE_URL); +const mailboxCases = ( + JSON.parse(conformanceBytes.toString("utf8")) as { cases: ReadonlyArray } +).cases.filter((entry): entry is MailboxCase => "queued" in entry); + +describe("standing manager mailbox conformance", () => { + it("vendors the Home contract byte for byte", () => { + expect(NodeCrypto.createHash("sha256").update(conformanceBytes).digest("hex")).toBe( + CONFORMANCE_SHA256, + ); + expect(mailboxCases.length).toBeGreaterThanOrEqual(5); + }); + + it.each(mailboxCases.map((entry) => [entry.name, entry] as const))("%s", (_name, entry) => { + const plan = planDequeue(entry.queued, entry.current_priority ?? null); + const got: Record = { ...plan }; + for (const [field, want] of Object.entries(entry.expect)) { + expect(got[field], field).toEqual(want); + } + }); +}); + +describe("standing manager mailbox", () => { + it("batches seven queued messages into one turn with the founder first", () => { + const queued: ReadonlyArray = [ + { id: "a1", at: "2026-11-27T10:00:00Z", sender_role: "agent" }, + { id: "a2", at: "2026-11-27T10:01:00Z", sender_role: "agent" }, + { id: "c1", at: "2026-11-27T10:02:00Z", sender_role: "ceo" }, + { id: "a3", at: "2026-11-27T10:03:00Z", sender_role: "agent" }, + { id: "f1", at: "2026-11-27T10:04:00Z", sender_role: "founder" }, + { id: "a4", at: "2026-11-27T10:05:00Z", sender_role: "agent" }, + { id: "a5", at: "2026-11-27T10:06:00Z", sender_role: "agent" }, + ]; + expect(planDequeue(queued)).toEqual({ + turns: 1, + batch: ["f1", "c1", "a1", "a2", "a3", "a4", "a5"], + digest: [], + preempt: false, + }); + }); + + it("classifies a typed message as the founder and the CEO seat by its standing name", () => { + expect(mailboxSenderRole({ createdBy: "user", scheduledTaskId: undefined }, null)).toBe( + "founder", + ); + expect(mailboxSenderRole({ createdBy: "agent", scheduledTaskId: undefined }, " ceo ")).toBe( + "ceo", + ); + expect(mailboxSenderRole({ createdBy: "agent", scheduledTaskId: undefined }, "CTO")).toBe( + "agent", + ); + }); + + it("flags a manager turn only past 300 seconds", () => { + expect(managerTurnOverBudget(0, 300_000)).toBe(false); + expect(managerTurnOverBudget(0, 300_001)).toBe(true); + }); +}); + +describe("standing manager mailbox on queued runs", () => { + const model = { instanceId: "codex", model: "gpt" }; + const senders = [ + ["a1", "agent"], + ["a2", "agent"], + ["c1", "ceo"], + ["a3", "agent"], + ["f1", "founder"], + ["a4", "agent"], + ["a5", "agent"], + ] as const; + const projection = { + messages: senders.map(([id, role]) => ({ + id: `message:${id}`, + text: `from ${id}`, + attachments: [], + createdBy: role === "founder" ? "user" : "agent", + })), + runs: senders.map(([id], index) => ({ + id: `run:${id}`, + ordinal: index + 1, + queuePosition: index + 1, + requestedAt: DateTime.makeUnsafe(`2026-11-27T10:0${index}:00Z`), + status: "queued", + userMessageId: `message:${id}`, + providerInstanceId: "codex", + modelSelection: model, + })), + } as never as Parameters[0]; + const roles = new Map( + senders.map(([id, role]) => [`message:${id}`, role]), + ) as never as MailboxRoles; + + it("starts the founder's message and answers the other six in the same turn", () => { + const [head] = rankQueuedRunsByMailbox(projection.runs, roles); + expect(head?.id).toBe("run:f1"); + const { folded, mailbox } = mailboxFold( + projection, + head!, + roles, + DateTime.makeUnsafe("2026-11-27T11:00:00Z"), + ); + expect(folded.map((run) => run.id)).toEqual([ + "run:c1", + "run:a1", + "run:a2", + "run:a3", + "run:a4", + "run:a5", + ]); + expect(mailbox.map((entry) => entry.senderRole)).toEqual([ + "ceo", + "agent", + "agent", + "agent", + "agent", + "agent", + ]); + const text = formatMailboxForProvider("from f1", mailbox); + expect(text.startsWith("from f1\n")).toBe(true); + expect(text).toContain(''); + expect(text.indexOf("from c1")).toBeLessThan(text.indexOf("from a1")); + }); + + it("leaves a typed message and a different model out of the batch", () => { + const head = projection.runs[0]!; + const { folded } = mailboxFold( + { + ...projection, + runs: projection.runs.map((run) => + run.id === "run:a2" ? { ...run, modelSelection: { ...model, model: "other" } } : run, + ), + }, + head, + roles, + DateTime.makeUnsafe("2026-11-27T11:00:00Z"), + ); + expect(folded.map((run) => run.id)).toEqual(["run:c1", "run:a3", "run:a4", "run:a5"]); + }); +}); diff --git a/apps/server/src/orchestration-v2/StandingMailbox.ts b/apps/server/src/orchestration-v2/StandingMailbox.ts new file mode 100644 index 0000000000000..e4685351ec7fc --- /dev/null +++ b/apps/server/src/orchestration-v2/StandingMailbox.ts @@ -0,0 +1,187 @@ +import { + type MessageId, + type OrchestrationV2ConversationMessage, + type OrchestrationV2MailboxEntry, + type OrchestrationV2Run, + type OrchestrationV2ThreadProjection, + withMessageSenderNote, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; + +import { queuedRunsInDeliveryOrder } from "./QueuedRunOrder.ts"; + +/** + * Standing manager mailbox (Closura CLO-1303). Port of `plan_dequeue` in closura-agent-config + * `scripts/lane_event_routing.py`; `laneEventRouting.conformance.json` is the shared contract. + */ +export type MailboxSenderRole = "founder" | "ceo" | "agent"; + +const MAILBOX_PRIORITY = { founder: 0, ceo: 1, agent: 2 } as const; + +export interface MailboxMessage { + readonly id: string; + readonly at: string; + readonly sender_role?: string | undefined; + readonly kind?: string | undefined; +} + +export interface MailboxPlan { + readonly turns: 0 | 1; + readonly batch: ReadonlyArray; + readonly digest: ReadonlyArray; + readonly preempt: boolean; +} + +export function mailboxPriority(role: string | undefined): number { + return role === "founder" ? MAILBOX_PRIORITY.founder : role === "ceo" ? MAILBOX_PRIORITY.ceo : 2; +} + +/** + * One turn for every actionable queued message, founder first, then CEO, then arrival order. + * Digest items start no turn. A founder message preempts any turn it outranks; a CEO message + * preempts only an agent-initiated turn; agent messages never preempt. + */ +export function planDequeue( + queued: ReadonlyArray, + currentPriority: number | null = null, +): MailboxPlan { + const digest = queued.filter((message) => message.kind === "digest"); + const actionable = queued + .filter((message) => message.kind !== "digest") + .toSorted( + (left, right) => + mailboxPriority(left.sender_role) - mailboxPriority(right.sender_role) || + (left.at < right.at ? -1 : left.at > right.at ? 1 : 0), + ); + const top = actionable[0] === undefined ? null : mailboxPriority(actionable[0].sender_role); + return { + turns: actionable.length > 0 ? 1 : 0, + batch: actionable.map((message) => message.id), + digest: digest.map((message) => message.id), + preempt: + top !== null && + currentPriority !== null && + top < currentPriority && + top <= MAILBOX_PRIORITY.ceo, + }; +} + +/** The CEO seat is the standing thread named "CEO" (closura-agent-config `config/standing-threads.json`). */ +function isCeoStandingName(name: string | null | undefined): boolean { + return name?.trim().toUpperCase() === "CEO"; +} + +/** A person typing in the chat is the founder; a CEO standing thread is the CEO; the rest are agents. */ +export function mailboxSenderRole( + message: Pick, + senderStandingName: string | null | undefined, +): MailboxSenderRole { + if (message.createdBy === "user" && message.scheduledTaskId === undefined) return "founder"; + return isCeoStandingName(senderStandingName) ? "ceo" : "agent"; +} + +/** A standing-manager turn longer than this is flagged; the manager should dispatch, not do the work. */ +const MANAGER_TURN_FLAG_SECONDS = 300; + +export function managerTurnOverBudget(startedAtMs: number, completedAtMs: number): boolean { + return (completedAtMs - startedAtMs) / 1000 > MANAGER_TURN_FLAG_SECONDS; +} + +export type MailboxRoles = ReadonlyMap; + +/** Founder first, then CEO, then the existing delivery order (the sort is stable). */ +export function rankQueuedRunsByMailbox>( + runs: ReadonlyArray, + roles: MailboxRoles, +): Array { + return runs.toSorted( + (left, right) => + mailboxPriority(roles.get(left.userMessageId)) - + mailboxPriority(roles.get(right.userMessageId)), + ); +} + +/** + * Only plain text another agent queued joins a batch. Attachments, commands, completions, + * notifications (PR-watch wakes included), structured-output asks and continuations keep their + * own turn, as does anything a person typed, so the transcript still shows it. + */ +function joinsBatch( + run: OrchestrationV2Run, + message: OrchestrationV2ConversationMessage | undefined, + head: Pick, + now: DateTime.Utc, +): message is OrchestrationV2ConversationMessage { + const deliveryClass = run.delivery?.class; + const expiresAt = run.delivery?.expiresAt; + return ( + message !== undefined && + message.createdBy !== "user" && + (deliveryClass === undefined || deliveryClass === "next_turn") && + (expiresAt === undefined || DateTime.isGreaterThan(expiresAt, now)) && + run.queueHeld !== true && + run.providerInstanceId === head.providerInstanceId && + run.modelSelection.model === head.modelSelection.model && + run.restartContinuationOfRunId === undefined && + run.manualContinuationOfRunId === undefined && + run.usageLimitContinuationOfRunId === undefined && + run.providerFailoverOfRunId === undefined && + run.steerWhenReadyRunId === undefined && + run.delegatedTaskId === undefined && + run.sourcePlanRef === undefined && + run.workspacePreparation === undefined && + run.outputSchema === undefined && + run.freshContext !== true && + message.attachments.length === 0 && + message.notification === undefined && + message.delegatedCompletion === undefined && + message.idleCompaction === undefined && + message.text.trim() !== "" && + !/^\s*[/$]/u.test(message.text) + ); +} + +/** The other queued messages a starting standing-thread turn answers too, in mailbox order. */ +export function mailboxFold( + projection: Pick, + head: Pick, + roles: MailboxRoles, + now: DateTime.Utc, +): { + readonly folded: ReadonlyArray; + readonly mailbox: ReadonlyArray; +} { + const folded: Array = []; + const mailbox: Array = []; + const waiting = queuedRunsInDeliveryOrder(projection).filter((run) => run.id !== head.id); + for (const run of rankQueuedRunsByMailbox(waiting, roles)) { + const message = projection.messages.find((candidate) => candidate.id === run.userMessageId); + if (!joinsBatch(run, message, head, now)) continue; + folded.push(run); + mailbox.push({ + messageId: message.id, + runId: run.id, + senderRole: roles.get(message.id) ?? "agent", + requestedAt: run.requestedAt, + text: withMessageSenderNote(message, message.text), + }); + } + return { folded, mailbox }; +} + +/** Appends the batched messages after the turn's own message, in mailbox order. */ +export function formatMailboxForProvider( + text: string, + mailbox: ReadonlyArray> | undefined, +): string { + if (mailbox === undefined || mailbox.length === 0) return text; + const noun = mailbox.length === 1 ? "message was" : "messages were"; + return [ + text, + "", + ``, + `${mailbox.length} more ${noun} queued for this thread. Answer them in this same turn:`, + ...mailbox.map((entry, index) => `## ${index + 1} (${entry.senderRole})\n${entry.text.trim()}`), + "", + ].join("\n"); +} diff --git a/apps/server/src/orchestration-v2/laneEventRouting.conformance.json b/apps/server/src/orchestration-v2/laneEventRouting.conformance.json new file mode 100644 index 0000000000000..56b36b1ce05cd --- /dev/null +++ b/apps/server/src/orchestration-v2/laneEventRouting.conformance.json @@ -0,0 +1,126 @@ +{ + "description": "Conformance contract for lane-event routing and standing-manager mailbox rules (CLO-1302, CLO-1303). scripts/lane_event_routing.py and the t3code port must both produce these decisions.", + "cases": [ + { + "name": "replay-c964fe48-98fbc01a-settled-launcher-zero-wakes", + "comment": "Audit thread c964fe48 settled; child 98fbc01a (declarative factory RFC) ended repeatedly across 10 runs with no open PR and no failure, plus a later provider-limit failure repeated with different numbers. The launcher must never be woken.", + "world": {"threads": {"c964fe48": {"state": "settled"}, "98fbc01a": {"state": "idle"}}, "delivered": []}, + "events": [ + {"child_thread_id": "98fbc01a", "owner": "c964fe48", "kind": "lane-ended", "condition": {"outcome": "completed"}}, + {"child_thread_id": "98fbc01a", "owner": "c964fe48", "kind": "lane-ended", "condition": {"outcome": "completed"}}, + {"child_thread_id": "98fbc01a", "owner": "c964fe48", "kind": "lane-ended", "condition": {"outcome": "completed"}}, + {"child_thread_id": "98fbc01a", "owner": "c964fe48", "kind": "lane-ended", "condition": {"outcome": "failed", "error": "Antigravity usage limit reached, resets at 2026-12-03T07:01:49Z"}}, + {"child_thread_id": "98fbc01a", "owner": "c964fe48", "kind": "lane-ended", "condition": {"outcome": "failed", "error": "Antigravity usage limit reached, resets at 2026-12-03T07:01:50Z"}}, + {"child_thread_id": "98fbc01a", "owner": "c964fe48", "kind": "lane-ended", "condition": {"outcome": "completed"}} + ], + "expect_actions": ["digest", "drop", "drop", "digest", "drop", "drop"], + "expect_wakes": 0 + }, + { + "name": "archived-or-missing-launcher-is-detached", + "world": {"threads": {"child": {"state": "idle"}, "gone": {"state": "archived"}}, "delivered": []}, + "events": [ + {"child_thread_id": "child", "owner": "gone", "kind": "lane-ended", "condition": {"outcome": "failed", "error": "boom 3"}}, + {"child_thread_id": "child", "owner": "never-existed", "kind": "lane-ended", "condition": {"outcome": "failed", "error": "boom 4"}} + ], + "expect_actions": ["digest", "drop"], + "expect_wakes": 0 + }, + { + "name": "active-owner-one-alert-per-condition", + "comment": "The owner is active and the child ended with an open PR: wake once, then drop identical repeats; a changed open-PR set is a new condition.", + "world": {"threads": {"owner": {"state": "idle"}, "child": {"state": "idle"}}, "delivered": []}, + "events": [ + {"child_thread_id": "child", "owner": "owner", "kind": "lane-ended", "condition": {"outcome": "completed", "open_prs": ["org/repo#1"]}}, + {"child_thread_id": "child", "owner": "owner", "kind": "lane-ended", "condition": {"outcome": "completed", "open_prs": ["org/repo#1"]}}, + {"child_thread_id": "child", "owner": "owner", "kind": "lane-ended", "condition": {"outcome": "completed", "open_prs": ["org/repo#1", "org/repo#2"]}}, + {"child_thread_id": "child", "owner": "owner", "kind": "lane-ended", "condition": {"outcome": "completed", "open_prs": ["org/repo#2", "org/repo#1"]}} + ], + "expect_actions": ["wake", "drop", "wake", "drop"], + "expect_wakes": 2 + }, + { + "name": "same-failure-class-different-numbers-dedupes", + "world": {"threads": {"owner": {"state": "idle"}, "child": {"state": "idle"}}, "delivered": []}, + "events": [ + {"child_thread_id": "child", "owner": "owner", "kind": "lane-ended", "condition": {"outcome": "failed", "error": "HTTP 500 for request 1234"}}, + {"child_thread_id": "child", "owner": "owner", "kind": "lane-ended", "condition": {"outcome": "failed", "error": "HTTP 500 for request 9876"}}, + {"child_thread_id": "child", "owner": "owner", "kind": "lane-ended", "condition": {"outcome": "failed", "error": "disk full"}} + ], + "expect_actions": ["wake", "drop", "wake"], + "expect_wakes": 2 + }, + { + "name": "target-running-drops", + "world": {"threads": {"owner": {"state": "idle"}, "child": {"state": "running"}}, "delivered": []}, + "events": [ + {"child_thread_id": "child", "owner": "owner", "kind": "lane-ended", "condition": {"outcome": "failed", "error": "x"}}, + {"child_thread_id": "child", "owner": "owner", "kind": "pr-checks-failed", "superseded": true, "condition": {"outcome": "failed"}} + ], + "expect_actions": ["drop", "drop"], + "expect_wakes": 0 + }, + { + "name": "pr-events-routing", + "comment": "Passing checks and merges go to the merge-queue code handler; only failures and review requests wake a model.", + "world": {"threads": {"owner": {"state": "idle"}, "child": {"state": "idle"}}, "delivered": []}, + "events": [ + {"child_thread_id": "child", "owner": "owner", "kind": "pr-checks-passed", "condition": {"outcome": "passed", "open_prs": ["org/repo#9"]}}, + {"child_thread_id": "child", "owner": "owner", "kind": "pr-merged", "condition": {"outcome": "merged", "open_prs": []}}, + {"child_thread_id": "child", "owner": "owner", "kind": "pr-checks-failed", "condition": {"outcome": "failed", "error": "lint failed", "open_prs": ["org/repo#9"]}}, + {"child_thread_id": "child", "owner": "owner", "kind": "review-requested", "condition": {"outcome": "review", "open_prs": ["org/repo#9"]}} + ], + "expect_actions": ["code-handler", "code-handler", "wake", "wake"], + "expect_wakes": 2 + }, + { + "name": "requester-is-used-when-no-owner", + "world": {"threads": {"req": {"state": "settled"}, "child": {"state": "idle"}}, "delivered": []}, + "events": [ + {"child_thread_id": "child", "requester": "req", "kind": "lane-ended", "condition": {"outcome": "failed", "error": "z"}} + ], + "expect_actions": ["digest"], + "expect_wakes": 0 + }, + { + "name": "mailbox-founder-first-and-batched", + "comment": "Seven queued messages become one turn: founder first, then CEO, then the rest in arrival order. Digest items start no turn.", + "queued": [ + {"id": "m1", "at": "2026-11-27T10:00:00Z", "sender_role": "agent"}, + {"id": "m2", "at": "2026-11-27T10:01:00Z", "sender_role": "ceo"}, + {"id": "m3", "at": "2026-11-27T10:02:00Z", "sender_role": "agent"}, + {"id": "m4", "at": "2026-11-27T10:03:00Z", "sender_role": "founder"}, + {"id": "d1", "at": "2026-11-27T10:04:00Z", "sender_role": "agent", "kind": "digest"} + ], + "current_priority": null, + "expect": {"turns": 1, "batch": ["m4", "m2", "m1", "m3"], "digest": ["d1"], "preempt": false} + }, + { + "name": "mailbox-digest-only-starts-no-turn", + "queued": [ + {"id": "d1", "at": "2026-11-27T10:00:00Z", "sender_role": "agent", "kind": "digest"}, + {"id": "d2", "at": "2026-11-27T10:01:00Z", "sender_role": "agent", "kind": "digest"} + ], + "current_priority": null, + "expect": {"turns": 0, "batch": [], "digest": ["d1", "d2"], "preempt": false} + }, + { + "name": "mailbox-founder-preempts-agent-turn", + "queued": [{"id": "f1", "at": "2026-11-27T10:00:00Z", "sender_role": "founder"}], + "current_priority": 2, + "expect": {"turns": 1, "batch": ["f1"], "digest": [], "preempt": true} + }, + { + "name": "mailbox-ceo-preempts-agent-turn-not-founder-turn", + "queued": [{"id": "c1", "at": "2026-11-27T10:00:00Z", "sender_role": "ceo"}], + "current_priority": 0, + "expect": {"turns": 1, "batch": ["c1"], "digest": [], "preempt": false} + }, + { + "name": "mailbox-agent-does-not-preempt", + "queued": [{"id": "a1", "at": "2026-11-27T10:00:00Z", "sender_role": "agent"}], + "current_priority": 2, + "expect": {"turns": 1, "batch": ["a1"], "digest": [], "preempt": false} + } + ] +} diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 6bf4ac46fa144..838842b075be3 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -975,6 +975,16 @@ export const OrchestrationV2DigestEntry = Schema.Struct({ }); export type OrchestrationV2DigestEntry = typeof OrchestrationV2DigestEntry.Type; +/** A queued message a standing thread's turn answered along with its own (Closura CLO-1303). */ +export const OrchestrationV2MailboxEntry = Schema.Struct({ + messageId: MessageId, + runId: RunId, + senderRole: Schema.Literals(["founder", "ceo", "agent"]), + requestedAt: Schema.DateTimeUtc, + text: Schema.String, +}); +export type OrchestrationV2MailboxEntry = typeof OrchestrationV2MailboxEntry.Type; + /** What a run returned as data: a value the server accepted against the run's `outputSchema`. */ export const OrchestrationV2RunOutput = Schema.Struct({ value: Schema.Json, @@ -1025,6 +1035,8 @@ export const OrchestrationV2Run = Schema.Struct({ delivery: Schema.optional(OrchestrationV2MessageDelivery), /** Digest messages folded into this run's turn, sent to the provider ahead of its message. */ digest: Schema.optional(Schema.Array(OrchestrationV2DigestEntry)), + /** Queued messages batched into this standing thread's turn, sent after its own message. */ + mailbox: Schema.optional(Schema.Array(OrchestrationV2MailboxEntry)), /** Tool and delegation counts while the thread's delegation nudge was on. */ delegationNudge: Schema.optional(RunDelegationNudgeStats), /** The JSON Schema of the result this run was asked to return as data. */ diff --git a/vite.config.ts b/vite.config.ts index c8f6ca58b1194..54d4529221b54 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -201,6 +201,8 @@ export default defineConfig({ "apps/mobile/modules/t3-highlights/cpp/generated/**", "apps/mobile/modules/t3-highlights/nitrogen/generated/**", "*.icon/**", + // Vendored byte-for-byte from closura-agent-config; its test pins the source hash. + "apps/server/src/orchestration-v2/laneEventRouting.conformance.json", ], sortPackageJson: {}, overrides: [ From 6f6bbd33e56a01a2d67a731f5d78d11134f2cbe8 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Sat, 28 Nov 2026 05:26:57 +0000 Subject: [PATCH 2/3] fix(server): keep the branded provider instance id in the mailbox test fixture (CLO-1303) The "different model" case spread the plain `{ instanceId: "codex" }` fixture over the run's model selection, so `instanceId` lost its `ProviderInstanceId` brand and `effect-tsgo` rejected the runs array with TS2322 at StandingMailbox.test.ts:158. Spread the run's own `modelSelection` instead. Co-Authored-By: Claude Sonnet 5.5 --- apps/server/src/orchestration-v2/StandingMailbox.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/StandingMailbox.test.ts b/apps/server/src/orchestration-v2/StandingMailbox.test.ts index 7571b52808e1b..0b1f898ca5984 100644 --- a/apps/server/src/orchestration-v2/StandingMailbox.test.ts +++ b/apps/server/src/orchestration-v2/StandingMailbox.test.ts @@ -156,7 +156,7 @@ describe("standing manager mailbox on queued runs", () => { { ...projection, runs: projection.runs.map((run) => - run.id === "run:a2" ? { ...run, modelSelection: { ...model, model: "other" } } : run, + run.id === "run:a2" ? { ...run, modelSelection: { ...run.modelSelection, model: "other" } } : run, ), }, head, From cda51efd60a09e49df6f6328e6c4d397e12627b6 Mon Sep 17 00:00:00 2001 From: Kameron Smith Date: Mon, 30 Nov 2026 05:32:49 -0500 Subject: [PATCH 3/3] fix(orchestration): preserve and fairly deliver standing mailbox turns Encode mailbox timestamps through the run JSON codec and age queued work into FIFO after two minutes. Retain composer context and visible messages when folding, consume originals only after provider acceptance, and carry mailbox instructions into failover and continuation runs. Respect explicit queue requests and stopped runs before considering priority steering. Addresses the important mailbox review findings on PR 239 (CLO-1303). Model: codex/gpt-6.1-sol Task: implementation Agent: Codex Lane: codex --- .../src/orchestration-v2/Orchestrator.ts | 152 ++++++---- .../ProviderTurnStartService.test.ts | 85 +++++- .../ProviderTurnStartService.ts | 53 +++- .../src/orchestration-v2/QueuedRunOrder.ts | 57 +++- .../orchestration-v2/StandingMailbox.test.ts | 94 ++++++- .../src/orchestration-v2/StandingMailbox.ts | 52 +++- .../src/orchestration-v2/runtimeLayer.test.ts | 262 +++++++++++++++++- .../contracts/src/orchestrationV2.test.ts | 39 +++ packages/contracts/src/orchestrationV2.ts | 8 + 9 files changed, 726 insertions(+), 76 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 6a16b38cecbe2..ada577224451b 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -233,10 +233,15 @@ import * as RunExecutionService from "./RunExecutionService.ts"; import { makeInterruptResultTurnItem } from "./runInterruptResult.ts"; import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts"; import { ProviderSwitchServiceV2 } from "./ProviderSwitchService.ts"; -import { isAutomaticCompletionRun, queuedRunsInDeliveryOrder } from "./QueuedRunOrder.ts"; +import { + isAutomaticCompletionRun, + queuedRunCancellationEvents, + queuedRunsInDeliveryOrder, +} from "./QueuedRunOrder.ts"; import { type MailboxRoles, type MailboxSenderRole, + mailboxWaitExceeded, mailboxFold, mailboxPriority, mailboxSenderRole, @@ -1158,16 +1163,25 @@ const TOOL_TURN_ITEM_TYPES: ReadonlySet = new Set([ "subagent", ]); -/** Digests never start a turn, and when_idle messages wait behind every other queued one. */ +/** Digests never start a turn; when_idle waits behind fresh work, up to the mailbox age bound. */ function nextQueuedRun( projection: Pick, roles?: MailboxRoles, + now?: DateTime.Utc, ): OrchestrationV2Run | undefined { const ordered = queuedRunsInDeliveryOrder(projection).filter( (run) => run.queueHeld !== true && run.delivery?.class !== "digest", ); // A standing manager answers the founder first, then the CEO (CLO-1303). - const startable = roles === undefined ? ordered : rankQueuedRunsByMailbox(ordered, roles); + const startable = roles === undefined ? ordered : rankQueuedRunsByMailbox(ordered, roles, now); + if ( + roles !== undefined && + now !== undefined && + startable[0] !== undefined && + mailboxWaitExceeded(startable[0], now) + ) { + return startable[0]; + } return startable.find((run) => run.delivery?.class !== "when_idle") ?? startable[0]; } @@ -1500,49 +1514,6 @@ function withoutSection({ section: _, ...stamp }: MonitorPullRequestStamp) { return stamp; } -function queuedRunCancellationEvents( - projection: Pick, - run: OrchestrationV2Run, - now: DateTime.Utc, -): ReadonlyArray> { - const rootNode = projection.nodes.find((node) => node.id === run.rootNodeId); - const attempt = projection.attempts.find((candidate) => candidate.id === run.activeAttemptId); - const events: Array> = [ - { - type: "run.updated", - threadId: run.threadId, - runId: run.id, - ...(run.rootNodeId === null ? {} : { nodeId: run.rootNodeId }), - providerInstanceId: run.providerInstanceId, - occurredAt: now, - payload: { ...run, status: "cancelled", queuePosition: null, completedAt: now }, - }, - ]; - if (attempt !== undefined && rootNode !== undefined) { - events.push({ - type: "run-attempt.updated", - threadId: run.threadId, - runId: run.id, - nodeId: rootNode.id, - providerInstanceId: run.providerInstanceId, - occurredAt: now, - payload: { ...attempt, status: "cancelled", completedAt: now }, - }); - } - if (rootNode !== undefined) { - events.push({ - type: "node.updated", - threadId: run.threadId, - runId: run.id, - nodeId: rootNode.id, - providerInstanceId: run.providerInstanceId, - occurredAt: now, - payload: { ...rootNode, status: "cancelled", completedAt: now }, - }); - } - return events; -} - function latestStartedRun(runs: ReadonlyArray): OrchestrationV2Run | undefined { return runs .filter((run) => run.status !== "queued") @@ -2576,7 +2547,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }) { const emitEvent = emit(input.events, input.command); for (const event of queuedRunCancellationEvents(input.projection, input.run, input.now)) { - yield* emitEvent(event); + yield* emitEvent(event); } }, ); @@ -2944,7 +2915,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const mailboxRoles = yield* standingMailboxRoles(projection); let storedQueuedRun = options?.queuedRunId === undefined - ? nextQueuedRun(projection, mailboxRoles) + ? nextQueuedRun(projection, mailboxRoles, checkedAt) : projection.runs.find( (run) => run.id === options.queuedRunId && run.status === "queued", ); @@ -2979,7 +2950,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio queuedRunCancellationEvents(projection, storedQueuedRun, checkedAt), ); projection = yield* readCommandProjection(threadId); - storedQueuedRun = nextQueuedRun(projection, mailboxRoles); + storedQueuedRun = nextQueuedRun(projection, mailboxRoles, checkedAt); } if (storedQueuedRun !== undefined && currentWake !== undefined) { const now = yield* DateTime.now; @@ -3712,10 +3683,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio for (const expiredRun of fold?.expired ?? []) yield* logExpiredDelivery(expiredRun); yield* writeSystemEvents( [ - ...[ - ...(fold === undefined ? [] : [...fold.folded, ...fold.expired]), - ...(mailbox?.folded ?? []), - ].flatMap((spent) => queuedRunCancellationEvents(projection, spent, now)), + ...(fold === undefined ? [] : [...fold.folded, ...fold.expired]).flatMap((spent) => + queuedRunCancellationEvents(projection, spent, now), + ), ...(selectionChanged ? [ { @@ -3848,6 +3818,55 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio yield* notificationTasks(threadId, queuedMessage, projection.subagents), ), }, + ...(mailbox?.folded ?? []).flatMap((folded, index) => { + const message = projection.messages.find( + (candidate) => candidate.id === folded.userMessageId, + ); + if (message === undefined) return []; + const item: OrchestrationV2TurnItem = { + id: idAllocator.derive.userTurnItem({ messageId: message.id }), + threadId, + runId: queuedRun.id, + nodeId: rootNodeId, + providerThreadId: queuedProviderThread.id, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: ordinal * 100 + index + 1, + type: "user_message", + status: "completed", + title: null, + messageId: message.id, + text: message.text, + attachments: message.attachments, + ...(message.context === undefined ? {} : { context: message.context }), + createdBy: message.createdBy, + creationSource: message.creationSource, + ...(message.scheduledTaskId === undefined + ? {} + : { scheduledTaskId: message.scheduledTaskId }), + ...(message.senderThreadId === undefined + ? {} + : { senderThreadId: message.senderThreadId }), + ...(message.linkedSender === undefined ? {} : { linkedSender: message.linkedSender }), + ...(message.sentBy === undefined ? {} : { sentBy: message.sentBy }), + inputIntent: "queued_turn", + startedAt: now, + completedAt: now, + updatedAt: now, + }; + return [ + { + type: "turn-item.updated" as const, + threadId, + runId: queuedRun.id, + nodeId: rootNodeId, + providerInstanceId: queuedRun.providerInstanceId, + occurredAt: now, + payload: item, + }, + ]; + }), { type: "run.updated", threadId, @@ -8828,6 +8847,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ]); projection = applyToProjection(projection, event); } + const continuationSourceId = + command.providerFailover?.ofRunId ?? + command.restartContinuationOfRunId ?? + command.usageLimitContinuationOfRunId ?? + command.manualContinuationOfRunId; + const continuationMailbox = + projection.runs.find((run) => run.id === continuationSourceId)?.mailbox ?? []; let modelSelection = command.modelSelection ?? projection.thread.modelSelection; const deliveryClass = command.delivery?.class; const steersByClass = @@ -8870,6 +8896,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio goalCommand === null && deliveryClass === undefined && requestedIntent === undefined && + command.dispatchMode.type !== "queue_after_active" && dispatchMode.type === "queue_after_active" && command.notification === undefined ) { @@ -8877,7 +8904,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const activeMessage = projection.messages.find( (message) => message.id === activeRun?.userMessageId, ); - if (activeMessage !== undefined) { + if ( + activeRun !== undefined && + activeMessage !== undefined && + !mailboxWaitExceeded(activeRun, yield* DateTime.now) && + !(yield* stopReachedRun(command, command.threadId, activeRun.id)) + ) { const senderPriority = mailboxPriority( yield* messageSenderRole({ createdBy: command.createdBy ?? "user", @@ -9437,7 +9469,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio (run) => run.status === "queued" && run.delivery?.coalesceKey === coalesceKey, )) { for (const event of queuedRunCancellationEvents(projection, replaced, releasedAt)) { - projection = applyToProjection(projection, yield* emit(events, command)(event)); + projection = applyToProjection( + projection, + yield* emit(events, command)(event), + ); } } } @@ -9617,6 +9652,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio completedAt: null, checkpointId: null, contextHandoffId: null, + ...(continuationMailbox.length === 0 ? {} : { mailbox: continuationMailbox }), ...(command.sourcePlanRef === undefined ? {} : { sourcePlanRef: command.sourcePlanRef }), ...(command.restartContinuationOfRunId === undefined ? {} @@ -10047,6 +10083,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio completedAt: null, checkpointId: null, contextHandoffId: legacyImportHandoff?.id ?? null, + ...(continuationMailbox.length === 0 ? {} : { mailbox: continuationMailbox }), ...(command.sourcePlanRef === undefined ? {} : { sourcePlanRef: command.sourcePlanRef }), ...(command.restartContinuationOfRunId === undefined ? {} @@ -10204,7 +10241,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } for (const spent of fold === undefined ? [] : [...fold.folded, ...fold.expired]) { for (const event of queuedRunCancellationEvents(projection, spent, now)) { - yield* emitEvent(event); + yield* emitEvent(event); } } for (const expired of fold?.expired ?? []) yield* logExpiredDelivery(expired); @@ -10888,6 +10925,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio mergeBackHandoff?.id ?? legacyImportRecoveryHandoff?.id ?? null, + ...(continuationMailbox.length === 0 ? {} : { mailbox: continuationMailbox }), ...(command.sourcePlanRef === undefined ? {} : { sourcePlanRef: command.sourcePlanRef }), ...(command.restartContinuationOfRunId === undefined ? {} @@ -11258,7 +11296,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } for (const spent of forkFold === undefined ? [] : [...forkFold.folded, ...forkFold.expired]) { for (const event of queuedRunCancellationEvents(projection, spent, now)) { - yield* emitEvent(event); + yield* emitEvent(event); } } for (const expired of forkFold?.expired ?? []) yield* logExpiredDelivery(expired); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index de932c1d87500..dfb8f51f55a91 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -707,6 +707,8 @@ it.each([ function makeLocalCommandHarness(input: { readonly text: string; + readonly mailbox?: boolean; + readonly failMailboxStart?: boolean; readonly manualContinuation?: boolean; readonly nativeResumeUnsupported?: boolean; readonly steeringRestart?: boolean; @@ -943,6 +945,33 @@ function makeLocalCommandHarness(input: { checkpoints: [], updatedAt: now, }; + if (input.mailbox) { + const folded = { + ...run, + id: RunId.make("folded-run"), + userMessageId: MessageId.make("folded-message"), + rootNodeId: null, + status: "queued" as const, + }; + projection = { + ...projection, + runs: [ + { + ...run, + mailbox: [ + { + messageId: folded.userMessageId, + runId: folded.id, + senderRole: "agent", + requestedAt: now, + text: "Folded instruction must survive.", + }, + ], + }, + folded, + ], + }; + } const parentThreadId = ThreadId.make("side-chat-parent"); const parentRunId = RunId.make("side-chat-parent-run"); const parentProviderThread = { @@ -1402,7 +1431,26 @@ function makeLocalCommandHarness(input: { ), ensureThread: fallbackEnsureThread, }; - const startTurn = vi.fn((_turn: ProviderAdapter.ProviderAdapterV2TurnInput) => Effect.void); + const startTurn = vi.fn((_turn: ProviderAdapter.ProviderAdapterV2TurnInput) => + Effect.suspend(() => { + if (input.mailbox) { + expect(projection.runs.find((candidate) => candidate.id === "folded-run")?.status).toBe( + "queued", + ); + } + return input.failMailboxStart + ? Effect.fail( + new ProviderAdapter.ProviderAdapterTurnStartError({ + driver: providerThread.driver, + threadId, + providerThreadId, + runId, + cause: "Synthetic provider refusal before acceptance", + }), + ) + : Effect.void; + }), + ); const sideChatThread = { ...providerThread, nativeThreadRef: { @@ -1497,7 +1545,7 @@ function makeLocalCommandHarness(input: { ), ); const writeIfRunCurrent = vi.fn( - ({ events: incoming, activeAttemptId, expectedStatus }) => + ({ events: incoming, runId: targetRunId, activeAttemptId, expectedStatus }) => "writeFailure" in input ? Effect.fail( new EventSink.EventSinkWriteError({ @@ -1506,7 +1554,7 @@ function makeLocalCommandHarness(input: { }), ) : Effect.sync(() => { - const current = projection.runs.find((candidate) => candidate.id === runId); + const current = projection.runs.find((candidate) => candidate.id === targetRunId); const committed = current !== undefined && current.activeAttemptId === activeAttemptId && @@ -1751,6 +1799,37 @@ function layerStartEffectWorker( ); } +effectIt.effect("consumes folded mailbox runs only after provider acceptance", () => { + const harness = makeLocalCommandHarness({ + text: "Head instruction", + mailbox: true, + sideChat: { contextRun: "current" }, + }); + return Effect.gen(function* () { + yield* harness.start; + expect(harness.startTurn.mock.calls[0]?.[0].message.text).toContain( + "Folded instruction must survive.", + ); + expect(harness.projection().runs.find((run) => run.id === "folded-run")?.status).toBe( + "cancelled", + ); + }); +}); + +effectIt.effect("retains folded mailbox runs when the provider refuses the combined turn", () => { + const harness = makeLocalCommandHarness({ + text: "Head instruction", + mailbox: true, + failMailboxStart: true, + sideChat: { contextRun: "current" }, + }); + return Effect.gen(function* () { + yield* harness.start; + expect(harness.startTurn).toHaveBeenCalledOnce(); + expect(harness.projection().runs.find((run) => run.id === "folded-run")?.status).toBe("queued"); + }); +}); + const enqueueStart = ( projection: OrchestrationV2ThreadProjection, request?: EffectOutbox.OrchestrationEffectRequestV2, diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index de9b8a3c3e191..277c578154920 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -41,6 +41,7 @@ import * as Semaphore from "effect/Semaphore"; import * as ServerConfig from "../config.ts"; import { formatMailboxForProvider } from "./StandingMailbox.ts"; +import { queuedRunCancellationEvents } from "./QueuedRunOrder.ts"; import { CLAUDE_PROVIDER, CLAUDE_QUERY_ENDED_BEFORE_TURN_DETAIL, @@ -2062,6 +2063,7 @@ export const layer: Layer.Layer< } = handoffContext; const retryHandoff = resumedRetryHandoff ?? (yield* prepareRetryHandoff(handoffContext)); const carriesPendingContext = + (run.mailbox?.length ?? 0) > 0 || effectiveHandoffs.length > 0 || retryHandoff.handoffs.length > 0 || retryHandoff.attachments.length > 0 || @@ -2312,7 +2314,8 @@ export const layer: Layer.Layer< !turnInput.message.attachments.some((current) => current.id === missed.id), ); // Like pending history, pending images need a prompt; native resume carries none. - const prompted = context !== "" || missedAttachments.length > 0; + const prompted = + context !== "" || missedAttachments.length > 0 || (run.mailbox?.length ?? 0) > 0; // A resume that must be prompted still needs a request, or the agent has nothing to do. const requestText = turnInput.resume && prompted && userText === "" ? RESUME_PROMPT : userText; @@ -2357,6 +2360,54 @@ export const layer: Layer.Layer< yield* inlineDeliveryLock.withPermits(1)( Effect.gen(function* () { if (promptDroppedOnTerminal) return; + // Keep folded runs queued until the provider accepts the combined prompt. + // Each cancellation compares the stored run so Stop or another delivery wins. + if ((run.mailbox?.length ?? 0) > 0) { + yield* Effect.gen(function* () { + const foldedIds = new Set(run.mailbox?.map((entry) => entry.runId)); + const foldedRuns = projection.runs.filter((candidate) => + foldedIds.has(candidate.id), + ); + const current = yield* projectionStore.getThreadRecords( + projection.thread.id, + ["runs", "nodes", "attempts"], + { + runIds: [...foldedIds], + nodeIds: foldedRuns.flatMap((folded) => + folded.rootNodeId === null ? [] : [folded.rootNodeId], + ), + attemptIds: foldedRuns.flatMap((folded) => + folded.activeAttemptId === null ? [] : [folded.activeAttemptId], + ), + }, + ); + const acceptedAt = yield* DateTime.now; + for (const entry of run.mailbox ?? []) { + const folded = current.runs.find((candidate) => candidate.id === entry.runId); + if (folded?.status !== "queued" || folded.activeAttemptId === null) continue; + yield* eventSink.writeIfRunCurrent({ + threadId: projection.thread.id, + runId: folded.id, + activeAttemptId: folded.activeAttemptId, + expectedStatus: "queued", + events: yield* Effect.forEach( + queuedRunCancellationEvents(current, folded, acceptedAt), + (event) => + Effect.map( + idAllocator.allocate.event({ threadId: projection.thread.id }), + (id) => ({ ...event, id }), + ), + ), + }); + } + }).pipe( + Effect.catchCause(() => + Effect.logWarning("Failed to record accepted mailbox delivery", { + runId: run.id, + }), + ), + ); + } // After provider acceptance, failed delivery bookkeeping must not stop live ingestion. const nativeThreadId = runningProviderThread.nativeThreadRef?.nativeId; yield* Effect.forEach( diff --git a/apps/server/src/orchestration-v2/QueuedRunOrder.ts b/apps/server/src/orchestration-v2/QueuedRunOrder.ts index 1635f4ab51674..5972b7cca2477 100644 --- a/apps/server/src/orchestration-v2/QueuedRunOrder.ts +++ b/apps/server/src/orchestration-v2/QueuedRunOrder.ts @@ -1,4 +1,8 @@ -import type { OrchestrationV2Run, OrchestrationV2ThreadProjection } from "@t3tools/contracts"; +import type { + OrchestrationV2DomainEvent, + OrchestrationV2Run, + OrchestrationV2ThreadProjection, +} from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; export function isAutomaticCompletionRun( @@ -49,3 +53,54 @@ export function queuedRunsInDeliveryOrder( } } } + +type CancellationEventType = "run.updated" | "run-attempt.updated" | "node.updated"; +type CancellationEvent = { + [Type in CancellationEventType]: Omit< + Extract, + "id" + >; +}[CancellationEventType]; + +export function queuedRunCancellationEvents( + projection: Pick, + run: OrchestrationV2Run, + now: DateTime.Utc, +): ReadonlyArray { + const rootNode = projection.nodes.find((node) => node.id === run.rootNodeId); + const attempt = projection.attempts.find((candidate) => candidate.id === run.activeAttemptId); + const events: Array = [ + { + type: "run.updated", + threadId: run.threadId, + runId: run.id, + ...(run.rootNodeId === null ? {} : { nodeId: run.rootNodeId }), + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...run, status: "cancelled", queuePosition: null, completedAt: now }, + }, + ]; + if (attempt !== undefined && rootNode !== undefined) { + events.push({ + type: "run-attempt.updated", + threadId: run.threadId, + runId: run.id, + nodeId: rootNode.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...attempt, status: "cancelled", completedAt: now }, + }); + } + if (rootNode !== undefined) { + events.push({ + type: "node.updated", + threadId: run.threadId, + runId: run.id, + nodeId: rootNode.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...rootNode, status: "cancelled", completedAt: now }, + }); + } + return events; +} diff --git a/apps/server/src/orchestration-v2/StandingMailbox.test.ts b/apps/server/src/orchestration-v2/StandingMailbox.test.ts index 0b1f898ca5984..7c3987f9edca4 100644 --- a/apps/server/src/orchestration-v2/StandingMailbox.test.ts +++ b/apps/server/src/orchestration-v2/StandingMailbox.test.ts @@ -1,6 +1,7 @@ // @effect-diagnostics nodeBuiltinImport:off -- Hashes the vendored conformance bytes to pin them to the Home source. import * as NodeCrypto from "node:crypto"; import * as NodeFS from "node:fs"; +import { ComposerContextId, ProviderInstanceId } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import { describe, expect, it } from "vite-plus/test"; @@ -87,7 +88,7 @@ describe("standing manager mailbox", () => { }); describe("standing manager mailbox on queued runs", () => { - const model = { instanceId: "codex", model: "gpt" }; + const model = { instanceId: ProviderInstanceId.make("codex"), model: "gpt" }; const senders = [ ["a1", "agent"], ["a2", "agent"], @@ -156,7 +157,9 @@ describe("standing manager mailbox on queued runs", () => { { ...projection, runs: projection.runs.map((run) => - run.id === "run:a2" ? { ...run, modelSelection: { ...run.modelSelection, model: "other" } } : run, + run.id === "run:a2" + ? { ...run, modelSelection: { ...run.modelSelection, model: "other" } } + : run, ), }, head, @@ -165,4 +168,91 @@ describe("standing manager mailbox on queued runs", () => { ); expect(folded.map((run) => run.id)).toEqual(["run:c1", "run:a3", "run:a4", "run:a5"]); }); + + it("promotes old excluded work ahead of a continuous stream of founder messages", () => { + const old = projection.runs[0]!; + const founder = projection.runs[4]!; + const queued = [founder, old]; + expect(rankQueuedRunsByMailbox(queued, roles, old.requestedAt)[0]?.id).toBe(founder.id); + const afterBound = DateTime.add(old.requestedAt, { minutes: 2 }); + expect(rankQueuedRunsByMailbox(queued, roles, afterBound)[0]?.id).toBe(old.id); + const laterFounder = { + ...founder, + requestedAt: DateTime.add(afterBound, { minutes: 1 }), + }; + expect( + rankQueuedRunsByMailbox([laterFounder, old], roles, laterFounder.requestedAt)[0]?.id, + ).toBe(old.id); + }); + + it.each([ + "notification", + "completion", + "attachment", + "command", + "output", + "continuation", + "model", + "person", + ])("bounds priority bypass for a non-batchable %s", (kind) => { + const original = projection.runs[0]!; + const founder = projection.runs[4]!; + const run = { + ...original, + ...(kind === "output" ? { outputSchema: { type: "object" } } : {}), + ...(kind === "continuation" ? { manualContinuationOfRunId: original.id } : {}), + ...(kind === "model" ? { modelSelection: { ...model, model: "other" } } : {}), + }; + const message = { + ...projection.messages[0]!, + ...(kind === "person" ? { createdBy: "user" as const } : {}), + ...(kind === "command" ? { text: "/compact" } : {}), + ...(kind === "attachment" ? { attachments: [{}] } : {}), + ...(kind === "notification" ? { notification: {} } : {}), + ...(kind === "completion" ? { delegatedCompletion: {} } : {}), + } as Parameters[0]["messages"][number]; + const waiting = { runs: [run, founder], messages: [message, projection.messages[4]!] }; + const now = DateTime.add(run.requestedAt, { minutes: 2 }); + expect(mailboxFold(waiting, founder, roles, now).folded).toHaveLength(0); + expect(rankQueuedRunsByMailbox(waiting.runs, roles, now)[0]?.id).toBe(run.id); + }); + + it("expands composer references in a folded message before it reaches the provider", () => { + const message = projection.messages[1]!; + const { mailbox } = mailboxFold( + { + ...projection, + messages: projection.messages.map((candidate) => + candidate.id !== message.id + ? candidate + : { + ...candidate, + text: "Read [Terminal](t3-context://v1/terminal/log)", + context: { + version: 1, + records: [ + { + version: 1, + kind: "terminal", + contextId: ComposerContextId.make("log"), + label: "Terminal", + terminalId: "terminal-1", + terminalLabel: "Terminal", + lineStart: 1, + lineEnd: 1, + text: "synthetic compiler error", + }, + ], + }, + }, + ), + }, + projection.runs[4]!, + roles, + DateTime.makeUnsafe("2026-11-27T11:00:00Z"), + ); + const folded = mailbox.find((entry) => entry.messageId === message.id); + expect(folded?.text).toContain("synthetic compiler error"); + expect(folded?.text).not.toContain("t3-context:"); + }); }); diff --git a/apps/server/src/orchestration-v2/StandingMailbox.ts b/apps/server/src/orchestration-v2/StandingMailbox.ts index e4685351ec7fc..3c04fc84bc698 100644 --- a/apps/server/src/orchestration-v2/StandingMailbox.ts +++ b/apps/server/src/orchestration-v2/StandingMailbox.ts @@ -7,6 +7,7 @@ import { withMessageSenderNote, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; +import { projectComposerContextForProvider } from "@t3tools/shared/composerContextReferences"; import { queuedRunsInDeliveryOrder } from "./QueuedRunOrder.ts"; @@ -89,22 +90,45 @@ export function managerTurnOverBudget(startedAtMs: number, completedAtMs: number export type MailboxRoles = ReadonlyMap; -/** Founder first, then CEO, then the existing delivery order (the sort is stable). */ -export function rankQueuedRunsByMailbox>( - runs: ReadonlyArray, - roles: MailboxRoles, -): Array { - return runs.toSorted( - (left, right) => - mailboxPriority(roles.get(left.userMessageId)) - - mailboxPriority(roles.get(right.userMessageId)), +/** After two minutes, FIFO wins at the next dispatch opportunity, regardless of sender. */ +const MAILBOX_PRIORITY_WAIT_MS = 120_000; + +export function mailboxWaitExceeded( + run: Pick, + now: DateTime.Utc, +): boolean { + return ( + DateTime.toEpochMillis(now) - DateTime.toEpochMillis(run.requestedAt) >= + MAILBOX_PRIORITY_WAIT_MS ); } +/** Founder first, then CEO; overdue work goes first in request order. */ +export function rankQueuedRunsByMailbox< + T extends Pick, +>(runs: ReadonlyArray, roles: MailboxRoles, now?: DateTime.Utc): Array { + const overdue = (run: T) => now !== undefined && mailboxWaitExceeded(run, now); + return runs.toSorted((left, right) => { + const leftOverdue = overdue(left); + const rightOverdue = overdue(right); + if (leftOverdue || rightOverdue) { + return leftOverdue && rightOverdue + ? DateTime.toEpochMillis(left.requestedAt) - DateTime.toEpochMillis(right.requestedAt) + : leftOverdue + ? -1 + : 1; + } + return ( + mailboxPriority(roles.get(left.userMessageId)) - + mailboxPriority(roles.get(right.userMessageId)) + ); + }); +} + /** * Only plain text another agent queued joins a batch. Attachments, commands, completions, * notifications (PR-watch wakes included), structured-output asks and continuations keep their - * own turn, as does anything a person typed, so the transcript still shows it. + * own turn, as does anything a person typed. */ function joinsBatch( run: OrchestrationV2Run, @@ -163,7 +187,13 @@ export function mailboxFold( runId: run.id, senderRole: roles.get(message.id) ?? "agent", requestedAt: run.requestedAt, - text: withMessageSenderNote(message, message.text), + text: withMessageSenderNote( + message, + projectComposerContextForProvider({ + text: message.text, + records: message.context?.records ?? [], + }), + ), }); } return { folded, mailbox }; diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 1484008ecbe2f..2a60ebb5d28ce 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -16356,6 +16356,15 @@ it.layer(layerProviderFailoverTest)("provider failover", (it) => { const [source] = (yield* orchestrator.getThreadProjection(threadId)).runs as [ OrchestrationV2Run, ]; + const mailbox: NonNullable = [ + { + messageId: MessageId.make(`${threadId}:folded-message`), + runId: RunId.make(`${threadId}:folded-run`), + senderRole: "agent", + requestedAt: now, + text: "Replay the folded instruction on the replacement provider.", + }, + ]; const item = (id: string, ordinal: number) => ({ id: TurnItemId.make(`${threadId}:${id}`), threadId, @@ -16377,7 +16386,7 @@ it.layer(layerProviderFailoverTest)("provider failover", (it) => { type: "run.updated", threadId, occurredAt: now, - payload: { ...source, status: "failed", completedAt: now }, + payload: { ...source, status: "failed", completedAt: now, mailbox }, }, { id: EventId.make(`${threadId}:error`), @@ -16481,6 +16490,7 @@ it.layer(layerProviderFailoverTest)("provider failover", (it) => { assert.lengthOf(after.runs, 2); const continued = after.runs.find((run) => run.id !== source.id); assert.equal(continued?.providerFailoverOfRunId, source.id); + assert.deepEqual(continued?.mailbox, mailbox); assert.deepEqual(continued?.modelSelection, scenario.expected.admitted); assert.equal(continued?.providerInstanceId, scenario.expected.admitted.instanceId); }), @@ -16608,3 +16618,253 @@ it.layer(layerProviderFailoverTest)("provider failover", (it) => { }), ); }); + +it.layer(layerTest)("standing mailbox repair", (it) => { + const seedManager = (name: string) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = ThreadId.make(`standing-mailbox:${name}`); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`${threadId}:create`), + threadId, + projectId: ProjectId.make(`${threadId}:project`), + title: "Mailbox manager", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + createdBy: "user", + creationSource: "web", + }); + yield* orchestrator.dispatch({ + type: "thread.standing.set", + commandId: CommandId.make(`${threadId}:standing`), + threadId, + standing: { name: "CTO", role: null, avatarId: "bolt", accent: "sky" }, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:active`), + threadId, + messageId: MessageId.make(`${threadId}:active`), + text: "Initial agent turn", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "agent", + creationSource: "mcp", + }); + return { + orchestrator, + threadId, + active: (yield* orchestrator.getThreadProjection(threadId)).runs[0]!, + }; + }); + + it.effect("shows folded instructions and leaves them queued until provider acceptance", () => + Effect.gen(function* () { + const { orchestrator, threadId, active } = yield* seedManager("transcript"); + const events = yield* EventSink.EventSinkV2; + for (const [name, createdBy] of [ + ["agent", "agent"], + ["founder", "user"], + ] as const) { + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:${name}`), + threadId, + messageId: MessageId.make(`${threadId}:${name}`), + text: `${name} instruction`, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy, + creationSource: "mcp", + }); + } + yield* events.write({ + events: [ + { + id: EventId.make(`${threadId}:complete`), + type: "run.updated", + threadId, + occurredAt: yield* DateTime.now, + payload: { ...active, status: "completed", completedAt: yield* DateTime.now }, + }, + ], + }); + yield* orchestrator.dispatch({ + type: "queue.resume", + commandId: CommandId.make(`${threadId}:resume`), + threadId, + }); + const after = yield* orchestrator.getThreadProjection(threadId); + const head = after.runs.find((run) => run.status === "starting")!; + const folded = after.runs.find((run) => run.userMessageId === `${threadId}:agent`)!; + assert.equal(head.userMessageId, `${threadId}:founder`); + assert.equal(folded.status, "queued"); + assert.equal(head.mailbox?.[0]?.messageId, folded.userMessageId); + const visible = createOrchestrationV2TurnItemVisibility({ + runs: after.runs, + attempts: after.attempts, + items: after.turnItems, + }); + assert.isTrue( + after.turnItems.some( + (item) => + item.type === "user_message" && + item.messageId === folded.userMessageId && + item.runId === head.id && + visible(item), + ), + ); + }), + ); + + it.effect.each(["next_turn", "when_idle"] as const)( + "starts an overdue %s notification before new founder work", + (deliveryClass) => + Effect.gen(function* () { + const { orchestrator, threadId, active } = yield* seedManager(`aged-${deliveryClass}`); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:notification`), + threadId, + messageId: MessageId.make(`${threadId}:notification`), + text: "Pending notification", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + delivery: { class: deliveryClass }, + notification: { + source: { kind: "background_task" }, + outcome: "updated", + summary: "Pending", + }, + }); + yield* TestClock.adjust("2 minutes"); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:founder`), + threadId, + messageId: MessageId.make(`${threadId}:founder`), + text: "New founder instruction", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "user", + creationSource: "web", + }); + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make(`${threadId}:complete`), + type: "run.updated", + threadId, + occurredAt: yield* DateTime.now, + payload: { ...active, status: "completed", completedAt: yield* DateTime.now }, + }, + ], + }); + yield* orchestrator.dispatch({ + type: "queue.resume", + commandId: CommandId.make(`${threadId}:resume`), + threadId, + }); + const after = yield* orchestrator.getThreadProjection(threadId); + assert.equal( + after.runs.find((run) => run.status === "starting")?.userMessageId, + `${threadId}:notification`, + ); + }), + ); + + it.effect.each([false, true])("honors an explicit queue request after Stop=%s", (stopped) => + Effect.gen(function* () { + const { orchestrator, threadId, active } = yield* seedManager(`queue-${stopped}`); + const events = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const providerThread = (yield* orchestrator.getThreadProjection(threadId)) + .providerThreads[0]!; + const sessionId = ProviderSessionId.make(`${threadId}:session`); + yield* events.write({ + events: [ + { + id: EventId.make(`${threadId}:running`), + type: "run.updated", + threadId, + occurredAt: now, + payload: { ...active, status: "running", startedAt: now }, + }, + { + id: EventId.make(`${threadId}:provider`), + type: "provider-thread.updated", + threadId, + occurredAt: now, + payload: { ...providerThread, providerSessionId: sessionId }, + }, + { + id: EventId.make(`${threadId}:session`), + type: "provider-session.attached", + threadId, + occurredAt: now, + payload: { + id: sessionId, + driver: ProviderDriverKind.make("codex"), + providerInstanceId: modelSelection.instanceId, + status: "ready", + cwd: process.cwd(), + model: modelSelection.model, + capabilities: { + ...CodexProviderCapabilitiesV2, + turns: { ...CodexProviderCapabilitiesV2.turns, supportsActiveSteering: true }, + }, + createdAt: now, + updatedAt: now, + lastError: null, + }, + }, + { + id: EventId.make(`${threadId}:turn`), + type: "provider-turn.updated", + threadId, + runId: active.id, + occurredAt: now, + payload: { + id: ProviderTurnId.make(`${threadId}:turn`), + providerThreadId: providerThread.id, + nodeId: active.rootNodeId!, + runAttemptId: active.activeAttemptId, + nativeTurnRef: null, + ordinal: 1, + status: "running", + startedAt: now, + completedAt: null, + }, + }, + ], + }); + if (stopped) + yield* orchestrator.dispatch({ + type: "thread.stop", + commandId: CommandId.make(`${threadId}:stop`), + threadId, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:founder`), + threadId, + messageId: MessageId.make(`${threadId}:founder`), + text: "Queue this for later", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "user", + creationSource: "web", + }); + const after = yield* orchestrator.getThreadProjection(threadId); + const queued = after.runs.find((run) => run.userMessageId === `${threadId}:founder`)!; + assert.equal(queued.status, "queued"); + assert.isUndefined(queued.steerWhenReadyRunId); + }), + ); +}); diff --git a/packages/contracts/src/orchestrationV2.test.ts b/packages/contracts/src/orchestrationV2.test.ts index 5e16fb4a545ad..95bea722c4611 100644 --- a/packages/contracts/src/orchestrationV2.test.ts +++ b/packages/contracts/src/orchestrationV2.test.ts @@ -19,6 +19,7 @@ import { OrchestrationV2ProviderThread, OrchestrationV2ProviderThreadJson, OrchestrationV2RpcSchemas, + OrchestrationV2RunJson, OrchestrationV2Subagent, OrchestrationV2ThreadShellJson, OrchestrationV2SubagentJson, @@ -45,8 +46,46 @@ const decodeOrchestrationV2ProviderThread = Schema.decodeUnknownSync(Orchestrati const decodeOrchestrationV2ProviderCapabilities = Schema.decodeUnknownSync( OrchestrationV2ProviderCapabilities, ); +const decodeOrchestrationV2RunJson = Schema.decodeUnknownSync(OrchestrationV2RunJson); +const encodeOrchestrationV2RunJson = Schema.encodeSync(OrchestrationV2RunJson); +const runWireCodec = Schema.toCodecJson(OrchestrationV2RunJson); +const decodeRunWire = Schema.decodeSync(runWireCodec); +const encodeRunWire = Schema.encodeSync(runWireCodec); describe("orchestration V2 contracts", () => { + it("round-trips a batched run through its JSON persistence and wire codec", () => { + const json = { + id: "mailbox-head", + threadId: "manager", + ordinal: 1, + providerInstanceId: "codex", + modelSelection: { instanceId: "codex", model: "gpt" }, + providerThreadId: null, + userMessageId: "head-message", + rootNodeId: null, + activeAttemptId: null, + status: "queued", + requestedAt: DateTime.formatIso(now), + startedAt: null, + completedAt: null, + checkpointId: null, + contextHandoffId: null, + mailbox: [ + { + messageId: "folded-message", + runId: "folded-run", + senderRole: "agent", + requestedAt: DateTime.formatIso(now), + text: "Keep this queued instruction.", + }, + ], + }; + const run = decodeOrchestrationV2RunJson(json); + expect(DateTime.formatIso(run.mailbox![0]!.requestedAt)).toBe(json.requestedAt); + expect(JSON.parse(JSON.stringify(encodeOrchestrationV2RunJson(run)))).toEqual(json); + expect(decodeRunWire(encodeRunWire(run))).toEqual(run); + }); + it("decodes thread event types from a newer server as skippable items", () => { const decodeWireItems = Schema.decodeUnknownSync( Schema.toCodecJson(Schema.Array(OrchestrationV2RpcSchemas.subscribeThread.output)), diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 838842b075be3..6426cc239722c 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -3084,6 +3084,14 @@ export const OrchestrationV2ThreadVisitJson = Schema.Struct({ export const OrchestrationV2RunJson = OrchestrationV2Run.mapFields((fields) => ({ ...fields, + mailbox: Schema.optional( + Schema.Array( + OrchestrationV2MailboxEntry.mapFields((entry) => ({ + ...entry, + requestedAt: Schema.DateTimeUtcFromString, + })), + ), + ), requestedAt: Schema.DateTimeUtcFromString, startedAt: Schema.NullOr(Schema.DateTimeUtcFromString), completedAt: Schema.NullOr(Schema.DateTimeUtcFromString),