Skip to content

feat(orchestration): standing manager mailbox batches queued work founder-first - #239

Open
nullStack65 wants to merge 3 commits into
release/native-0.1.10from
clo-1303-standing-manager-mailbox
Open

nullStack65 wants to merge 3 commits into
release/native-0.1.10from
clo-1303-standing-manager-mailbox

Conversation

@nullStack65

Copy link
Copy Markdown
Owner

Problem

The standing manager threads (CEO, CTO, CoS and the other standing seats) work through their queue one message per turn, in arrival order. When a founder writes while ten agent reports are waiting, the founder waits behind all of them. This is Linear CLO-1303, the standing manager mailbox issue.

Behavior

On a thread with a standing persona (thread.standing set):

  1. One turn for the queue. The queued run that starts answers every other waiting plain-text agent message in the same turn. They go to the provider after the turn's own message in a <queued-messages> section, each labeled with its sender role. They are stored on the starting run as mailbox entries, and their own queued runs are cancelled. This is the same mechanism and precedent as the existing digest fold.
  2. Priority. The head is chosen founder first, then CEO, then the existing delivery order. A person typing is the founder. A message sent from the standing thread named CEO is the CEO. Everything else is an agent.
  3. Preemption. A founder message steers a turn it outranks (an agent or CEO turn). A CEO message steers only an agent-started turn. Agent messages never preempt. This only upgrades a queue to an active steer when the provider supports steering. It never interrupts and restarts a turn.
  4. Digests still never start a turn (unchanged).
  5. Slow manager turn flag. When a standing-thread run ends after more than 300 s, the server logs standing manager turn exceeded 300 seconds with thread, standing name, run, provider and seconds. It logs only; nothing else acts on it.

Non-standing threads are unchanged: the roles map is undefined and every new branch is skipped.

Port and conformance

StandingMailbox.planDequeue is a TypeScript port of plan_dequeue in closura-agent-config scripts/lane_event_routing.py (PR 1507, commit 40e39541c6). laneEventRouting.conformance.json is a byte-for-byte copy of that repository's config/lane-event-routing/conformance.json. The test pins its sha256, so drift fails CI. Every mailbox case (the ones with queued) is asserted on turns, batch, digest and preempt.

Deliberate deviations from the pure plan

  • Founder-typed messages are not folded into another message's turn. Each one keeps its own turn so it stays visible in the transcript. Several queued founder messages therefore take several turns, founder first.
  • Folded agent text reaches the provider but is not rendered as its own transcript bubble. This matches the existing digest fold.
  • Anything that is not plain agent text keeps its own turn: attachments, slash commands, notifications (PR-watch wakes included), delegated completions, structured-output asks, continuations, a different provider or model, or held, expired or non-next_turn delivery classes.

Queue-latency signal for t3_wake_audit.py

No new table. orchestration_v2_projection_runs already carries:

  • requested_at
  • $.startedAt
  • completed_at
  • provider
  • $.modelSelection.model
  • $.userMessageId, whose prefix is the wake source

A folded message's own run is cancelled without a start time. Its latency is in the starting run's new optional $.mailbox[] entries (messageId, runId, senderRole, requestedAt), which pair with that run's $.startedAt. The run is stored as payload JSON, so this needs no migration.

Related, not in this PR

  • Rule 5, routing PR-watch checks-passed and merged events to merge-queue code, belongs to sibling CLO-1302, the lane event routing issue. No t3code PR exists for it yet. This PR only keeps notification wakes out of the mailbox batch, so it does not overlap with CLO-1302.
  • Provider failover is CLO-1298, owned by the CTO. It is not implemented here.

No UI change.

Verification

  • vp test run src/orchestration-v2/StandingMailbox.test.ts (apps/server): 11 passed. This covers:
    • the conformance hash and every mailbox case
    • 7 queued messages becoming one turn with the founder first, both in the pure planner and on queued-run projections (fold order CEO, then agents)
    • typed-message and model-mismatch exclusion
    • sender role classification
    • the 300 s boundary
  • vp run typecheck (apps/server): 0 errors.
  • vp run check:changed origin/release/native-0.1.10:
    • format, lint, graphql and the 8 affected test files pass.
    • The remaining failures are all in files this PR does not touch, so they are already on the base:
      • knip: unused .github/scripts/set-*-version.cjs, plus unused exports in AgentOutputGate.ts, RemoteDelegation.ts and secretRedaction.ts.
      • web typecheck: Sidebar.logic.test.ts and botOrgTree.test.ts, which are standing-avatar type errors.
  • Not verified: a live standing thread on a fleet host, and the full CI suite (pending on this PR).

Prior art

Searched: t3code orchestration-v2 (digest fold, QueuedRunOrder, CommandPolicy delivery intent) and closura-agent-config scripts/lane_event_routing.py, 2026-11-27.

  • Existing digest fold (digestFold/carriesDigest): reused as the pattern and the cancellation path. It cannot carry actionable messages, so it was extended rather than replaced.
  • queuedRunsInDeliveryOrder: reused as the base order; the mailbox rank is a stable sort on top of it.
  • resolveDeliveryIntent "auto": reused for preemption. No new steering path.
  • Home plan_dequeue and its conformance JSON: ported, with the JSON vendored and hash-pinned rather than reimplemented.
  • External queue or priority libraries: not needed. The ordering is a three-level stable sort.

Deploy: fleet
Verify: on a standing thread, queue several agent messages and one typed message during a running turn. One turn should start with the typed message first and a <queued-messages> block. The queued runs should be cancelled, and $.mailbox should appear on the run in orchestration_v2_projection_runs.

🤖 Generated with Claude Code

…nder-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 <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Important

  • Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

Run configuration

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

…t 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 <[email protected]>
@nullStack65

Copy link
Copy Markdown
Owner Author
{
  "reviewed_base": "9fd13faa16321f87a07916f0550e14b8a99dd47a",
  "reviewed_head": "6f6bbd33e56a01a2d67a731f5d78d11134f2cbe8",
  "reviewer": "codex/gpt-6.1-sol, Codex via T3 Code",
  "reviewer_family": "openai",
  "author_session": "6f6bbd33e56a01a2d67a731f5d78d11134f2cbe8",
  "reviewer_session": "codex:01a22bce-ca2a-7d70-a2f5-0f75bcd90e07",
  "fresh_context": true,
  "review_kind": "full",
  "round_id": "codex:01a22bce-ca2a-7d70-a2f5-0f75bcd90e07",
  "patch_id": "570da82ee3b86ef1c0dd11ed4a88987b3f58e7b8",
  "intent": [
    "Batch queued plain-text agent messages into one standing-manager turn.",
    "Prioritize founder messages, then CEO messages, and steer lower-priority active turns where supported.",
    "Preserve separate delivery for excluded message classes and log standing-manager turns longer than 300 seconds."
  ],
  "prior_findings": [],
  "findings": [
    {
      "id": "O-F1",
      "severity": "important",
      "outcome": "open",
      "file": "packages/contracts/src/orchestrationV2.ts",
      "line": 983,
      "summary": "Mailbox timestamps cannot round-trip through the persisted/wire run JSON schema. OrchestrationV2MailboxEntry.requestedAt uses Schema.DateTimeUtc, but OrchestrationV2RunJson (lines 3085-3097) inherits mailbox unchanged and converts only its other timestamp fields. JSON encoding serializes mailbox[0].requestedAt to an ISO string; decoding then fails with Expected DateTime.Utc at [\"mailbox\"][0][\"requestedAt\"]. ProjectionStore uses this codec for stored runs, including provider turn start reads. Consequently the first nonempty batch creates an unreadable run after the folded runs have already been cancelled, preventing normal execution/readback. Add the nested DateTimeUtcFromString mapping (and a run JSON round-trip regression test), or use an ISO-string field with explicit conversion."
    },
    {
      "id": "O-F2",
      "severity": "important",
      "outcome": "open",
      "file": "apps/server/src/orchestration-v2/StandingMailbox.ts",
      "line": 97,
      "summary": "Strict role sorting can indefinitely starve older work that cannot be folded. Every founder run overtakes all CEO/agent runs regardless of age, while joinsBatch explicitly excludes notifications, delegated completions, attachments, commands, structured-output requests, continuations and differing models. If another founder message queues during each founder-started turn, an old PR failure notification or delegated completion is never selected and never included in a batch. The previous QueuedRunOrder interleaving deliberately prevents this starvation; sorting by role afterward removes that guarantee. A source-function reproduction skipped an older monitor notification for 100 consecutive founder arrivals. Preserve founder responsiveness while bounding bypasses or aging excluded actionable work, with a repeated-arrival regression test."
    },
    {
      "id": "O-F3",
      "severity": "important",
      "outcome": "open",
      "file": "apps/server/src/orchestration-v2/StandingMailbox.ts",
      "line": 166,
      "summary": "Folding silently drops composer context from otherwise eligible agent messages. joinsBatch permits message.context, but mailbox entries copy only withMessageSenderNote(message, message.text). Normal provider delivery calls projectComposerContextForProvider with message.context.records; formatMailboxForProvider simply appends the raw folded text instead. An agent message containing a t3-context reference can therefore be cancelled and sent with only its opaque context ID, without the referenced path, selected code, review diff or other record payload the request depends on. An in-memory fold of an eligible agent mention reproduced the retained opaque link and absent record path. Either exclude contextual messages or project each folded message with its own context records before storing/sending it."
    }
  ]
}

Requested question 1 - Can founder-first ordering starve other queued work indefinitely? Yes. O-F2: excluded actionable items cannot ride along with founder turns, and the role sort has neither aging nor a bounded bypass count. Repeated founder arrivals can keep such items queued forever. Eligible plain-text agent messages normally avoid this specific problem by folding.

Requested question 2 - Can a batch include an item the founder has not seen? Yes. mailboxFold scans all current queued runs, with no comparison to the founder message timestamp, seenMarker or a per-founder seen boundary. A plain-text agent message arriving after the founder queued their message is eligible. The provider receives its text in queued-messages, while its run is cancelled and no separate transcript bubble is created. The existing seen-marker formatting covers only the head message and does not mark the added entries as seen/unseen. This matches the PR body's documented provider-only presentation; I do not treat unseen status alone as an additional authorization defect.

Evidence: inspected the GitHub files diff and pinned-head source for all seven changed files, plus the queue, projection JSON codecs, seen-marker and composer-context delivery paths. Focused read-only checks reproduced the nested schema round-trip failure, 100 bypasses of an older monitor notification, folding of a post-founder message, and loss of its context record. The queue/fold checks executed the pinned source in memory with TypeScript types stripped and an identity sender-note formatter for fixtures without sender metadata. These are focused checks, not a full application/integration test. Full suite, live UI and fleet behavior were not run. No repository files changed.

@nullStack65

Copy link
Copy Markdown
Owner Author

Claude review of the standing manager mailbox (PR #239)

1. Can founder-first ordering starve other queued work indefinitely? Yes, for queued work that cannot join a batch. Plain agent text does not starve, because it folds into whichever turn starts next, including a founder or CEO turn. Delegated completions, notifications (PR-watch wakes included), messages with attachments, structured-output asks, continuations and runs on another model never join a batch. They wait behind every queued founder or CEO run, with no aging. This also overrides the completions/messages interleave in queuedRunsInDeliveryOrder. A CEO thread that keeps replying to a standing thread starves them for as long as it does so (C-F2).

2. Can a batch include an item the founder has not seen? Yes. Every folded item is an agent message. Its run is cancelled before it starts, and the timeline hides cancelled, never-started queued_turn messages. No UI renders run.mailbox. So the founder never sees what the manager answered, and the text survives only in the $.mailbox field (C-F4). If the batched turn fails at start, failover and continuation do not carry the mailbox, and those items are lost (C-F3).

Not run: the PR's test suite. This review read the code only, at the exact head.

{
  "reviewed_base": "9fd13faa16321f87a07916f0550e14b8a99dd47a",
  "reviewed_head": "6f6bbd33e56a01a2d67a731f5d78d11134f2cbe8",
  "reviewer": "claude-opus-5-5, Claude Code via T3 Code",
  "reviewer_family": "claude",
  "author_session": "6f6bbd33e56a01a2d67a731f5d78d11134f2cbe8",
  "reviewer_session": "claude:39b8fc52-6a24-4c7e-96e9-8a3eefc0b798",
  "fresh_context": true,
  "review_kind": "full",
  "round_id": "claude:39b8fc52-6a24-4c7e-96e9-8a3eefc0b798",
  "patch_id": "570da82ee3b86ef1c0dd11ed4a88987b3f58e7b8",
  "intent": [
    "On standing threads, the queued run that starts also answers every other waiting plain-text agent message in the same turn (a <queued-messages> block); those runs are cancelled and recorded on the starting run as $.mailbox entries",
    "Pick the next queued run founder first, then CEO, then the existing delivery order",
    "Upgrade a queued founder send to a steer into an agent or CEO turn, and a queued CEO send into an agent turn, when the provider can steer",
    "Log a warning when a standing-thread turn runs longer than 300 seconds",
    "Port plan_dequeue from closura-agent-config with a hash-pinned conformance JSON"
  ],
  "prior_findings": [],
  "findings": [
    {
      "id": "C-F1",
      "severity": "important",
      "outcome": "open",
      "file": "apps/server/src/orchestration-v2/Orchestrator.ts",
      "line": 8889,
      "summary": "The preemption upgrade only ever fires on sends that explicitly asked to queue, so it overrides the sender's choice. The guard requires requestedIntent === undefined and dispatchMode queue_after_active. The web client (packages/client-runtime/src/operations/commands.ts:1014) leaves deliveryIntent unset only when the composer mode is 'queue'. The default follow-up behavior is 'steer', which already sends deliveryIntent 'steer'. So a normal founder send never reaches this block. Only the sends where the founder pressed the alternate (queue) modifier or set followUpBehavior to 'queue' reach it, and the composer button showed 'Queue' for those. The same holds for agent sends: ThreadManagementService sets deliveryIntent 'auto' unless the caller asked for queue mode. A second effect: the existing stop-reached guard (Orchestrator.ts:8927) checks only command.deliveryIntent === 'auto', so it is skipped here. Failure: the founder stops an agent-started turn on a standing thread and, before the provider winds down, sends a queued message. The server upgrades it to steer_active, and dispatchSteerIntoRun rejects it with 'Target run ... is stopping and cannot be steered'. On the base the message queued. Suggested fix: apply the upgrade only to sends with deliveryIntent 'auto', or drop it, since default sends already steer."
    },
    {
      "id": "C-F2",
      "severity": "important",
      "outcome": "open",
      "file": "apps/server/src/orchestration-v2/StandingMailbox.ts",
      "line": 93,
      "summary": "Founder and CEO ordering is a strict priority with no aging. It also replaces the fairness guarantee in queuedRunsInDeliveryOrder, which interleaves delegated completions with messages by request time 'so neither kind can hold the other back'. Plain agent text cannot starve, because it folds into whichever turn starts next. Work that never joins a batch can starve: delegated completions, PR-watch and other notifications, messages with attachments, structured-output asks, continuations, and runs on another model. Failure: on a standing CTO thread, the CEO thread answers each CTO report with a new message. The CEO message that arrives during a CEO-started turn queues at priority 1. The next pick is that CEO run again, so the CTO's delegated completions and PR-watch wakes wait for as long as the exchange continues. A founder working session on CoS has the same effect, bounded only by how fast the founder types. Suggested fix: rank only messages that can join a batch, or promote any run older than N minutes or N turns ahead of the founder and CEO rank."
    },
    {
      "id": "C-F3",
      "severity": "important",
      "outcome": "open",
      "file": "apps/server/src/orchestration-v2/Orchestrator.ts",
      "line": 3717,
      "summary": "Folded agent messages are cancelled when the batched turn is staged, before the provider accepts it, and nothing re-delivers them if that turn fails. The usage-limit continuation, provider failover and restart continuation dispatch a new run for the head message only. carriesDigest() is false for every *ContinuationOfRunId and providerFailoverOfRunId, so no mailbox is rebuilt, and the cancelled runs are not re-queued. Failure: a CoS turn starts with 6 waiting agent reports folded in. The provider returns a quota or rate-limit error at turn start. Failover replays only the head message on another provider, and the 6 reports are gone; their only trace is the failed run's $.mailbox. The existing digest fold has the same property, but digests are FYI by class. Mailbox items are actionable agent work. Suggested fix: carry run.mailbox forward on continuation and failover runs (and render it in formatMailboxForProvider), or re-queue the folded runs when the head run fails before startedAt."
    },
    {
      "id": "C-F4",
      "severity": "important",
      "outcome": "open",
      "file": "apps/server/src/orchestration-v2/StandingMailbox.ts",
      "line": 145,
      "summary": "A batch includes agent messages the founder never sees, and after the fold the founder cannot see them in the transcript at all. Folded runs are cancelled with startedAt null. packages/shared/src/orchestrationV2Timeline.ts (isHeldRun, plus the visibility filter at lines 108-113) hides every queued_turn user_message whose run is cancelled and never started. No UI renders run.mailbox, and the PR body confirms there is no UI change. On the base, each of these messages got its own visible bubble and turn. Now the founder sees the manager's reply act on instructions and reports whose text appears nowhere in the thread. The text exists only in the $.mailbox JSON in orchestration_v2_projection_runs. This is a real visibility and audit regression for actionable input, unlike the digest precedent it cites. Suggested fix: keep the folded messages visible by marking them delivered with the head run rather than cancelled-unstarted, or render run.mailbox entries under the head message."
    },
    {
      "id": "C-F5",
      "severity": "nit",
      "outcome": "open",
      "file": "apps/server/src/orchestration-v2/Orchestrator.ts",
      "line": 2836,
      "summary": "The CEO role is resolved only through projectionStore.getThreadShell(senderThreadId) on the local environment. A message from a CEO standing thread on another linked environment arrives with linkedSender, and its senderThreadId is not resolvable on this host, so it is silently ranked as 'agent'. Standing seats are spread across machines (config/standing-threads.json), so CEO priority may not apply on hosts other than the CEO's own. It degrades safely, but the documented CEO tier would quietly not exist there."
    }
  ]
}

@nullStack65

Copy link
Copy Markdown
Owner Author

Question 1. Yes, for every queued run the batch refuses. nextQueuedRun sorts founder, then CEO, then everyone else, and never by wait time. joinsBatch leaves notifications (PR-watch wakes included), delegated completions, attachments, commands, structured-output asks, continuations, other models, and person-typed messages on their own runs. Those runs stay behind every later founder message. A founder who queues the next message before the current turn ends, which is normal while talking to a standing manager, keeps a founder run at the head of every drain. There is no age, count, or deadline that lets the excluded work start. Plain agent and CEO text does not starve in the common case: mailboxFold pulls it into the founder turn. A founder turn that skips the fold (outputSchema, or carriesDigest false) leaves even that plain text behind the next founder turn. This is G-F1.

Question 2. A person-typed message cannot be in the batch. joinsBatch requires createdBy !== "user", and founder is only createdBy === "user" with no scheduled task, so a founder message stays its own transcript turn. Every other plain-text queued message can be in the batch whether or not the founder has seen it. The fold does not read seenMessageByFounder, the seen marker, or a user-message turn item. The run is cancelled and no transcript bubble is created, and this PR does not render run.mailbox. That is the stated deviation (agent text goes to the provider and is not shown as its own bubble), so I am not filing it.

{
  "reviewed_base": "9fd13faa16321f87a07916f0550e14b8a99dd47a",
  "reviewed_head": "6f6bbd33e56a01a2d67a731f5d78d11134f2cbe8",
  "reviewer": "grok/magpie-grok, Grok via T3 Code",
  "reviewer_family": "grok",
  "author_session": "6f6bbd33e56a01a2d67a731f5d78d11134f2cbe8",
  "reviewer_session": "grok:01a22bcf-40e2-72a2-99e6-5b042189a77c",
  "fresh_context": true,
  "review_kind": "full",
  "round_id": "grok:01a22bcf-40e2-72a2-99e6-5b042189a77c",
  "patch_id": "570da82ee3b86ef1c0dd11ed4a88987b3f58e7b8",
  "intent": [
    "On a standing thread, start the queued run founder-first, then CEO, then the existing delivery order",
    "Fold other waiting plain-text agent messages into that one turn, store them on the run as mailbox entries, and cancel their queued runs",
    "Steer, and do not restart, when a founder message outranks the active turn or a CEO message outranks an agent turn",
    "Log a standing-manager turn that runs longer than 300 seconds",
    "Port plan_dequeue and vendor the lane-event conformance file byte for byte"
  ],
  "prior_findings": [],
  "findings": [
    {
      "id": "G-F1",
      "severity": "important",
      "outcome": "open",
      "file": "apps/server/src/orchestration-v2/Orchestrator.ts",
      "line": 1170,
      "summary": "Founder-first start order can starve every queued run the batch refuses, with no bound. nextQueuedRun reorders startable runs by sender priority only (founder, then CEO, then everyone else) and never by wait time. joinsBatch then leaves notifications (including PR-watch wakes), delegated completions, attachments, slash commands, structured-output asks, continuations, other models, and anything a person typed on their own queued runs. Each founder message keeps its own turn and sorts ahead of all of those. A founder who sends the next message before the current turn ends leaves a founder run queued at every drain, so that excluded work never starts; nothing promotes it after an age, a count, or a deadline. queuedRunsInDeliveryOrder had interleaved completions and messages by request time so one class could not hold the other back while more of it kept arriving; this rank removes that on standing threads. Plain agent and CEO text is not stuck in the common case: mailboxFold cancels it into the founder turn. A founder turn that skips the fold (outputSchema set, or carriesDigest false for a goal, maintenance, or continuation) leaves even that plain text queued behind the next founder turn."
    }
  ]
}

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

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants