# Agent loop boundaries

`../loop.ts` remains the public `runQuery` entry. The implementation uses explicit
phases and async generators, not a configurable middleware framework. Continuation
decisions stay visible in one place: retry, consult, execute, publish or interrupt.

| Module | Responsibility |
| --- | --- |
| `options.ts` | Existing host injection contract; type-only dependencies |
| `requestPreparation.ts` | Automatic compaction, budget checks, request-local tool fitting |
| `toolExecutor.ts` | Single-call authorization, rules, leases, execution and delivery receipt |
| `toolBatch.ts` | Safe concurrency segments, question/advisor barriers and ordered commits |
| `progressStream.ts` | Callback-to-generator progress bridge and worker settlement |
| `messages.ts` | Model message projection, interrupts, screenshot lifecycle, tool deltas |
| `toolPresentation.ts` | Human-readable tool descriptions; no execution policy |
| `toolSemantics.ts` | Advisor side-effect classification |
| `deliveryIntent.ts` | Existing formal-delivery intent policy |
| `finalPublication.ts` | Pure publication plan for a final answer: label (final/progress), the body the user sees, gate warning and receipt `shownChars`. Only a ledger-backed closed gate may withhold the candidate; the "no file presented" heuristic never does |
| `liveDiagramGate.ts` | Holds back a possible text-drawn diagram in a live answer until its fence closes |

## Ownership and invariants

- The orchestrator owns history, request continuation and turn accounting. Modules
  receive narrow inputs or explicit callbacks, not a shared universal mutable bag.
- History replacement goes through the orchestrator so usage estimates and cache
  edit state are reset consistently. Accumulated turn usage is not reset.
- The effective tool set is both the model catalog and execution boundary. Emergency
  fitting is request-local; it cannot expand host permissions.
- Tool progress is live, but results enter history in model tool-call order.
  Writes and interactive/advisor barriers do not become parallel work.
  Stops of already registered targets may launch ahead of unrelated long work;
  they still pass authorization, never overtake a restart of the same target or
  a human/advisor decision boundary, and their receipts retain original order.
- Host execution hooks start only after preflight checks. UI `tool_start` is a
  separate event: even a denied/deferred request receives a visible result.
- Before each request the orchestrator decides whether the answer can stream
  live (`liveFinal`): only when no delivery check could still hold it back
  (no owed formal delivery or unresolved delegation). The advisor is not such
  a check: its nudge (`advisor/advisorNudge.ts`) never holds an answer or defers
  ordinary work for missing consultation. Explicit consultations still obey the
  dependency check and batch barrier (`../advisor/README.md`). Live text is never retracted — on
  interruption or error only the text actually shown is committed, and pending
  messages commit it as progress first. **Correction count never grants
  delivery**: after the one corrective request, a still-open gate (or an
  unreadable ledger) publishes the candidate as `progress` with the status and
  recovery path first, and `turn_done` carries `delivery_incomplete` plus
  `pendingRequired`; only a `ready` gate marks the message `final`
  (`runtime/deliveryGate.ts`). The gate reads the ledger after the response
  settles and right before publishing — the turn loop is the Session's
  serialization point, so the checked snapshot is the one submitted (this does
  not claim cross-process atomicity). The ask correction applies only to
  private drafts; the diagram correction also works live: `liveDiagramGate`
  holds a possible text drawing until its fence closes, and a box stops the
  visible answer right before it — the shown part becomes a progress message and
  the model continues from there. Otherwise the candidate stays private until
  every check passes and is published verbatim; no second tool-free request
  rewrites it. Corrections retire the draft and add a transient reminder (the
  diagram one carries the draft as internal material until the revised answer
  itself arrives, across any skill-loading round); the kernel never
  writes a tool call the model did not make. Advisor failures do not trigger
  repeated consultation on unchanged evidence, including the optional follow-up.
- A non-terminal/truncated model response retains its text generation receipt
  and yields an incomplete turn, never a successful child result or cron run.
- A response with unknown terminal status, damaged SSE data or conflicting
  call identity cannot authorize tool execution. The gateway waits for the
  upstream protocol terminator rather than treating a final delta as EOF proof.
  Recovered calls without receipts have unknown execution state, never an
  automatic replay. Completed receipts retain their original contents.
- Deferred Advisor reads use the same eligibility check as scheduling and receive
  only the unclaimed part of the batch's read allowance. Patch preflight checks
  the rules for every source and destination before execution.
- The last model step may finish without draining notification mailboxes.
  An Advisor followup cannot certify a truncated answer. Prior-goal notices
  retain their delivery-time routing in the transcript but are excluded from
  main requests, compaction prompts and advisor evidence. A saved, explicitly
  completed foreground turn may acknowledge an observed, successful process
  belonging to its goal. An exit code or a partial answer cannot do so.
- The resource ledger counts logical local model requests for this loop and
  its auto/reactive/explicit compaction. Complete input and output usage are
  required for trustworthy totals; child and advisor usage stay separate.
- Cancellation belongs to the host AbortSignal. Progress stream disposal waits for
  active workers to settle; it does not grant permission to leave tools orphaned.
- Hosts supplying `takePendingMessages` keep queued steering inside the run at
  protocol-safe model boundaries, with the original delivery identity. Old calls
  are deferred while input is pending; old final drafts cannot publish. The TUI
  uses a separate mailbox wake signal for AgentWait, not the turn AbortSignal.
  Children retain read/report capability; stale write authority requires a parent
  followup. Without a consumer, `hasQueuedInput` keeps its legacy stop-turn behavior.
- Existing exports from `loop.ts` remain compatible for TUI, Desktop, subagents and
  workflow hosts. The new directory is internal, not a second runtime or protocol.

## Verification

Run `bun run typecheck`, `bun test test/loop*.test.ts test/finalAnswer.stream.test.ts`
and the full Agent suite. Verify Desktop against a refreshed local Agent dependency,
then run its typecheck, tests and web build. npm build must also include the new
modules; no migration or server/database dependency is introduced.
