# Equipo turn batching

2026-11-11, branch `turn-batching` from main 03f8a91.

## What happens today

The instance already batches. This has been the case since the first thin
v1 commit (64cd2ce, the thin v1 spec's §2 "Second message rule", tested by
`TestQueuedMessagesJoinOneTurn` and headless scenario 6).

1. `chatSend` (the page) and `POST /api/v1/messages` (devices) both call
   `Store.Send`, then `txn.send` in one write transaction.
2. `send` looks for the person's queued, undispatched person turn. If it
   finds one, the message joins it. If not, it creates a new turn
   (`chat_turns`, state `queued`). The message row (`chat_messages`) points
   at that turn.
3. If no dispatched turn is in flight (`queued`, `running` or `waiting`),
   `dispatch` runs in the same transaction. It writes one `message` command
   to the person's primary runner's mailbox (`runner_commands`): the
   attachment frames first, then `wire.MessageCommand` with `Text`,
   `PersonText` (one entry per message), the tail and the attachment refs.
   The turn becomes `dispatched`. If a turn is already in flight, the
   message waits in the queued turn.
4. The runner's ack moves the turn to `running`. `reply`, `report`
   (failed or cancelled), `sync` (a turn the runner no longer holds) and
   `Cancel` of an undispatched turn each end the turn and call
   `dispatchNext` in the same transaction. `dispatchNext` dispatches the
   oldest queued turn (the person's own first) once nothing is in flight.
5. The runner (`thin.coordBase.prompt`) puts `Text` under "Newest message"
   in a fresh session, or sends it alone in a warm one. Claude and Codex
   read the same text.

So three messages sent during a slow turn already become one next turn and
one reply. A message sent while nothing runs starts its own turn at once.
The 13 staging turns fit messages that mostly arrived between turns. I
could not check this, because I did not read staging.

## What was missing

- **Distinct messages.** `Text` was the messages joined with a blank line.
  "two\n\nthree" reads the same as one message with two paragraphs. The
  fake coordinator, which splits on blank lines, counted the attachment
  note as a fourth message.
- **Attachments per message.** The runner lists every file of the turn as
  "the person attached these files", with nothing tying a file to the
  message that carried it.
- **Recovery of a stranded queued turn.** Each end path dispatches the next
  turn in the same transaction, so the current code cannot strand one. A
  queued turn left behind with nothing in flight (an older build, a manual
  repair) waited until the person sent another message.

## The change

All of it is on the instance, mostly in its turn building. There is no
wire, protocol, fixture or migration change.

- `dispatch` builds `Text` with `turnText`. One message is sent exactly as
  before. Several messages are sent as:

  ```
  [Equipo: the person sent 3 messages while you were busy, oldest first. Each is a separate message; answer them together in one reply.]

  Message 1 of 3:
  alpha first

  Message 2 of 3 (attached: notes.md):
  bravo second

  Message 3 of 3:
  charlie third
  ```

  `relayFiles` also returns each message's file names. `PersonText` and
  `Attachments` keep their meaning. Every protocol reads `Text` as the
  person's words, so old and new runners get the same frame shape.
- `sync`, after it reconciles, calls `dispatchNext` for the person.
  `dispatchNext` does nothing while a turn is in flight. A stranded queued
  turn therefore starts on the runner's next connection, exactly once.
- **One frame each** (Astra round 1). A runner reads at most
  `wire.MaxFrameBytes` (256 KiB) and refuses a larger frame every time it
  is resent. Each message is up to 16 KiB and goes in twice (`Text` and
  `PersonText`), JSON-escaped. A message joins the newest waiting batch
  only while the batch's own part fits `batchRoom` (the frame less 64
  KiB). Otherwise it starts the next batch, which goes after the first,
  one turn at a time and in order. `dispatch` drops the oldest tail
  messages until the command fits (`fitTail`). The tail never holds the
  messages of a batch still waiting behind the one being sent.
- **A failed runner frame is retryable** (Astra round 1). A store error
  while applying a runner frame used to close the socket with
  `CloseRevoked`, so a real runner stopped as if its credential had been
  revoked. Now it closes with 1011 (internal error): the runner
  reconnects with backoff and resends the unacked frame. `ErrForbidden`
  keeps `CloseRevoked`. A credential revoked meanwhile is refused at the
  handshake (403), and every runner version maps that to revoked. Old
  runners treat any other close code as a reason to reconnect.

## Crash, retry and end cases

| Case | What happens | Contract |
|---|---|---|
| Crash between "turn ended" and "next turn created" | The end and the next dispatch are one transaction. Neither commits. The runner's reply is not acked, so it comes again after the restart. The inbox row rolled back with the transaction, so the reply applies once and starts one next turn. | `TestBatchCrashBetweenTurns` |
| Same reply again, runner reconnects | The inbox drops the duplicate reply. The reconnect resends the same unacked command (same frame id), not a new turn. | `TestBatchCrashBetweenTurns` |
| End committed without its successor | The next `sync` dispatches it once. A second sync does nothing. | `TestBatchStrandedRecovers` |
| Running turn fails, is cancelled, or is lost across a runner reconnect | The batch goes next, once. The ended turn keeps only its own message. | `TestBatchAfterTurnEnds` |
| Running turn retried (attempt 2) | The batch keeps waiting. A message sent during the retry joins it. A late attempt-1 reply is ignored. The batch goes once, after attempt 2 replies. | `TestBatchWaitsForRetriedTurn` |
| The instance refuses the next turn (a store error) with a real runner | The reply rolls back and the socket closes 1011. The runner reconnects and resends the reply, and the batch goes once. | `TestHeadlessBatchAfterRefusedReply` |
| Batch too big for one frame | It is split into several batches, sent one after another, in order. Each frame fits. | `TestBatchSplitsToFitTheFrame` |
| Batch cancelled while it waits | All of its messages end `cancelled` together, unsent. The next message gets a turn of its own. | `TestBatchCancelledWhileWaiting` |
| Bubbles and the queued note | Each message keeps its own bubble in the queued turn. One note sits under the latest one, as the thinking-stale fix did. The note clears for all of them when the batch's frame goes out, before the ack. | `TestBatchMarkerClearsTogether`, `TestHeadlessTurnBatching` |

## Usage attribution

Usage is recorded per turn (`chat_usage.turn_id`). A batch is one
coordinator turn, so it is one user message to the CLI and one result.
Claude's rows come from that result's `model_usage_since_last_result`.
Codex's `CodexTally` counts one provider turn per attempt. Both attribute
the whole batch to the batch turn. Nothing reads usage per message.
`TestHeadlessTurnBatching` checks for one row for the batch turn and none
for any single message.

## Rulings (controller, 2026-11-11)

1. **No hold.** A message sent while nothing runs starts its turn at
   once. A fast first reply beats batching messages that arrive between
   turns.
2. **One note.** The single "Waiting its turn" note under the latest
   waiting message stays, as the thinking-stale fix built it.
3. **Plural failure.** A failed turn that covered more than one message
   says `chat.failed_many`, "The coordinator could not answer these
   messages." (Astra copy pass: KEEP). The page and the event stream
   (`chat-stream.js`, from the turn's `message_ids`) both choose it.
   `TestBatchFailedSaysThemAll` and `TestBrowserInstantThinkingQueued`
   cover it.
