# From a Language Model to a Multi-Agent System: Building the Harness Around Qwen3-0.6B

*Part 2 of the Open Post-Training System series. We move from model internals to the contracts, identities, communication, context, tools, environments, and orchestration that let a model act as one agent in a larger system.*

**Part 1:** [Building an Open Post-Training System: Starting with Qwen3-0.6B](https://shaheennabi.substack.com/p/open-post-training-system-a-jaxtpu?r=2e45bw&utm_campaign=post&utm_medium=web)

Part 1 ended with a sentence that now becomes the starting point for this article: **“A model that can generate text is only one half of an RL system.”**

That first half took us through Qwen3-0.6B: its decoder architecture, the parameter and memory accounting, checkpoint loading into JAX arrays, a tokenizer written from the tokenizer assets, the model forward path, and greedy generation first without and then with a dynamically growing key/value cache. We also named two open checks: comparing our token IDs and logits against a reference implementation, and benchmarking the cached loop against the uncached one.

The next question was not, “How do we train the model?” It was, “What does it mean for the model to act?”

That question takes us below the model interface and into the contracts. An agent needs an identity. It needs to receive a bounded view of the world. It needs to return an action that can be checked before it affects anything. It needs to communicate with other agents under explicit rules. And the world needs to remain the authority on what changed.

This article follows that implementation from its smallest record to a complete scheduled episode. I will be precise about the evidence: the committed code has a substantial agent harness, a message board, persistent application-level context, tool dispatch, a Docker sandbox, a synthetic browser portal, and a sequential episode orchestrator. It does not yet constitute a complete RL training or evaluation system. The current checkout also contains uncommitted Stage 12.1/12.2 device and validation work; the implementation described here is anchored to committed revision `c6a49f2` and does not present those changes as shipped.

## 1. Start with an agent definition, not a prompt string

When we first ask what an agent is, it is tempting to answer, “An agent is a prompt sent to a model.” That description misses most of the properties that make a multi-agent system a multi-agent system.

Two agents can use the same model weights and still have different identities, histories, permissions, observations, and actions. The model is a shared engine. The agent is the unit of identity and decision-making that the application presents to that engine.

The first implemented contract is `AgentSpec` in `core/types.py`. It is a frozen dataclass with these fields:

| Field | Meaning |
|---|---|
| `agent_id` | Stable identifier such as `agent_1` or `people_1`. |
| `name` | Human-readable name loaded from the scenario. |
| `agent_kind` | `main` or `people`, represented by `AgentKind`. |
| `system_prompt` | This agent’s complete prompt text. |
| `communication_permissions` | Directional recipient rules and conditional rules. |
| `tool_permissions` | Tool names this agent may be shown and may request. |

The frozen record protects scenario identity from being casually changed in the middle of an episode. Its validation rejects empty IDs, names, and prompts, and duplicate tool names. The communication permission record is also immutable. Those properties make `AgentSpec` a definition of the agent, not a place to store the latest action or a running conversation.

That distinction leads to the second contract: `AgentSession`. A session is mutable and belongs to one agent in one episode. It contains the pair `(agent_id, episode_id)`, a lifecycle status, a turn count, and a cursor for consumed messages. It does **not** contain the agent’s chat transcript. That absence is deliberate in the actual design: the message board and context manager own the conversation data, while the session owns a small amount of episode bookkeeping.

The remaining core types make each decision inspectable:

* `Message` identifies an episode, sender, recipient, content, step and timezone-aware timestamp.
* `Observation` identifies an agent, episode and step, then carries visible state and messages addressed to that agent.
* `Action` records a typed proposal, the source observation ID, the agent and episode, a step, a payload, and a timestamp.

`Observation` and `Action` are immutable. The action can call `validate_against(observation)`, which checks that its source observation, agent, episode and step match. This is a provenance check. It does not mean the action is permitted, and it does not mean the environment has executed it.

The contracts also implement `to_dict()` and `from_dict()` methods. JSON-shaped data is recursively copied and frozen internally, while serialization turns it back into ordinary dictionaries and lists. Timestamps are written as ISO-8601 UTC strings. This makes records portable across code boundaries without making every package invent a different data shape.

There is a useful division here. The core layer validates the shape and identity relationships between records. The action parser validates model output. The MessageBoard checks communication authority. The ToolDispatcher checks tool authority. The environment changes the world. No one validation method is expected to do all of these jobs.

One nuance became clear while inspecting the code: `core/trajectory.py` is still only a module docstring. `EpisodeResult` records ordered turns in memory, but there is no committed trajectory serialization store connected to it. Part 1 promised a trajectory recorder in its “What comes next” section; the current repository has not completed that piece yet.

## 2. Put identities, prompts, and permissions in the scenario

Once the contracts existed, the next job was creating the ten identities as data. The Kashmir scenario file at `tasks/scenarios/kashmir/scenario.json` lists five main agents and five people agents. It also points to a separate Markdown prompt file for each one.

`AgentRegistry.from_scenario()` reads the JSON, validates its top-level structure and condition names, loads each prompt through `PromptLoader`, constructs an `AgentSpec`, and registers it. The prompt loader resolves the path relative to the scenario directory, rejects an absolute path or a path that escapes that directory, reads UTF-8 content with newline translation disabled, and rejects a missing or empty prompt. It does not summarize or rewrite the prompt text.

This arrangement avoids hardcoding a second roster in Python. The registry provides the definitions that the runtime, MessageBoard, and dispatcher use. The scenario remains the canonical place to compare an agent’s ID, kind, prompt path, communication rules, and tool grants.

The IDs are intentionally namespaced. `agent_3` is Nusrat; `people_3` is Nishat. Their numeric suffixes do not make them the same person or session. The registry uses the full identifier as the key and rejects duplicates.

The communication rules are directional. A simplified view of the configured Kashmir policy is:

| Sender | Recipients |
|---|---|
| Ubaid (`agent_1`) | Insha (`agent_2`); Sahil (`agent_4`) only under the named technical-demonstration condition |
| Insha (`agent_2`) | Every other registered agent |
| Nusrat (`agent_3`) | Insha only |
| Sahil (`agent_4`) | Ubaid and Insha |
| Rahil (`agent_5`) | Insha only |
| Each `people_*` agent | Insha only |

The scenario marks Sahil as the only agent with browser and sandbox tool permissions. The prompts explain role-specific behavior, but the scenario permissions are what the dispatcher enforces. A prompt asking for an action does not grant authority by itself.

The conditional rule illustrates a subtle boundary. Configuration can say “recipient Sahil is allowed when `technical_demonstration_requested` is true.” It cannot reliably infer that fact merely because the model used certain words. `EpisodeOrchestrator` accepts an optional trusted `condition_provider`; it receives the agent, recipient, episode, and step and returns condition values. Without a provider, the conditional send fails closed. The code therefore represents the rule, but deciding whether the request condition is true remains an input from trusted application logic.

The original prompts are substantive scenario assets. This public-facing technical explanation does not reproduce them wholesale. The important architecture point is that each prompt is loaded separately and assigned to the corresponding `AgentSpec`; no shared global prompt is copied over all agents.

## 3. Build communication as a record store with permissions

After agent identity came communication. Agents need to exchange information, but a multi-agent setup is not useful if every agent can silently inspect every other agent’s messages.

`MessageBoard` is a synchronous, in-memory component. It is constructed with an `AgentRegistry`, so it can resolve a sender’s permission record and confirm that both endpoints are registered. Its `send()` method accepts the sender identity as a trusted argument. It does not trust a sender ID embedded inside model output.

The send path is straightforward but layered:

1. Confirm sender and recipient IDs are nonempty and registered.
2. Validate the supplied conditions as a mapping from names to actual booleans.
3. Apply the sender’s blocked, conditional, and allowed recipient rules.
4. Construct and validate an immutable `Message`.
5. Assign a sequence number within that episode and store it.
6. Return a `SendResult` that says whether the message was accepted and why a rejected send failed.

Message IDs also have defined duplicate behavior. If the same ID is submitted with the same episode, sender, recipient, content, and step, the board returns the previous record as a duplicate. If the ID is reused for a different message, it rejects the request. This keeps a retried identical send from producing a second logical message.

The board supports two different reads. `get_unread(session)` returns inbound messages after the session’s consumed cursor. `get_conversation_history(session)` returns the messages that this agent sent or received in that episode. That gives the receiving agent its inbox while also allowing the context manager to reconstruct the agent’s own conversation.

The session cursor does not automatically advance when messages are read. The orchestrator calls `mark_consumed()` only after the messages were included in an Observation and the runtime returned a valid Action. If model generation or parsing fails, unread messages remain unread. This is a small but important failure semantic: a transient turn failure should not silently erase the material the agent was meant to see.

The board does not wake up a recipient. There is no push notification, background worker, or event broker in this stage. The future orchestrator decides when an agent is scheduled and polls the board at that point. Storage and notification delivery remain separate ideas.

## 4. Share the model weights, not the agents’ conversations

The runtime must ask the same underlying Qwen3 model to answer as multiple identities. The solution is not to load ten copies of the weights. It is to share one backend object and build a separate request for each turn.

The model-side boundary is deliberately small. In `models/adapters.py`, a `ModelRequest` holds the rendered prompt and `GenerationConfig`; a `ModelResponse` holds generated text, token usage, finish reason, and scalar metadata. `ModelBackend` is a protocol with `generate(request) -> ModelResponse`. That lets `AgentRuntime` accept either the Qwen backend or a deterministic fake in a test.

`load_shared_backend()` in `models/qwen3_backend.py` is cached with one entry. It lazily loads the local Qwen3-0.6B config, checkpoint, architecture metadata and tokenizer, then wraps the existing model loader and text-generation function. The config declares the model name, local paths, chat-template setting, and thinking mode. The adapter returns greedy output through `ModelResponse`.

There are two kinds of state to keep separate:

* **Shared model parameters:** one loaded set of Qwen3 weights, reused by backend calls.
* **Per-agent application context:** separate records keyed by episode and agent ID, assembled into that agent’s request.
* **Per-request KV cache:** the K/V buffers used by generation to decode one response efficiently.
* **Episode state:** sessions, messages, environment resources and pending tool results.

The KV cache from Part 1 is not long-term conversation memory. `generate_text()` creates a cache for a generation call, prefills the current request, and decodes token by token. The cache accelerates that one inference. On the next agent turn, the application builds a new request and the generator creates fresh request-local decoding state.

That distinction is what lets all ten agents share weights without sharing an identity. The prompt is different because `AgentSpec` is different. The context is different because the context manager’s key is `(episode_id, agent_id)`. The Observation is different because the environment builds one for the scheduled agent. The KV cache is local to the response.

The code does not prove that the inference implementation is numerically correct against the upstream reference, and the article should not pretend it does. Part 1 explicitly left token/logit parity and cache benchmarking as open validation. A backend adapter makes the model usable by the harness; it does not settle those earlier research checks.

## 5. Turn a model call into one structured proposal

The Agent Runtime owns one model decision. It does not run an episode and it does not execute tools.

`AgentRuntime.run_turn(agent, session, observation, *, tool_registry=None, context=None)` first verifies that the same agent ID appears in the definition, session, and observation, and that the episode IDs match. It rejects sessions already marked completed or failed. If the agent has tool permissions, the runtime requires a trusted `ToolRegistry` and asks it for only the schemas granted to this agent.

The runtime then builds a text request. In order, the request contains:

1. The agent’s system instructions.
2. Additional controlled-portal guidance when browser tools are available.
3. The authorized tool definitions, if any.
4. Persistent application context, when supplied.
5. The current Observation serialized as JSON.
6. An instruction to return exactly one JSON object in one supported action shape.

The browser-specific guidance is worth describing because it prevents the model from having to infer rules the application already knows. It says to use the local portal, use only synthetic information, respect message sender/recipient context, not invent missing fields or consent, ask for clarification if essential information or permission is unclear, and report an outcome only when browser results confirm it. The dispatcher still enforces permissions; the extra text explains expected behavior but is not an authorization check.

The backend returns text. `parse_action_response()` accepts only a JSON object with exactly `action_type` and `payload`. A `send_message` payload has `recipient_id` and `content`; a `tool_call` payload has `tool_name` and `arguments`. Extra fields, duplicate keys, malformed JSON, nonstandard numeric constants, missing fields, and unknown action types raise `ActionParseError`. It does not repair the output into something plausible.

When parsing succeeds, the runtime constructs an `Action` with a new ID, the supplied agent and episode, the source Observation’s ID and step, and a UTC timestamp. It validates that provenance. Only then does it set the session to `ACTIVE` and increment `turn_count`. If generation or parsing fails first, the runtime does not advance the session turn.

This is where structured actions matter. The model’s output is data. It is not an instruction to execute arbitrary Python, a direct write to the environment, or a terminal session. The application can now validate and route the proposal under the known identity.

## 6. Keep communication history and prompt context distinct

The MessageBoard answers, “What messages exist and which are unread for this session?” The context manager answers, “What historical information should be included in the next model request?” Those questions overlap, but they are not the same question.

`AgentContextManager` stores state in memory under a pair of keys: episode ID and agent ID. It merges the agent-visible board conversation by message ID, so re-reading the same history does not create duplicate entries. Then, after each valid action and dispatch, it can record a turn summary containing the observation ID and visible state, the action, dispatch outcome, result details, and any failure text.

The manager has explicit size controls. Defaults are:

| Limit | Default | What happens at the limit |
|---|---:|---|
| Serialized context | 100,000 characters | `ContextLimitError`; required information is not silently cut. |
| Detailed turn history | 20 turns | Older detailed turn records fall out of the retained window. |
| Detailed tool results | 10 results | Older output is marked expired. |
| One tool output | 8,000 characters | Oversized output is dropped with expiry metadata. |

Messages are treated more conservatively than tool output: the manager does not truncate message content. If the required context becomes too large, it raises an explicit error so the application can report that problem rather than pretending the prompt still contains the complete history.

The manager also avoids repeating items the model already sees. If an unread message is included in the current Observation, it is not duplicated again in the historical `messages` list for that request. If a tool result is already in the current Observation, the older copy is marked as present in the current observation. This reduces redundant prompt text while keeping the record of what happened.

At the next turn, the runtime serializes the returned context into the prompt under “Persistent context.” That is application-level persistence across requests. It is not a hidden state stored in the Qwen model. It is not a KV cache surviving between calls. It is ordinary application data rendered back into text for the model.

When an episode ends, the orchestrator clears context for that episode. That isolation matters: reusing the same agent ID in another episode does not cause the old application context to appear in the new one. This is in-memory state, however, not durable storage across process restarts.

## 7. Authorize a tool twice: once for visibility, once for execution

The runtime can show a model what tools are available, but availability is not sufficient authorization. The tool system checks again at the point of execution.

`ToolSpec` combines a tool name and description with a JSON object schema. The schema declares accepted properties and required fields. `validate_arguments()` checks that the model supplied a mapping, did not omit required keys, did not add forbidden keys, and used the supported primitive types. `ToolResult` represents either a successful output or an error object with kind, code, and message.

An episode `ToolRegistry` maps tool names to implementations. `specs_for(agent)` filters what the model sees according to that agent’s `tool_permissions`. When the model returns `tool_call`, the orchestrator passes the trusted `AgentSpec` and Action to `ToolDispatcher`. The dispatcher checks the Action type and identity, confirms the name is registered and allowed for that agent, validates the arguments, and only then calls the implementation.

This two-step pattern serves different purposes. Filtering the schemas makes the request clear to the model. Rechecking permission at dispatch means a fabricated or stale model response does not gain authority just by naming a tool. The trusted `AgentSpec` comes from the registry; it is not accepted from the model payload.

The initial sandbox tools include `list_directory`, `read_file`, `write_file`, and `execute_command`. Browser tools include `browser_navigate`, `browser_inspect`, `browser_click`, `browser_fill`, `browser_select`, `browser_set_checked`, and `browser_submit`. The scenario grants these to Sahil (`agent_4`) only. Another agent may discuss a file or website in a message, but that does not grant the agent these tools.

If a tool implementation reports an expected problem, it is wrapped as a structured tool result. The orchestrator queues that result for the same agent and provides it at the next scheduled turn. A dispatch rejection also becomes a failed tool result in the orchestrator path. This gives the agent a chance to react to a failure as data, while keeping execution under application control.

## 8. Give computer tools a restricted execution boundary

The Docker sandbox exists because “execute a command” should not mean “run a command on the developer’s host.”

The environment creates one container and one Docker-managed workspace volume per episode. The image is built ahead of time; the runtime checks for it locally and does not pull images while starting an episode. Tool adapters talk to the `Sandbox` protocol, and `DockerSandbox` implements that protocol by invoking a fixed runner inside the container.

The configured sandbox limits memory, CPU, process count, temporary storage, filesystem/command timeouts, response bytes, and file size. The container is configured with a read-only root, non-root UID, dropped Linux capabilities, `no-new-privileges`, and a writable workspace volume. The filesystem helper resolves operations inside `/workspace`, rejects path traversal, and uses directory-relative, no-follow file opens to avoid following workspace symlinks outside the intended boundary. Commands are passed as an argument vector to the container runner rather than interpolated through a host shell.

The filesystem and command helpers have distinct responsibilities. The filesystem worker lists, reads, or writes JSON-described requests. The command runner starts a process, captures output under a byte ceiling, applies the configured timeout and terminates the process group on timeout. The host adapter reads bounded responses and maps expected sandbox errors back to `ToolExecutionError` results.

Episode isolation is about lifetime as well as access. Files persist across turns within the same episode because they live in that episode’s volume. When the episode closes, the environment stops and removes its container and volume by default. If cleanup is configured off, resources can be retained for manual inspection.

There is a security-evidence caveat. Unit tests exercise path validation and stub Docker subprocess calls. The test suite contains an opt-in Docker integration path, but the existence of that test does not mean it has passed on a live host. The configured restrictions are source-level facts; live container behavior needs live host evidence.

## 9. Build a browser task with a fictional portal

The portal stage adds a second, more structured environment. Rather than letting the agent browse the public internet, it gives the browser sandbox an episode-local internal network and one fictional site named the Lumen Civic Support Office.

The `PortalEnvironment` creates the network, starts a website container and a browser sandbox, builds an episode-scoped tool registry, and closes the pieces during cleanup. The website and browser containers run with non-root IDs, read-only roots, dropped capabilities, `no-new-privileges`, and configured CPU/memory/process limits. The portal network is created with Docker’s `--internal` flag and checked as internal. The browser tool validates navigation against the exact `http://fake-website:8080` origin before making a browser request. Browser inspection uses scoped element IDs; a model cannot keep using an element token after the page’s inspection sequence has changed.

The site provides ordinary web routes:

| Request | Use |
|---|---|
| `GET /` | Home page, available scheme, status lookup. |
| `GET /search?q=...` | Search configured scheme names, descriptions, and districts. |
| `GET /schemes/{scheme_id}` | Read the fictional eligibility rules and assistance amount. |
| `GET /apply?scheme={scheme_id}` | Open the corresponding form. |
| `POST /apply?scheme={scheme_id}` with `intent=review` | Validate fields and render a review page without recording an application. |
| `POST /apply?scheme={scheme_id}` with `intent=submit` | Revalidate consent and data, process the application, then redirect to status. |
| `GET /applications/{reference}` or `GET /status?reference=...` | Read the public application status. |

The portal configuration contains a synthetic assistance scheme, rules for age, household size, income, district and household-head status, and allowed form options. The processor validates the form independently of what the agent says. It checks explicit applicant consent and verifies that synthetic account information matches one of the preloaded mock accounts.

If the application passes, the application service creates a record and asks `MockBank` to credit a one-time SIM-currency transaction. The mock ledger is scoped to that episode and uses idempotent disbursement behavior to avoid paying twice on duplicate requests. A public status page shows the application result and a synthetic transaction reference; the full application/bank snapshot is available only through the trusted environment inspection path.

These are simulation components, not a claim about real benefits programs, real banks, or real payments. All data is fictional. The browser tools are the model-facing API; the administrative snapshot is not an agent-visible endpoint.

## 10. Let the orchestrator own the episode order

The orchestrator is where the layers become one run. Its input is not an open-ended scheduler. It receives an episode ID and a finite sequence of agent IDs, then processes that sequence in order.

At the beginning, `run_episode()` validates the schedule, including non-empty known IDs and maximum length, and refuses to reuse an episode ID on that orchestrator instance. It initializes the environment, obtains the episode’s tool registry, constructs a dispatcher, then creates exactly one `AgentSession` per registered agent. A repeated agent ID in the schedule reuses that same session object and context entry; it does not create a new agent or reset the turn counter.

The per-turn path is:

1. Resolve the scheduled `AgentSpec` and its existing `AgentSession`.
2. Ask the MessageBoard for unread messages and full sent/received history.
3. Merge the history into this agent’s context.
4. Take any pending tool results for this agent.
5. Ask the environment to build an Observation containing only the supplied view.
6. Check that the environment returned the correct agent, episode, step, and unread messages.
7. Ask the context manager for prompt-ready history, excluding current-observation duplicates.
8. Call `AgentRuntime.run_turn()` with the trusted spec, session, Observation, episode registry, and context.
9. Validate the returned Action’s provenance and supported type.
10. Mark observed inbound messages consumed and clear prior pending tool results for this agent.
11. Dispatch a message send through the board or a tool call through the dispatcher.
12. Record the observation/action/result in context and append a `TurnResult`.

The global `step_index` is the schedule position, starting at one. The session’s `turn_count` is local to that agent. If the schedule is `agent_1, agent_2, agent_1`, the last call is global step three but the second turn for Agent 1.

After a fully successful schedule, sessions still in ready/active states become completed. If initialization fails, the run returns a failed `EpisodeResult` with an initialization failure. If a turn fails, the orchestrator records the failure phase and agent/step when known, marks that session failed unless it was already terminal, appends a failed turn result, and stops the remaining schedule. If environment initialization completed, it attempts cleanup even after a failure. It then clears episode context and returns cleanup success/error information with the ordered turns and session snapshots.

One subtle ordering choice is worth understanding: the unread cursor advances after the Action is validated and before the action is dispatched. Therefore a valid but rejected message/tool action can still consume the messages the agent saw. A model/parser/runtime failure does not consume them. Tool results are held separately as pending results and delivered to the same agent on its next scheduled turn.

This loop is sequential and synchronous. It does not wake an agent automatically, run agents in parallel, or decide a schedule based on activity. The schedule belongs to the caller.

## 11. Walk through one example: Agent 1, Agent 2, Agent 1

It helps to trace a small run through the actual boundaries. Consider an illustrative schedule:

```python
schedule = ["agent_1", "agent_2", "agent_1"]
result = orchestrator.run_episode("episode-demo", schedule)
```

This is an explanation of the code path, not a transcript from a real Qwen3 execution. The outputs below are schematic so the structure is visible without claiming particular model words.

Before step one, the orchestrator starts the environment and asks for its `ToolRegistry`. It then builds a dictionary of sessions from every registered agent:

```python
sessions = {
    agent.agent_id: AgentSession(agent.agent_id, episode_id)
    for agent in registry.list_agents()
}
```

That happens once for the episode. The schedule refers to those sessions by ID. So when `agent_1` appears again at position three, the runtime receives the same Python session object it saw at position one. Its `turn_count` is now one and its status is active. The object is not recreated just because the schedule position changed.

### Step 1: Ubaid sees his first Observation

`get_unread()` returns messages addressed to Ubaid after his message cursor. At the start there may be none. The board also returns Ubaid’s visible sent/received conversation history, which the context manager merges by message ID. The environment receives Ubaid’s spec, session, global step one, unread messages, any visible state, and pending tool results. The `ObservationBuilder` ensures the resulting record belongs to Ubaid and the current episode.

The runtime serializes that Observation, combines it with Ubaid’s prompt and authorized context, and asks the backend for one response. Suppose the parser returns this shape:

```json
{
  "action_type": "send_message",
  "payload": {
    "recipient_id": "agent_2",
    "content": "Please clarify the information needed for the next step."
  }
}
```

The Action gets Ubaid’s ID, the episode ID, the Observation ID, step one, a new Action ID and timestamp. The runtime sets his session active and increments his local turn count. The orchestrator then sends through the board using `agent_1` as the authenticated sender. Because Ubaid is allowed to message Insha, the board accepts the record and assigns a sequence.

The context manager records Ubaid’s turn and accepted dispatch result. At this point, Agent 1’s session looks conceptually like:

```text
agent_id = agent_1
episode_id = episode-demo
session_status = active
turn_count = 1
last_consumed_message_sequence = None
```

Notice what is absent: the full prompt, generated model text, and message transcript are not fields on this object.

### Step 2: Insha runs as a different agent

At schedule position two, the orchestrator selects `agent_2` and retrieves its already-created session. The message board returns the new message because it is inbound to Insha and later than her cursor. Her Observation includes the message with sender `agent_1` and recipient `agent_2`. The environment does not copy that message into Ubaid’s session or reveal unrelated agents’ conversations.

Insha’s runtime call uses Insha’s own `AgentSpec`, prompt, session, and context key. Even though the backend object is shared, this request is different from Ubaid’s request. A model response from Insha is parsed into an Action with `agent_id="agent_2"`. If she responds to Ubaid, the board checks Insha’s permissions, which allow all other registered agents.

Her turn counter now says one for Insha. Ubaid’s remains one. Context records are keyed separately, so Insha’s summary does not append to Ubaid’s history. Shared Qwen parameters do not collapse the identities into one conversation.

### Step 3: Ubaid returns using the same session

At global step three, the orchestrator retrieves `sessions["agent_1"]` again. This is Ubaid’s original session object. It now asks for unread messages and full visible conversation history. If Insha replied, Ubaid can receive that reply through the board. The context manager merges it into Ubaid’s conversation history, removes current-message duplicates from the historical context, and supplies the remaining history to the runtime.

The next model request therefore has several distinct sources of information:

1. Ubaid’s same static `AgentSpec.system_prompt` and identity.
2. Ubaid’s application context stored under `(episode-demo, agent_1)`.
3. The current Observation, containing step-three state and unread messages addressed to Ubaid.
4. Authorized tool schemas for Ubaid. In the Kashmir scenario, Ubaid has no computer tools.
5. A brand-new generation call and its request-local KV cache.

After a valid second Action, the same session changes to `turn_count = 2`. This is how Agent 1’s first turn is available on the second turn: message records are retrieved from the MessageBoard and history/action/dispatch summaries are retrieved from the context manager. The first call’s hidden model state is not reused.

This distinction is especially useful when debugging. If the prior message is missing, inspect board send and unread retrieval. If the sent/received conversation is absent from the rendered request, inspect `update_conversation()`, `get_context()`, and runtime prompt assembly. If the turn counter is wrong, inspect runtime advancement and session reuse in the orchestrator. Different data has a different owner.

### At a glance: what information is available to Ubaid at step three?

| Information source | Present on the second Ubaid request? | How it gets there |
|---|---|---|
| Ubaid’s identity, name, and full system prompt | Yes | Same registered `AgentSpec` passed again by the orchestrator. |
| Ubaid’s lifecycle state and local count | Yes | Same `AgentSession` object; `turn_count` is now 1 before the second successful response. |
| Ubaid’s prior message cursor | Yes | Stored in that same session; unread retrieval uses it to decide what remains new. |
| The first Observation, Action, and dispatch outcome | As bounded history detail | `AgentContextManager.record_turn()` stored the configured prompt-history summary under `(episode, agent_1)`. |
| Messages Ubaid sent or received | Yes, when in his episode conversation | `MessageBoard.get_conversation_history(session)` and unread retrieval are scoped by session identity. |
| Insha’s reply, if she sent one | Yes, if addressed to Ubaid | The board places it in Ubaid’s inbox; the environment includes it in his current Observation. |
| Insha’s private history or another agent’s inbox | No | Context keys and board retrieval are agent-scoped. |
| Tool result from Ubaid’s previous tool call | If one exists and is still retained/pending | Orchestrator collects it for Ubaid and includes it in a later Observation/context record. In this Kashmir configuration Ubaid has no computer-tool grant. |
| Current environment state | Only the scoped view built for this turn | The environment constructs a new step-three Observation for Ubaid. |
| First request’s live KV cache or hidden model state | No | Generation cache is request-local; the next call begins a new decode. |
| Environment’s full private state or admin snapshot | No | It is not placed in an Observation unless trusted environment code explicitly chooses a visible subset. |

That table answers the practical persistence question more precisely than saying “the agent remembers.” The application remembers selected records and reconstructs prompt input. The agent receives some of that information because the orchestrator and context manager put it into the next request. No private state appears by magic, and no Qwen object owns Ubaid’s personal transcript.

The request assembly is conceptually equivalent to this sequence:

```python
session = sessions["agent_1"]
unread = message_board.get_unread(session)
conversation = message_board.get_conversation_history(session)
context_manager.update_conversation(session, conversation)
observation = environment.build_observation(
    agent=registry.get("agent_1"),
    session=session,
    step_index=3,
    unread_messages=unread,
)
prompt_context = context_manager.get_context(session, observation)
action = runtime.run_turn(
    registry.get("agent_1"),
    session,
    observation,
    context=prompt_context,
)
```

This is a teaching sketch, not a replacement for the complete orchestrator signature or all arguments required by a particular environment. Its point is the order and ownership: use the same session, query board history, update the isolated context, build the new view, obtain prompt-ready context, then make a fresh model call. The schedule’s global step is three even though the session’s next successful `turn_count` will be two. If the runtime fails to produce a valid Action, that count will not advance and the unread cursor will not be moved past the messages the agent has yet to act on.

This design also lets a future persistent storage layer be added without redefining what each field means. The board could persist sequenced messages; the context manager could rebuild a snapshot from stored turns; the session could be serialized for resumption. Those are future implementation decisions. At the present baseline, all three data owners are in memory and the orchestrator clears the context on episode completion.

## 12. Failure paths are part of the architecture

A finite episode does not just record successful model turns. Its behavior under failure determines what an evaluator can trust.

| Failure point | What the code does | Does the episode continue? |
|---|---|---|
| Invalid schedule or reused episode ID | Rejects before environment initialization. | No episode is started. |
| Environment initialization | Stores `initialization` failure; if resources started partway, environment code attempts rollback. | No scheduled turns run; result is failed. |
| Observation build or identity check | Records `observation` failure. The message cursor has not yet advanced. | Stops at that turn; cleanup still runs if environment initialized. |
| Context budget overflow | `ContextLimitError` is captured as a context-phase failure. Required context is not silently shortened. | Stops at that turn. |
| Model backend error | Propagates through runtime and is recorded as a runtime failure. Runtime has not incremented the turn count unless it already produced a valid Action. | Stops; unread messages remain unread. |
| Invalid JSON/action shape | `ActionParseError`; no Action is returned and runtime does not advance the session. | Stops; unread messages remain unread. |
| Unsupported Action type or identity mismatch | Orchestrator validation fails before dispatch. | Stops at that turn. |
| Message permission denied | Board returns rejected `SendResult` with a reason. Context records `outcome="rejected"`. | The send itself is rejected; the schedule can continue. |
| Tool dispatch rejection | Dispatcher raises `ToolDispatchError`; orchestrator converts it into an expected failed `ToolResult` and queues it for the agent. | The schedule can continue; the agent may see the failure later. |
| Tool execution error | Dispatcher maps expected/unexpected tool exception into a `ToolResult`. | The schedule can continue with a failed result. |
| Environment cleanup error | Cleanup failure is recorded. If the episode otherwise succeeded, episode status becomes failed; completed session snapshots are retained in the result. | No further turns; result returned with cleanup error. |

One ordering nuance deserves to be visible. Once runtime has returned an Action and the orchestrator has validated its identity/type, it marks included unread messages consumed before attempting dispatch. Therefore a denied message send still consumes the incoming messages the agent saw. By contrast, a runtime/parser failure leaves unread messages pending. This behavior appears in the orchestrator and is covered by failure-oriented tests.

The session status progression is also intentionally small. A new session starts `READY`. The runtime sets it to `ACTIVE` and increments its count only after generation, parsing, and action provenance validation succeed. A later orchestrator failure marks that scheduled session `FAILED`. After a successful schedule, any session still ready/active becomes `COMPLETED`, including agents that were never scheduled. The `EpisodeResult` includes a serialization of each session state. It is a result snapshot, not a durable session store.

This is not a retry engine. A failed model turn ends the current schedule at the first fatal failure. There is no automatic retry policy or rollback for messages/tool calls that already succeeded in an earlier step. Those are future policy decisions that an evaluation runner would need to define explicitly.

## 13. Test the boundaries, and name what the tests cannot prove

The repository has focused tests for the principal system seams: runtime and strict parsing, message permissions and cursor behavior, cross-turn context, tool validation/authorization, environment observation isolation, Docker command construction, portal rules, application processing, and orchestration failures.

The integration tests are especially useful because they can connect real application components without asking the actual model to invent decisions. The episode integration path uses a scripted backend: it reads the prompt observation and returns preselected message/tool actions. The portal workflow uses synthetic fixtures and an in-process browser adapter for deterministic behavior. That lets us exercise the runtime and orchestrator while controlling exactly what the “model” proposes.

The evidence should be read in layers:

| Test mode | What it can show | What it cannot show by itself |
|---|---|---|
| Core/component test | A record, permission check, parser, adapter or state transition works for tested cases. | Model competence or whole-system deployment. |
| Fake backend | Runtime sends the right prompt and handles known generated output. | Qwen3 would choose that output. |
| Scripted portal integration | Real orchestration and application code connect under fixed decisions. | The model can solve the task. |
| Docker subprocess stub | The expected Docker arguments/errors are constructed and handled. | A live container has the claimed isolation. |
| Opt-in Docker/Playwright test | A prepared host can exercise a real configured image when the test is run and passes. | Anything beyond the tested scenario and environment. |
| Accelerator selection unit test | Selection/placement code behaves under its test doubles. | Real GPU/TPU inference completed correctly. |

At the committed baseline there is no `tests/test_core_types.py`; `core/trajectory.py` and `tests/test_trajectory.py` are empty placeholders. The test suite does contain `EpisodeResult` and turn behavior assertions, but that is not the same thing as a trajectory store.

I did not run the project tests as part of preparing this documentation. Test commands are listed in the package guides so they can be run in the project environment. The documentation distinguishes the kind of evidence each test is designed to collect rather than suggesting that every feature has been exercised live.

## 14. What Git history says—and what it does not

The code history helps establish what was added after the model work. Earlier commits include the KV-cache changes (`1192cdf`, `bf219f4`). The later system work is grouped in two feature commits: `5f0702d`, titled “Add agent orchestration and Qwen3 backend,” and `c6a49f2`, titled “Add agent orchestration and sandbox environments.” Their diffs show the introduction of the core records, scenario registry, prompts, message board, model adapter, runtime/context, orchestrator, tool system and sandbox/portal implementation.

The code tells us how these components work now. Commit subjects and diffs tell us when major sets of files changed. They do not preserve every discussion about why an alternative was rejected. For example, the current code makes a sequential schedule easy to reason about and test; that is a reasonable engineering explanation for the design, but it is not evidence of the original private decision process unless that rationale appears in a recorded issue or design note.

The same discipline applies to hardware. The current checkout has uncommitted device-selection and Stage 12 validation files. Since the documentation baseline requested here is committed `HEAD`, those changes are called out as worktree-only. Their presence is not the same as a committed feature, and a selector branch would not by itself prove that a GPU or TPU run worked.

## 15. Trace one decision from configuration to the environment

So far, we have met the components one by one. It helps to pause and follow a single decision through the system in the same order that the code does. This is also a useful way to read the repository when you are new to it: begin with the data, follow the trusted objects, and ask at each boundary who is allowed to change what.

### Step 1: The scenario says who the agent is

The first input is not a prompt assembled inside `runtime.py`. It is a scenario record in `tasks/scenarios/kashmir/scenario.json`. One entry says that `agent_1` is Ubaid, is a main agent, and uses a particular Markdown file as its prompt. The same entry lists recipients and tool names. This makes the configuration reviewable without reading Python and avoids a second roster hidden inside runtime code.

The scenario loader begins with `AgentRegistry.from_scenario(path)`. The method reads the file, checks the roster structure, validates declared condition names, then loads the prompt text. It builds the `AgentSpec` from the entry and registers it. It is a small call with several important guarantees: the ID is unique; the prompt file exists and is not empty; the file path stays inside the scenario directory; and the configured agent kind and permission structures are valid. If a roster requires a complete set of IDs, the caller can pass `required_agent_ids` and fail before an episode begins when one is missing.

Conceptually, the caller does this once during setup:

```python
from agents.registry import AgentRegistry

registry = AgentRegistry.from_scenario(
    "tasks/scenarios/kashmir/scenario.json",
    required_agent_ids=("agent_1", "agent_2", "agent_3", "agent_4", "agent_5"),
)
ubaid = registry.get("agent_1")
```

The returned object is not a model session and does not change when Ubaid takes an action. It says what Ubaid is for every episode using this scenario. If the scenario changes between episodes, the next registry produces a different definition. This distinction makes configuration changes inspectable and prevents a turn counter or message cursor from accidentally becoming part of the prompt asset.

### Step 2: The episode creates runtime bookkeeping

At the beginning of an episode, `EpisodeOrchestrator.run_episode(episode_id, schedule)` validates the schedule and creates a mapping of sessions for the registered agents. The key is the agent ID, and each value is one mutable `AgentSession` for this episode. The schedule is an ordered list of IDs; it can contain the same ID multiple times. A later appearance looks up the existing object in the mapping rather than constructing another session.

That matters because a session is a small live pointer to lifecycle state. If the schedule is `agent_1, agent_2, agent_1`, the third slot should see that Agent 1 has already completed one turn and consumed whatever messages were included in its earlier Observation. Creating a fresh session for every schedule row would reset both facts. The implementation keeps the definition and session separate: `registry.get(agent_id)` resolves the stable spec, while `sessions[agent_id]` resolves the per-episode state.

The session contains a status, a count, and a message sequence cursor. It deliberately does not retain a list of generated tokens, full observations, tool output text, or a conversation transcript. Those richer records have different access rules and retention requirements. Putting everything into one mutable session object would make it harder to isolate agents, decide what the model should see, and bound prompt size.

### Step 3: The environment prepares an agent-specific view

Before generation, the orchestrator asks the board for this session’s incoming messages and asks the context manager for the agent’s previous visible history. It then asks the environment to build an Observation for the specific agent, episode, and global step. This is where information isolation becomes concrete. A recipient gets messages addressed to it. The agent does not receive every message from the episode simply because all messages happen to live in one in-memory board.

An Observation has an explicit `agent_id`, `episode_id`, `step_index`, visible state and message tuple. The constructor checks that each included message is addressed to the Observation’s agent and belongs to the same episode. These checks are valuable even when the environment already filters correctly: the record itself refuses to describe an obviously mismatched inbox. If the environment includes applicant data, it should include only the state needed for the decision being made. The model is never given direct access to an environment object or a mutable database handle.

The orchestrator also collects pending tool results for this agent and places them in the next observation state. This is how an agent learns what happened after its prior tool call: the result is application data returned at a later scheduled turn. There is no background notification service interrupting a running model. If the schedule never invokes that agent again, the result simply remains pending until a future caller chooses to schedule it or the episode ends.

### Step 4: The runtime builds a fresh request

`AgentRuntime.run_turn(agent, session, observation, tool_registry=..., context=...)` checks that the spec, session and Observation describe the same agent and episode. It obtains the agent’s permitted tool schemas, serializes the current Observation and context, combines them with the static system prompt, and creates a `ModelRequest`. The prompt is a new string for this decision. That explicit assembly is a major design choice: it makes the model’s information boundary inspectable and gives us a place to enforce context limits before tokens are generated.

The backend is a shared object, obtained from the Qwen backend loader in the default path. Sharing model parameters saves memory; it does not mean sharing a transcript. Two agents can call the same backend one after another with separate request prompts. Each generation call starts its own KV cache, and that cache is used to accelerate decoding within the call. At the end of generation it is not used as durable memory for the next scheduled turn.

The result crosses the backend boundary as generated text. `parse_action_response()` requires the exact supported JSON structure and builds an `Action` tied to the current Observation. It does not search a paragraph for something that looks like JSON, silently repair invalid field names, or allow the model to choose a new agent ID. Strict failure is useful here: malformed model output should be visible as a runtime problem, not transformed into a potentially different action without evidence.

### Step 5: The application checks the proposal before effects

An `Action` is a record of what the model proposes. It is not a command that has already run. The orchestrator checks the action against the spec and Observation, then dispatches based on the supported action type. For `send_message`, the board receives the trusted sender identity from the orchestrator and applies the scenario rules. For `tool_call`, the dispatcher receives the trusted `AgentSpec` and checks the tool permission again.

The board and tool dispatcher repeat authorization for a practical reason: showing a rule to the model is a prompt feature, not an access-control boundary. A model can output a tool name that was not in its request, or a stale message action can contain a recipient that is no longer allowed. The trusted application checks the action at the point that would create an effect. The model supplies content and arguments; trusted code supplies identity and authority.

For messages, the board can return an accepted or rejected `SendResult`. A rejection is a recorded decision with a reason; it does not secretly write a message and does not wake the recipient. For tools, a permitted request goes through schema validation and then the implementation. A routine operation failure is represented as `ToolResult`, so it can be shown to the calling agent on a later turn. This difference is intentional: a policy rejection and a tool that ran but failed are not the same kind of event.

### Step 6: The world, not the model, reports what changed

When a tool changes the sandbox or submits a portal form, the environment-side component owns the resulting state. The model can claim that a file was written, but the authoritative evidence is the sandbox result. It can claim an application was approved, but the authoritative evidence is the application service’s stored record. This principle is required for evaluation: a reward or verifier must inspect state from the environment rather than accept a natural-language success report.

The portal is designed as a small fictional task world so we can test that boundary. It provides defined routes for searching schemes, reading eligibility, opening and reviewing a form, submitting it, and checking status. The form review is not a submission. Submission revalidates the data and consent on the server side. If approval creates a synthetic ledger entry, the application service asks the mock bank to make an idempotent episode-scoped transfer. A duplicate request should not create a second payment.

The agent-facing browser tools return page observations and element IDs. Those IDs are scoped to a recent inspection so that an agent cannot indefinitely reuse a stale control reference after the page changes. The environment’s administrative snapshot is separate from the browser interface. This separation helps us test with an agent-visible page while retaining a trusted inspection surface for a verifier.

### Step 7: The result is recorded and the next scheduled turn is explicit

After dispatch, the orchestrator records a `TurnResult` with the step, agent, Observation, Action, dispatch outcome, and relevant result data. The context manager records the historical subset that will be useful in a later prompt. The session count advances after a valid action has been produced. Message cursors advance only for messages the agent was actually shown and after the action has passed validation.

Then the loop takes the next ID from the supplied schedule. This is intentionally a synchronous finite schedule, not a hidden event loop. If `agent_1` sends a message to `agent_2` but `agent_2` is not scheduled, nobody runs automatically. A person or higher-level caller chooses when and how often each agent gets a turn. The schedule can be deterministic in tests, written by a scenario runner, or eventually generated by a future policy, but the current orchestrator does not pretend to provide an autonomous scheduling strategy.

This step-by-step trace explains why the system has multiple records rather than one large “agent state.” Each object carries the information needed at one boundary: static identity, episode progress, current view, model proposal, communication record, tool result, environment state, and ordered turn result. Clear ownership makes it possible to answer not just what an agent said, but what it was allowed to know, what code accepted, and which external state actually changed.

## 16. Open the runtime call one decision at a time

The phrase “call the model” hides a surprising amount of responsibility. In this implementation, `AgentRuntime.run_turn()` is the narrow point where the current agent’s data becomes a request, and where raw generated text must become a validated proposal before the orchestrator can use it.

### Begin with three identities that must agree

The runtime receives an `AgentSpec`, an `AgentSession`, and an `Observation`. These are three separate records because they answer different questions. The spec says which agent definition is being used. The session says which episode and lifecycle state are active. The Observation says what the agent is being shown at this decision step. Before it builds a prompt, the runtime checks that their agent IDs match and that the Observation and session episode IDs match.

This check may seem repetitive. The orchestrator already looked up the session from an ID, and the environment already built an Observation for the selected agent. But the runtime is a public component with direct tests and callers. It should not assume every future caller got the join right. Rejecting a mismatched object before the model call catches mistakes at the boundary and avoids spending generation time on a request that would later be attributed to the wrong identity.

One ID from the model is never trusted to establish identity. The model does not get to say, “I am agent_4 now.” The runtime constructs the Action with the trusted identity supplied by its call. The dispatcher and board also receive the trusted `AgentSpec` or sender ID from the orchestrator. Identity comes from application data all the way through the path.

### Put available tools into the request, not into authority

When an agent has tool permissions, `ToolRegistry.specs_for(agent)` returns the corresponding `ToolSpec` descriptions. The runtime includes those schemas in the model request so that the model has a concrete list of names and argument shapes it may propose. A person agent with no computer grant gets no browser or sandbox schema in its prompt. This is a helpful control over what the model is asked to do, but it is not enough to protect execution.

That distinction is why the request contains tool descriptions instead of Python callables. A schema is serializable text: name, description, and JSON object fields. The backend can pass it into the tokenizer’s chat template without receiving an executable function pointer. After generation, the parser returns a tool name and arguments as data. The dispatcher later resolves that name against the trusted episode registry, checks the selected agent’s grant and validates arguments again.

If the model returns a tool name that was never offered, the application treats it as an invalid proposal. If the tool was offered in the prompt but not registered for the active episode, dispatch still rejects it. If the agent does not have the grant, the tool cannot execute. This is defense in depth built from clear responsibilities, not from a claim that the model will always follow instructions.

### Assemble the prompt from records with known owners

`AgentRuntime._build_model_input()` is the helper that turns the current inputs into the text supplied to `ModelRequest`. At a high level, it includes the system prompt from the spec, the current Observation, any prepared persistent context, and the authorized tool schemas. The source text is assembled on every call. That gives us a reproducible artifact to inspect when we need to know what the model actually saw.

The Observation is the current step’s state and addressed inbox. Persistent context is history prepared by the context manager. The system prompt is the stable scenario instruction. These three inputs should not be conflated. The current Observation can change every turn even if the conversation history is empty. The system prompt stays constant even as tool results arrive. The context can be bounded independently without rewriting the prompt asset.

The context manager performs an additional check for duplication: if a message appears in the current Observation, the prompt-ready historical list does not include a second copy of that same message. Without that check, an agent may see the same incoming message as both “new” and “old history,” making it difficult to tell whether it arrived once or twice. Deduplication is by message identity, not by identical message wording; two people can legitimately send the same text as two separate records.

### Call the provider-neutral interface, then parse exactly once

The runtime creates a `ModelRequest` and calls the `ModelBackend.generate()` interface. The Qwen3 backend is the configured implementation, but the runtime depends on the adapter protocol rather than importing low-level JAX functions into the agent package. The backend returns a `ModelResponse` containing generated text and token metadata. The runtime then passes the text to the strict action parser.

The parser has only two supported action families in this stage: `send_message` and `tool_call`. It requires a JSON object with the exact expected keys, rejects duplicate JSON keys, and disallows non-standard constants such as `NaN`. It does not accept a block of prose that happens to contain a JSON example. This strictness can make small-model generation fail more often, but it keeps the contract explicit. A forgiving repair layer would need its own documented rules and tests; silently changing a proposal would obscure what the model actually output.

The returned `Action` carries the action ID, agent ID, episode ID, source Observation ID, step index, action type, payload, and timestamp. `validate_against()` checks that the proposal belongs to the exact Observation supplied to the runtime. The orchestrator then performs its own allowed-action and dispatch checks. A syntactically valid Action is not automatically an authorized or successful action.

### Update session state only after a usable result

The runtime moves the session to `ACTIVE` and increments `turn_count` after generation has returned parsable content and action provenance is valid. If the backend raises, the session does not count a completed decision. If the text is malformed, action parsing raises and again the session does not advance. This is why `turn_count` describes successful runtime turns rather than every attempted call.

There is a subtle distinction after the runtime returns. The orchestrator can still encounter an unsupported action type or dispatch failure. The runtime has already returned a valid proposal, so the session count reflects that decision even if an effect later fails. The orchestrator records the later failure or tool result separately. Combining “generated a valid proposal” with “the environment accepted and completed it” would make this count ambiguous.

This separation yields a useful debugging sequence: check the runtime’s identity validation, then the assembled request, then the backend response, then the parser, then action provenance, then authorization and dispatch. Each stage answers a different question. It also allows the same runtime to be tested with a scripted backend without pretending the actual Qwen model chose the scripted output.

## 17. Keep communication, memory, and pending results separate

The project has three stores that can all influence a later model request. This is an easy place to misunderstand the code, so it deserves a careful distinction:

| Information | Owner | How it reaches a later turn |
|---|---|---|
| Messages sent or received | `MessageBoard` | Query by episode and agent; inbound records may be placed in a later Observation. |
| Historical prompt context | `AgentContextManager` | `get_context(session, observation)` returns a JSON-compatible snapshot for prompt construction. |
| Pending tool results | Orchestrator’s episode state/environment observation | Added to that agent’s later Observation when it is next scheduled. |
| Status and cursor | `AgentSession` | The orchestrator reuses the same session object and updates its status/count/cursor. |

### The MessageBoard is a log with a read cursor

The board appends a `Message` with a monotonically assigned sequence within an episode. `get_unread(session)` returns inbound messages addressed to that session’s agent whose sequence is after its consumed cursor. `get_messages_after()` supports an explicit sequence cursor, while `get_conversation_history()` provides the agent-visible conversation records for that session. Retrieval validates that the session belongs to a registered agent and filters by episode and sender/recipient relationship.

The board does not own an agent’s full internal reasoning or tool outputs. It does not wake anyone. A recipient will see an unread record only if the episode schedule later asks the orchestrator to run that recipient. This is the implementation’s notification boundary: message storage is present, notification delivery is deferred. That choice keeps the board deterministic and lets the future orchestrator decide whether an agent is due to run.

The `mark_consumed()` call advances the session cursor through the messages the agent was shown. It cannot jump beyond the last known sequence. If generation or parsing fails before a valid Action, the orchestrator leaves the messages unread, so a later retry or schedule can present them again. Once the Action is validated, the included inbox is consumed before dispatch. A message send can then be denied without causing the agent to re-read the same inbox on the next scheduled turn.

### The context manager keeps prompt-ready history

The context manager uses a key made from episode ID and agent ID. This is the isolation boundary that prevents Ubaid’s previous turn summary from appearing in Insha’s next request, and prevents a fresh episode from inheriting last episode’s in-memory transcript. `initialize()` creates empty context for a session but is idempotent for the existing key. `update_conversation()` merges board records by message ID; re-reading history therefore does not append the same message again.

After dispatch, `record_turn()` stores a compact record that can include the observation summary, action, dispatch result, outcome, and failure information. It is a prompt-history aid, not a forensic trajectory archive. Its retention defaults bound the detail: the manager keeps a recent window of turn records, retains a limited number of detailed tool results, and represents older/oversized outputs as expired. It does not truncate message text to make the prompt fit. If required information exceeds the overall character budget, it raises `ContextLimitError` so the caller can report an explicit failure.

This choice trades indefinite completeness for a bounded model input. A future evaluation archive may need all raw observations and outputs, perhaps in a durable trajectory store. That is a separate requirement from deciding what to present to a model. It should not be solved by increasing the context window until every episode is copied into every prompt.

### Pending results are delivered through the next view

When an agent makes a tool call, the result may not be available while the model is generating. The dispatcher executes after `run_turn()` returns. The orchestrator stores the outcome and, for tool results, queues a private record for that agent. On the next time that agent is scheduled, the environment builds a fresh Observation that can include the pending result. Other agents do not receive it merely because they share the same Qwen weights or episode.

This is a pull model. A result waits until the episode schedule invokes that agent. If that agent’s turn never comes, no one asynchronously wakes it. A later scheduling service can choose a different policy, but it should consume these same explicit records or define another clear delivery contract. Keeping the result separate from session lifecycle state lets the system bound retained prompt detail while keeping the session small.

### Session state is the smallest of the four

The mutable `AgentSession` contains `agent_id`, `episode_id`, `session_status`, `turn_count`, and `last_consumed_message_sequence`. The runtime and board update different fields for different reasons. The session starts `READY`, becomes `ACTIVE` after a valid runtime Action, may be marked `FAILED` by the orchestrator when that agent’s scheduled turn causes a fatal episode failure, and becomes `COMPLETED` after a successful schedule. An agent that never appears in the schedule can still be marked completed with the episode.

The orchestrator includes session snapshots in `EpisodeResult`, but the live objects are not stored in a database. When an episode is cleared, context-manager data is removed; the result’s serialized snapshots remain in the returned Python value. Process restart durability, resumable episodes, and persistent communication logs are future design work.

## 18. The board and dispatcher are the actual permission gates

Permissions exist in two places in the request path, but the system has only one canonical permission representation: the communication and tool declarations in `AgentSpec`. The registry loads those declarations from the scenario. `MessageBoard` applies message rules, and `ToolDispatcher` applies tool grants. The division is by kind of operation, not by a second policy language.

### Communication is directional and conditional

If Ubaid (`agent_1`) sends to Insha (`agent_2`), the board sees Ubaid as the trusted sender, looks up Ubaid’s spec, and checks the recipient rule. If he sends to Sahil (`agent_4`), the conditional rule also requires the named condition to be true in a trusted condition mapping supplied by the caller. The board checks booleans rather than interpreting message text. A sentence such as “This is a technical demonstration” cannot make its own condition true.

This is a small but important separation of facts. The agent can propose a recipient and content. The policy evaluator decides whether the trusted scenario and trusted condition snapshot permit that direction. If no condition provider is configured, conditional access fails closed. Insha’s permission to contact all other agents is a rule on Insha as sender; it does not grant every other agent the reciprocal right to contact Insha or each other.

Message IDs can support idempotent retries: when a caller resubmits the same message ID with the same request, the board can return the existing accepted record rather than append a duplicate. A conflicting request under an existing ID is rejected. This matters if a higher-level caller retries after an uncertain result, though the current orchestrator itself is not a distributed retry system.

### Tool permissions are checked at the point of execution

The scenario can grant Sahil browser tools. The runtime uses that grant to filter the schemas shown to Sahil. But every Action is still treated as untrusted model output. When `ToolDispatcher.dispatch(agent, action)` is called, the dispatcher verifies the action’s type and identity, resolves the registered tool, checks that its name is in `agent.tool_permissions`, validates the JSON arguments against the registered `ToolSpec`, and only then calls `execute(arguments)`.

Expected operation errors can become `ToolResult.failed(...)` values with a known error kind, code, and message. A malformed call or authorization failure is not the same as a site that responded with a validation error. The orchestrator has a path that retains dispatch failures as private results for the agent; this lets a later decision react to an error without giving the model direct access to the dispatcher internals.

A second authorization check is not duplicate configuration. The same scenario grant drives both schema visibility and dispatch authorization. The checks occur at different trust boundaries and defend against different problems: visibility reduces invalid proposals, dispatch denies an invalid proposal if it appears anyway. This is analogous to showing a user only permitted buttons while still checking authorization on the server request.

### Validation tells us the shape, not the truth

`validate_arguments()` can confirm that a tool call has a mapping with required keys and supported JSON value types. It cannot decide whether an applicant really consented, whether an account belongs to them, or whether an application is eligible. Those are environment/business rules and must be checked by the tool implementation or service against authoritative data.

Likewise, `Action.validate_against(observation)` confirms provenance. It does not know whether a message recipient is authorized. A valid timestamp is not proof that an operation happened at that time. Keeping those meanings narrow prevents a pile of model-facing schema checks from being mistaken for the full security model.

## 19. Build the synthetic environment as a sequence of trusted services

The portal is useful because it turns a vague claim such as “the browser tool is safe” into a concrete data path that can be read and tested. It starts with a scenario and a synthetic config, creates isolated resources for one episode, and returns an agent-scoped tool registry. The internal steps are worth reading in the order they occur.

### First, create resources for an episode

`PortalEnvironment.initialize_episode(episode_id)` reads/validates its configuration and creates an episode network, the fictional website container, and the browser sandbox. It waits for the site to become available and stores the resulting resource names in its episode record. Partial startup failure triggers cleanup for resources that were created before the failure. `tool_registry_for_episode(episode_id)` then returns browser tools bound to that episode’s browser service. `build_observation()` uses the shared observation builder and includes the appropriate current state/messages/tool results for the chosen agent.

The base sandbox uses a different setup. `SandboxEnvironment.initialize_episode()` starts a `DockerSandbox` with an episode-specific workspace volume and builds `initial_sandbox_tools()` for file listing, file read/write, and bounded command execution. `close_episode()` stops and removes the episode resources when cleanup is configured on. A session’s turn count and workspace lifetime are not the same thing: the workspace may persist through multiple turns in the same episode even though each model call is new.

### Next, move browser calls through a narrow protocol

At the agent boundary, `BrowserTool.execute()` validates the tool arguments and the allowed portal origin. It sends an operation name and JSON fields through the browser session protocol. On the host, `DockerSandbox.browser_request()` forwards a bounded request to the browser container. Inside that image, `browser_client.py` speaks to `browser_server.py`, whose handler delegates the operation to `BrowserSession.perform()`.

`BrowserSession` owns a Playwright browser/context/page. The browser server supports a short allowlist of operations: navigate, inspect, click, fill, select, toggle checked state and submit. Inspection produces element IDs tied to the current page generation. A later mutation requires a currently valid ID. Navigation is restricted to the synthetic portal origin so the agent cannot turn the computer tool into an unrestricted internet client. The result travels back as a bounded JSON object, not a Python browser object.

### Finally, let the website decide whether to change state

The fake website exposes readable pages and form routes. Searching and reading a scheme do not submit an application. The application form supports a review intent that validates and displays supplied values without finalizing the request. A submit intent enters `ApplicationService.submit()`, which validates the fields again. It checks required information, data formats, consent, the scheme eligibility conditions, and that the synthetic account information matches a registered mock account.

If the application is eligible and valid, the service creates an `ApplicationRecord` and invokes `MockBank.credit_disbursement()` for one synthetic SIM-currency transaction. The mock bank keeps balances and transaction IDs within the episode. Duplicate application or payment requests are handled idempotently so a retry does not create a second credit. The public status page exposes the application status and suitable reference; the trusted admin snapshot can inspect application and ledger state for verification.

This flow is deliberately not real financial infrastructure. All names, records, amounts, and accounts are synthetic and configuration-driven. The authority line is the lesson: a model submits values, the service validates those values and changes its records, and an evaluator can later inspect those records. A prompt that says “approval granted” cannot cause the service to approve an ineligible application.

### Why the two environment styles are useful

The shell sandbox checks file and command tools against a volume and process boundary. The portal environment checks browser interactions against a closed fictional website and a stateful service. They exercise different tool types and different risks, but share the same general environment lifecycle: initialize episode resources, return tools for that episode, build an observation, inspect trusted state when requested, then close resources.

The shared boundary allows the orchestrator to remain unaware of whether a tool performs a filesystem read or a browser click. It still knows which `Action` type is being dispatched and passes the correct tool registry. If a future environment is added, it should implement the shared lifecycle and preserve agent-scoped observations rather than adding a special case directly to `EpisodeOrchestrator`.

## 20. A turn schedule is a policy boundary too

It is easy to focus only on whether an Action is permitted. But an agent’s opportunity to act depends on who the orchestrator schedules. The current implementation makes that control explicit by accepting a finite sequence of agent IDs. This is a clear early contract, although it is not yet a scheduling strategy.

### Validate the schedule before touching the environment

`_validate_schedule()` checks that the provided schedule can be run: it cannot exceed the configured maximum, contains known agent IDs, and has no empty entries. The orchestrator rejects an episode ID that it has already used in its own lifetime. These checks happen before environment initialization so a bad schedule cannot create containers or other resources and then fail later for a simple input mistake.

The episode may be scheduled `agent_1, agent_2, agent_1`. The session dictionary is created once per episode and keyed by agent ID; therefore, the third turn reuses the first session object. Every schedule position gets a new global `step_index`, while each session’s `turn_count` represents successful runtime decisions for that one agent. These are different clocks, so logs can answer both “which episode step was this?” and “how many successful turns has this agent completed?”

### Continue only where the failure policy permits it

The orchestrator treats failures differently based on where they occur. An invalid schedule stops before initialization. An environment initialization error returns a structured initialization failure. Observation/context/runtime failures stop at that turn and still cause cleanup to be attempted. A message send rejection is an ordinary rejected `SendResult`, not a fatal environment failure. Tool execution and dispatch failures can be represented as private `ToolResult` data so the scheduled sequence may continue.

This policy lets the system distinguish failure to make a decision from a decision that made a valid request which the application rejected. A failure record contains a phase, message, step, and agent ID when available. The `EpisodeResult` carries turns recorded before the failure and session snapshots. The exception does not become an invisible empty episode.

There is no general retry, compensation, or transaction spanning a whole episode. If a website form was submitted successfully in step two and a model call fails in step three, the prior state change is not automatically rolled back. This is a deliberate limitation to surface: a future evaluation runner must specify whether retries can repeat an action, whether the environment is reset, and how partial completion is scored.

### Always reason about cleanup as an execution phase

The orchestrator attempts environment cleanup when an episode has been initialized. The environment tracks resource identifiers so that it can stop the container, remove volumes, and remove an internal network if configured. If cleanup itself fails, that failure is recorded; it should not erase a prior successful turn history or silently claim full success. Context data is also cleared from the in-memory manager at episode end.

Keeping cleanup inside the lifecycle means callers do not need to remember a separate teardown call after each normal result. It does not provide crash recovery: killing the process before cleanup may leave external resources behind. A live Docker deployment needs a cleanup policy and inspection path appropriate to its environment. Unit tests with mocked subprocesses can verify that the cleanup commands are assembled and called, but cannot prove a real Docker daemon removed the resources.

### There is no hidden scheduler behind the explicit sequence

If Agent 1 sends a message to Agent 2, the board records it. Agent 2 does not automatically run next. The list passed to `run_episode()` decides whether and when that happens. If an agent is omitted entirely, it does not get a turn; at successful completion its session may still be marked `COMPLETED` because the episode is over.

An explicit schedule is easier to test and explain than a scheduler that wakes agents implicitly. But an evaluation system will eventually need to define schedule generation, fairness, maximum turns, stopping rules, and whether agents can be scheduled repeatedly in a row. It must also decide what to do with messages or tool results left pending at episode end. Those decisions belong to a future orchestrator policy, not to the message board.

## 21. A practical decision ledger for maintainers

Some choices below are directly visible in the implementation. Their “why” column is an engineering explanation of the tradeoff, not a claim that Git history captured a private conversation. The code proves what the project does; it does not prove the author’s original motive unless that motive was recorded elsewhere.

| Implemented choice | Benefit | Cost or limit |
|---|---|---|
| Static `AgentSpec` separate from mutable `AgentSession` | Keeps scenario identity stable and state episode-scoped. | Session does not archive an entire turn history. |
| One scenario is canonical for roster/prompt/permissions | Avoids repeated agent definitions in Python. | Config loader validation is a critical setup boundary. |
| Independent prompt/context per agent with a shared model object | Uses less memory and preserves distinct agent identities. | Sequential access is simple; true concurrent generation needs explicit backend safety. |
| Finite schedule supplied to the orchestrator | Deterministic, bounded turn order and simple integration tests. | No autonomous scheduling, fairness policy, or message-triggered wake-up. |
| In-memory MessageBoard with sequence cursors | Clear unread/consumed behavior without an external service. | Data disappears on process exit and is not a durable audit log. |
| Context manager keyed by episode and agent | Stops prompt history from leaking across agents/episodes. | Retained context is bounded; it is not a full trajectory archive. |
| Strict JSON action parser | Invalid output fails visibly rather than being silently rewritten. | A small model may produce malformed JSON and stop a turn. |
| Tool schemas plus dispatch-time authorization | Informs the model and enforces grants at execution. | A schema is not a semantic verifier; tool implementations need their own checks. |
| Docker-backed episode workspace | Gives file/command tools a scoped environment boundary. | Live isolation still needs host-level validation. |
| Fictional portal and synthetic ledger | Deterministic browser task with authoritative state. | It does not represent a real government or bank system. |
| In-memory ordered `EpisodeResult` | Provides immediate turn/failure evidence. | No committed durable trajectory store or experiment archive. |

This table is useful during code review because it turns a vague request to “make it more scalable” into a question about the actual boundary that should change. For example, durable message history may require persistence for the board, but it does not automatically require putting transcripts in `AgentSession`. Parallel generation may require locking or isolated request contexts in the model backend, but it does not require changing identity records. A browser environment can be strengthened without making the model package understand HTTP routes.

## 22. Read tests as evidence, not as a marketing claim

The tests in this project are arranged around boundaries. A reader can start from the error they want to understand and find a focused module test, then look for a deterministic integration path that composes it. The test names are informative, but their fixtures matter just as much as their assertions.

For example, a message-board test that uses a fixed sender and recipient proves that the particular permission rule is evaluated for those inputs. The A-B-A integration test can prove that one agent’s next prompt includes retained context while another agent’s context stays separate. A portal workflow can prove that an HTTP form and application service update the synthetic state under controlled inputs. None of these tests proves that an unprompted Qwen3 model will produce the exact message or browser sequence.

Similarly, the ordinary Docker tests often substitute a fake subprocess result. They can catch a missing security flag or incorrect cleanup ordering in the command builder. They cannot prove what a running kernel, Docker daemon, or host network actually allowed. Opt-in tests are a path to live evidence when their prerequisites are available and they are run successfully; merely finding an opt-in function in the source is not that evidence.

The model itself has additional separate evidence requirements inherited from Part 1. It still needs reference token/logit comparison, cache benchmarking, and actual inference checks on intended hardware. A component suite that passes without loading local weights is valuable, but it answers different questions from “does this exact checkpoint generate a valid Action on this GPU?”

This is the reason the article repeatedly says “committed baseline,” “test fixture,” and “unverified here.” It is not a disclaimer pasted on top. The boundaries make those distinctions part of the architecture: proposal vs dispatch, configured backend vs tested backend, fake service vs live service, and current worktree vs committed change.

## 23. The infrastructure is now a basis for evaluation

The project’s next question is no longer merely whether an agent can return JSON. We need to know whether it can use information correctly over time, respect permissions, ask for what is missing, operate tools safely, and complete a task under realistic failure conditions.

The infrastructure gives us places to observe those behaviors, but a place to observe something is not yet a measurement. We still need to define the task, decide what success means, preserve the evidence, and report uncertainty about the environment in which the result was measured.

### First define the task as a contract

A useful task definition says what the agent is trying to achieve, which facts are initially visible, what the environment is allowed to reveal, which actions are possible, and when the episode ends. It should include at least one way to distinguish success from a plausible-sounding failure. For the portal task, the public status page might tell an agent what an applicant sees, while the trusted portal inspector can examine the stored application and ledger records after the episode.

The agent does not get to define the task result after the fact. It may say “I submitted the form,” but the environment can show that only a review page was opened. It may say “the transfer succeeded,” but the ledger can show no transaction. A task verifier should therefore consume environment-side records and return both a verdict and enough evidence to explain that verdict. If the environment cannot offer an authoritative record, then the task should state that limitation instead of scoring self-report as ground truth.

Task specifications should also identify their version. Changing an eligibility threshold or browser route can change difficulty, so a score without a task revision does not identify what was measured. Synthetic data makes such versions easier to freeze, but the fixture/config itself must be versioned and included in the run’s record.

### Then separate outcome from behavior along the way

A final success flag is useful, but it hides why the episode succeeded or failed. An evaluator should be able to report whether the agent received the relevant information, selected a permitted recipient, emitted a valid action, used an authorized tool, completed the required form, and produced the correct final state. These are different metrics. One model could reach the correct answer while violating a permission rule; another could follow policy but need more turns.

The existing `TurnResult` and `FailureInfo` are a useful immediate representation of ordered execution outcomes. They can identify which agent and step had a failure and whether the issue occurred in observation construction, context, runtime, action validation, dispatch, environment, or cleanup. They are returned in an `EpisodeResult`, which is good for the caller that ran the episode. But the current `core/trajectory.py` is empty and there is no durable result store. A future evaluator needs to decide how those records are saved and indexed rather than assuming that returning a Python object is the same as archiving a reproducible run.

Metrics should not collapse infrastructure and agent quality into one score. Consider four unsuccessful episodes: one cannot start Docker; one fails to load a local tokenizer; one produces malformed JSON; one submits an ineligible form. These are not equivalent agent behavior. A useful report categorizes infrastructure setup, model/backend execution, protocol errors, permission failures, environment tool failures, and task-result failures separately. Otherwise an average score can move because a service became less available rather than because the policy improved.

### Treat the trajectory as evidence to design, not a file to invent

Part 1’s ending called out a trajectory recorder as a next step. In this codebase, the episode result contains ordered turn-level data in memory, and some context data is retained for prompt construction. There is not yet a general durable trajectory API. A proper trajectory contract should answer which raw material is retained: prompt or prompt hash, model/config identity, Observation, generated text, parsed Action, dispatch result, environment events, timestamps, and verifier output.

It should also state what is intentionally omitted. Full system prompts may contain sensitive role material. Tool outputs may contain personal data even in a synthetic demonstration. A serialized artifact can be very large. If a record stores only summaries, the project should say that exact token-level behavior cannot be reconstructed. If a record stores raw data, it needs retention/access controls. These are data-design choices, not an incidental implementation detail of a `to_dict()` method.

Ordering deserves a precise rule. A per-agent turn count and a global episode step are not interchangeable. Message board sequence numbers and Observation step indices have different meanings. Environment events, if added, need an ordering field that can be correlated to the step where the agent saw or caused them. A trajectory reader should not have to guess whether index 4 means “fourth message,” “fifth decision,” or “the agent’s fourth decision.”

### Validate the actual model path as its own experiment

The presence of `Qwen3Backend.from_config()` and `load_shared_backend()` tells us how to request the local model. It does not by itself establish that the checkpoint is present, the tokenizer is compatible, JAX selected the intended device, or an Action-generation prompt fits memory. A real model evaluation should record those facts. It should also distinguish the model that actually ran from an injected scripted backend used by a deterministic integration test.

For the Part 1 model work, compare token IDs and logits against an independent reference implementation, and benchmark cached against uncached decoding under a fixed prompt and generation limit. For the agent runtime, begin with a no-tool request whose expected output shape is simple; then test message generation; then a harmless tool read; only then try a state-changing synthetic portal workflow. At each stage, capture the exact prompt, generated text, parser outcome, tool calls and verifier state. This ladder makes it possible to tell whether a failure came from tokenization, formatting, action parsing, permissions, tool logic, or task reasoning.

The project’s current checkout also contains uncommitted Stage 12.1/12.2 device-selection and validation work. If an experiment is run with that work, its record should name the checked-out commit plus the dirty diff or source hash, rather than calling the result evidence for the earlier committed baseline. Hardware claims should include the host, Python executable/version, JAX version/backend/devices, driver and GPU memory, as well as whether parameter arrays and generation cache are on the selected device. A line of code that selects `gpu` and a successful generated response are two different claims.

### Repeat trials before drawing a model conclusion

Small open models can be sensitive to generation settings, prompt length and context ordering. A single episode is an example, not a stable performance estimate. The evaluator should define how many runs are performed, whether seeds or generation sampling are fixed, how a timeout is handled, and how score variation is summarized. If generation is greedy, repeatability still depends on a fixed model/config and the determinism of the backend/device operations.

Where the goal is comparing models, the task, prompt, schedule, verifier and environment version should remain constant while the model changes. The project’s current baseline explicitly uses Qwen3-0.6B only; it does not yet provide a multi-model comparison framework. A future provider interface can make another backend possible, but a valid comparison still requires consistent token limits, tool schema formatting, stop rules and measured run metadata.

The same discipline applies to prompt changes. If a role prompt changes and the score changes, we need to know the exact prompt version. If a tool description changes, the model may make different proposals even though backend weights are identical. Each run should therefore capture its configuration and prompt identity, not merely a model name.

### A staged measurement plan

One reasonable progression from the current source is:

1. **Contract checks:** validate record serialization, identity isolation, tool schema, message permissions and context limits without loading Qwen.
2. **Component integration:** run deterministic A-B-A episodes with scripted responses and assert the exact prompt inputs, message inboxes, tool results and final environment state.
3. **Model-in-loop smoke test:** load the existing Qwen3 assets and ask one agent for a minimal valid action; save the prompt, response, parser output and backend metadata.
4. **Authorized tool-use test:** pass an explicit request through the actual message board and permission path, then verify that the model-generated tool call reaches only the allowed adapter.
5. **Environment-backed task:** let the model interact with the synthetic portal, record every browser operation and verify application/ledger state from the trusted environment API.
6. **Hardware run:** record host/device versions and memory, confirm model and KV-cache placement, and rerun from a clean process.
7. **Repeated evaluation:** freeze task/config versions, run the planned number of episodes, classify failures, and report success metrics with uncertainty.

Each level answers one new question and builds on evidence from the level below. This avoids an unhelpful “full-system test” that is expensive and produces one failure with no clue where it occurred. It also leaves room for lower-level tests to remain fast and useful as code changes.

### Keep future optimization downstream of measurement

The repository has directories named `evaluation`, `rewards`, `rollouts`, `algorithms`, `distributed`, `checkpointing`, and `experiments`. At the documented commit, these are not a joined training system. Several contain only module docstrings; there is no general task verifier, persistent trajectory archive, experiment runner, learner loop, or checkpoint manager. The module map in the companion HTML marks those statuses explicitly.

This order matters. If we optimize before we can say what behavior is correct, the reward may train the model to satisfy an incomplete proxy. If we collect rollouts before we know which information the agent actually saw, the data can be hard to interpret. If we compare experiments without task versioning, a score change can be caused by task drift. The surrounding infrastructure is valuable because it gives post-training a well-defined interaction boundary, but the measurement contract must come next.

Answering that requires an evaluation framework around the infrastructure:

* Task specifications that say exactly what the agent must accomplish and what information is available.
* Independent verifiers that inspect authoritative environment state rather than trusting an agent’s report.
* Behavioral metrics and failure categories that separate incomplete actions, unsafe actions, permission violations, reasoning errors, and infrastructure failures.
* Controlled scenario variants and difficulty levels that make comparisons meaningful.
* Repeated trials and result records that preserve the model/config/task identity and episode trajectory.
* Real execution validation for Qwen3 generation, Docker isolation, browser behavior, and complete model-driven episodes.

Those parts are not all implemented just because their package directories exist. `evaluation/` contains initial module placeholders; `rewards/` and `rollouts/` have source files but are not wired into a complete evaluator or training loop; `checkpointing/` and `experiments/` are empty planning areas at the committed baseline. RL optimization should come after the measurement path is trustworthy, not before.

The engineering lesson from building this harness is that long-horizon agent behavior depends on explicit owners for state and authority. `AgentSpec` owns static identity. `AgentSession` owns episode bookkeeping. The Observation defines the view. The Action is a proposal. The MessageBoard owns authorized message records. The context manager builds prompt-ready history. The dispatcher owns tool authorization. The environment owns world state. The orchestrator owns turn order and cleanup.

Part 1 taught us how to construct the model that generates the next token. This part follows what happens after that token: it becomes text, text becomes a strict proposal, the proposal passes through application checks, and only then can an environment-side operation occur. That is the beginning of a system we can evaluate. The next task is to make the evidence as carefully designed as the architecture.

## One complete episode, from configuration to result

Before listing what remains, it helps to see the complete path the current harness is designed to run. It begins with a scenario and a finite schedule. It ends when the orchestrator returns an `EpisodeResult`. Between those points, each agent receives its own prompt and current view, makes one proposal, and reaches a trusted message or tool boundary. The schedule, rather than a notification service, determines who runs next.

```text
Scenario + model + environment configuration
        │  agent identities, prompts, grants, shared Qwen3 backend
        ▼
EpisodeOrchestrator.run_episode(episode_id, ordered agent schedule)
        │  validate schedule; create one reusable session per agent
        │  initialize context and environment; get episode ToolRegistry
        ▼
For each scheduled agent ID (repeat this block in order)
        │
        ├─ MessageBoard: unread inbox + conversation history for this session
        ├─ ContextManager: retained turns + relevant prior tool outcomes
        ├─ Environment/ObservationBuilder: agent-scoped Observation
        │    Current orchestrator passes visible_environment_state=None
        ├─ AgentRuntime: system prompt + context + Observation + tool schemas
        ├─ Shared Qwen3 backend: generate text for this independent request
        ├─ Action parser and provenance checks: produce/validate one proposal
        │
        ├─ send_message ─► MessageBoard permission check ─► stored sequenced Message
        │                                             (recipient reads when scheduled)
        └─ tool_call ────► ToolDispatcher checks ─► sandbox/browser adapter
                                                   └─ ToolResult held for its agent
        │
        └─ record TurnResult and continue to next scheduled agent
        ▼
Schedule ends (or a turn fails)
        │  attempt environment cleanup; clear episode context
        ▼
Return EpisodeResult in memory
   ordered turns · session snapshots · pending tool results · failure details
```

The same `AgentSession` is used when an agent ID appears more than once in a schedule. The context manager keeps prompt-ready history by episode and agent, while the message board separately stores messages and read cursors. A `ToolResult` is retained for the agent that made the call. These are related pieces of state, but they are not one shared transcript and they do not cause an automatic agent wake-up.

Observation construction also has a specific limit in the current code. The orchestrator passes `visible_environment_state=None`, so the builder puts an empty mapping under `environment` by default. Portal page information is obtained through the browser tools; the trusted `PortalEnvironment.inspect_episode()` path is not automatically copied into the model’s Observation. That distinction keeps the evaluation view separate from the agent-facing page.

If a valid Action is produced, the orchestrator routes it to the message board or tool dispatcher, records its outcome, and proceeds through the schedule. A backend, parser, or validation failure can stop the run with structured phase and agent details. The orchestrator attempts cleanup and returns the turns and final session snapshots in an `EpisodeResult`. That result is useful to the caller, but it is currently an in-memory return value rather than a durable, verifier-backed evaluation record.

## What is still pending

The project has connected execution infrastructure. The following architecture is still needed to turn individual episodes into a repeatable evaluation and research program.

### Pending architecture

#### Evaluation framework

- Task specifications.
- Verifiers.
- Behavioral metrics.
- Failure classification.
- Episode-level evaluation records.
- Result analysis.

#### Evaluation task suite

- Controlled evaluation scenarios.
- Task variations.
- Difficulty levels.
- Adversarial test cases.
- Long-horizon evaluation tasks.

#### Experiment runner

- Experiment configuration.
- Repeated episode execution.
- Result collection.
- Model/configuration comparisons.
- Experiment tracking and aggregation.

#### Research analysis infrastructure

- Baseline comparisons.
- Behavioral analysis.
- Failure investigation.
- Reproducible research experiments.

### Pending real execution validation

These are not missing architecture components. The code paths and interfaces are present to different degrees, but these behaviors still need actual execution evidence from the intended hardware and runtime environments.

- Actual Qwen3 inference on CPU, NVIDIA GPU, and TPU.
- Actual model-driven agent communication.
- Actual Qwen3 browser-tool selection.
- Real Docker sandbox execution.
- Real Playwright/browser interaction with the portal.
- A complete model-driven multi-agent episode.
- Cross-backend numerical and behavioral comparisons.

---

*Technical companion: [`docs/index.html`](index.html) follows the same story with interactive message, context, action, portal, and episode diagrams. The source/API and folder guides are linked from there. The committed source examined for this article is `c6a49f2`; uncommitted Stage 12.1/12.2 changes in the current working tree are intentionally not described as committed functionality.*
