# Architecture decisions and evidence

**Baseline:** committed `HEAD` `c6a49f2e794977fdb45347528c4e6384def0bdb4` (2026-12-02). Commit subjects and diffs show changes, but usually do not record why a choice was made. Each record distinguishes a fact visible in source from an engineering interpretation. “Unknown” means the history does not preserve the original motivation.

## ADR-01 · Keep provider-neutral core contracts

- **Problem:** Agent, environment, and action data must be exchanged without binding every layer to Qwen or a hosting API.
- **Chosen approach:** `core/types.py` defines IDs, immutable `AgentSpec`, `Message`, `Observation`, `Action`, and mutable `AgentSession`; `models/adapters.py` independently defines `ModelRequest`, `ModelResponse`, and `ModelBackend`.
- **How it works:** the runtime accepts the backend protocol and core records; serialization methods produce JSON-compatible dictionaries.
- **Historical evidence:** commits `5f0702d` and `c6a49f2` added/extended this boundary. The specific original rationale is not in those commit subjects.
- **Engineering reasoning:** narrow records make validation and fake-backend tests possible without a second provider dependency.
- **Alternatives / tradeoffs:** one framework model type would reduce adapters but couple providers; the present structures require explicit conversion and validation.
- **Consequences:** contracts define provenance and visible information, but not executing systems or authoritative state transitions.
- **Status:** implemented; unit/component coverage exists.
- **Sources:** [`core/types.py`](../core/types.py), [`models/adapters.py`](../models/adapters.py), [`agents/runtime.py`](../agents/runtime.py).

## ADR-02 · Separate agent definition from per-episode session

- **Problem:** The same named agent needs stable instructions and permissions while its turn count and unread-message cursor change per episode.
- **Chosen approach:** frozen `AgentSpec` plus mutable `AgentSession(agent_id, episode_id, ...)`.
- **Evidence in source:** orchestrator creates one session per registered agent at episode initialization and reuses the same object at repeated schedule entries.
- **Historical rationale:** not recorded explicitly.
- **Engineering reasoning:** this avoids mutating scenario identity and prevents different episodes from sharing cursor/lifecycle state.
- **Tradeoff:** session serialization does not preserve application conversation history; that is owned by `AgentContextManager` and `MessageBoard`.
- **Status:** implemented and covered by orchestrator/context tests.
- **Sources:** [`core/types.py`](../core/types.py), [`agents/orchestrator.py`](../agents/orchestrator.py).

## ADR-03 · Put information on an explicit Observation

- **Problem:** An agent should receive only the information selected for its decision.
- **Chosen approach:** `Observation` is immutable, agent/episode/step tagged, and includes visible state and recipient-validated messages.
- **Evidence in source:** `ObservationBuilder` composes caller-supplied state, unread messages and only tool results allowed by the agent specification.
- **Rationale:** explicit input makes isolation and action provenance inspectable; the historical reason was not recorded.
- **Tradeoff:** correctness depends on environment/orchestrator callers providing the right state; the contract cannot discover whether omitted information should exist.
- **Status:** implemented; observation isolation tests exist.
- **Sources:** [`core/types.py`](../core/types.py), [`environments/observation.py`](../environments/observation.py).

## ADR-04 · Treat Action as a proposal, not a state change

- **Problem:** Model text must not directly mutate environment state.
- **Chosen approach:** parse a strict JSON action (`send_message` or `tool_call`), attach the source observation identity, validate it, then dispatch in trusted orchestrator code.
- **Evidence:** `AgentRuntime` returns an `Action`; only `EpisodeOrchestrator` calls the board or `ToolDispatcher`.
- **Rationale:** separating proposal, authorization, and execution gives each boundary a validation point; no explicit historical rationale found.
- **Tradeoff:** structured outputs can be rejected rather than repaired; unsupported action types stop the episode.
- **Status:** implemented; fake-backend tests validate parser and dispatch behavior.
- **Sources:** [`agents/action_parser.py`](../agents/action_parser.py), [`agents/runtime.py`](../agents/runtime.py), [`agents/orchestrator.py`](../agents/orchestrator.py).

## ADR-05 · Keep scenario and prompt content in data files

- **Problem:** Agent instructions and communication/tool declarations need to be editable independently of execution code.
- **Chosen approach:** one scenario JSON references prompt files; `AgentRegistry.from_scenario()` loads both into `AgentSpec` records.
- **Evidence:** prompt path resolution is scenario-relative and constrained beneath the scenario folder.
- **Rationale:** one canonical roster avoids duplicating identities in code; original motivation is not documented.
- **Tradeoff:** scenario JSON and prompt files must stay consistent; the registry validates shape and condition names but does not semantically review prompt prose.
- **Status:** implemented; scenario/prompt loading tests exist.
- **Sources:** [`tasks/scenarios/kashmir/scenario.json`](../tasks/scenarios/kashmir/scenario.json), [`agents/registry.py`](../agents/registry.py), [`agents/prompt_loader.py`](../agents/prompt_loader.py).

## ADR-06 · Make communication directional and condition-aware

- **Problem:** Different agents have intentionally different communication reach, including a conditional Ubaid→Sahil route.
- **Chosen approach:** immutable `CommunicationPermissions` and `ConditionalCommunicationRule` on each spec; board asks for trusted condition values at send time.
- **Evidence:** the board resolves recipient permission, refuses unknown IDs and fails conditional checks closed when conditions are absent/false.
- **Rationale:** permissions travel with the sender identity and can be inspected; historical reason not recorded.
- **Tradeoff:** scenario truth is supplied by a trusted provider. The repository does not implement an automatic semantic detector for “technical demonstration requested.”
- **Status:** implemented and tested for configured directions and fail-closed conditional behavior.
- **Sources:** [`core/types.py`](../core/types.py), [`agents/message_board.py`](../agents/message_board.py), [`agents/orchestrator.py`](../agents/orchestrator.py).

## ADR-07 · Use ordered message cursors rather than wake-ups

- **Problem:** An agent needs to retrieve only new messages and know when those messages have been consumed.
- **Chosen approach:** in-memory episode message lists with per-episode sequence order and a cursor on `AgentSession`.
- **Evidence:** orchestrator polls unread messages when an agent is scheduled and only marks them consumed after runtime/action validation succeeds.
- **Rationale:** simple synchronous semantics fit the finite schedule. Historical record explicitly separates notifications as deferred in user instruction; no push service exists.
- **Tradeoff:** no persistence, background workers, or automatic wake-up; board state is process memory.
- **Status:** implemented; message ordering and cursor tests exist.
- **Sources:** [`agents/message_board.py`](../agents/message_board.py), [`core/types.py`](../core/types.py).

## ADR-08 · Separate MessageBoard records from persistent prompt context

- **Problem:** A consumed inbox should not erase information needed in a later model request.
- **Chosen approach:** MessageBoard owns ordered communication records; `AgentContextManager` stores per-(episode, agent) conversation and turn context for prompt construction.
- **Evidence:** runtime receives optional context as a serialized request field, and context is cleared at episode end.
- **Rationale:** message delivery and model history have different lifetimes and filtering rules; original rationale is not documented.
- **Tradeoff:** context is in-memory and bounded, not a durable event store.
- **Status:** implemented; cross-turn tests cover retention and isolation.
- **Sources:** [`agents/context_manager.py`](../agents/context_manager.py), [`agents/orchestrator.py`](../agents/orchestrator.py).

## ADR-09 · Use explicit bounded context with visible expiry

- **Problem:** Long episodes and large tool outputs can exceed useful prompt size.
- **Chosen approach:** keep recent turn details, cap tool-result details/output size, mark expired outputs, and raise `ContextLimitError` instead of silently truncating required context.
- **Evidence:** defaults are 20 retained turns, 10 detailed tool results, 8,000 output characters, and a 100,000-character serialized context budget.
- **Rationale:** explicit expiration is easier to audit than invisible truncation; this is engineering reasoning, not proven historical intent.
- **Tradeoff:** a large required message history may stop the turn rather than be summarized or dropped.
- **Status:** implemented; budget, expiry, deduplication and episode cleanup tests exist.
- **Sources:** [`agents/context_manager.py`](../agents/context_manager.py), [`tests/test_context_manager.py`](../tests/test_context_manager.py).

## ADR-10 · Share model weights but create request-local generation state

- **Problem:** Ten agents need distinct prompts and histories without loading ten copies of Qwen3.
- **Chosen approach:** cached singleton `Qwen3Backend` with independent fully rendered `ModelRequest`s. The generation loop allocates a KV cache for each generation request.
- **Evidence:** `load_shared_backend()` uses `lru_cache(maxsize=1)`; per-agent context is passed separately by runtime; generation code instantiates/uses request-local cache state.
- **Rationale:** weight sharing reduces duplicate model memory while preserving independent application context. Historical motivation is not stated in the commit message.
- **Tradeoff:** one backend configuration per process; model cache is not conversation memory and is not shared across agents.
- **Status:** implemented in committed source; true model inference is asset/device-dependent. Part 1 still calls out reference parity and cache benchmark work as open.
- **Sources:** [`models/qwen3_backend.py`](../models/qwen3_backend.py), [`agents/runtime.py`](../agents/runtime.py), [`models/text_generation.py`](../models/text_generation.py).

## ADR-11 · Keep model protocol small and provider-neutral

- **Problem:** Agent code should request generation without depending on model loader details.
- **Chosen approach:** `ModelBackend.generate(ModelRequest) -> ModelResponse` protocol, with Qwen3 as the implementation and fake backends in tests.
- **Evidence:** runtime accepts an injected backend and validates `generate` callable.
- **Rationale:** it enables deterministic tests and replacement through adapters without introducing multi-model orchestration. This is inferred from code.
- **Tradeoff:** advanced sampling/streaming features are not in the generic request contract; the Qwen backend currently reports greedy decoding.
- **Status:** implemented; model-specific hardware verification remains separate.
- **Sources:** [`models/adapters.py`](../models/adapters.py), [`models/qwen3_backend.py`](../models/qwen3_backend.py), [`tests/test_agent_runtime.py`](../tests/test_agent_runtime.py).

## ADR-12 · Bind tool exposure and execution authorization to AgentSpec

- **Problem:** The model should see and execute only tools granted to its trusted agent identity.
- **Chosen approach:** `ToolRegistry.specs_for(agent)` filters visible schemas; `ToolDispatcher.dispatch(agent, action)` independently checks authorization, action identity, schema and registry.
- **Evidence:** tools are episode-scoped in the portal/sandbox and dispatcher receives the registry AgentSpec from trusted orchestration.
- **Rationale:** checking twice at prompt exposure and execution limits the effect of model output spoofing; historical reason not recorded.
- **Tradeoff:** tool permissions must match actual episode registry names or dispatch is rejected.
- **Status:** implemented; permission/identity tests exist.
- **Sources:** [`tools/registry.py`](../tools/registry.py), [`tools/dispatcher.py`](../tools/dispatcher.py), [`tools/contracts.py`](../tools/contracts.py).

## ADR-13 · Place Docker behind a narrow Sandbox protocol

- **Problem:** Agent filesystem and command tools should not directly call host APIs.
- **Chosen approach:** tool adapters depend on `Sandbox` operations; `DockerSandbox` implements them within an episode container and managed workspace.
- **Evidence:** path validation and bounded runner live inside the image; Docker calls use argument arrays, while tests stub the adapter's subprocess calls.
- **Rationale:** a protocol allows test doubles and isolates backend details; precise historical reasoning is unavailable.
- **Tradeoff:** real protection depends on Docker host/image configuration and opt-in live tests. Stubbed unit tests cannot prove container isolation.
- **Status:** source/configuration implemented; live Docker execution must be verified on a prepared host.
- **Sources:** [`tools/sandbox.py`](../tools/sandbox.py), [`environments/docker_sandbox.py`](../environments/docker_sandbox.py), [`environments/sandbox_image/`](../environments/sandbox_image/).

## ADR-14 · Model browser use as tools against an episode-local portal

- **Problem:** Exercise browser actions without using real services or allowing general outbound browsing.
- **Chosen approach:** a synthetic web application, mock bank, browser-control service, and browser sandbox are joined on an episode-internal network; browser tools target the portal origin.
- **Evidence:** portal environment creates per-episode network/containers and app/ledger state, and config provides synthetic scheme/account fixtures.
- **Rationale:** deterministic, isolated simulation reduces external variables; this is inferred engineering rationale.
- **Tradeoff:** simulation results do not establish behavior against external websites. Real Docker/Chromium tests are opt-in.
- **Status:** implemented; deterministic in-process flow tests exist; actual isolated Docker/Playwright run is not assumed.
- **Sources:** [`environments/portal_environment.py`](../environments/portal_environment.py), [`environments/fake_website/`](../environments/fake_website/), [`environments/browser_sandbox_image/`](../environments/browser_sandbox_image/).

## ADR-15 · Centralize the finite episode loop in EpisodeOrchestrator

- **Problem:** State, message delivery, context, model calls, dispatch, errors and cleanup must advance in a predictable order.
- **Chosen approach:** caller supplies a finite schedule; one synchronous orchestrator owns the loop and returns ordered `TurnResult`s and an `EpisodeResult`.
- **Evidence:** `run_episode` validates the schedule, creates sessions, checks observation/action identity, dispatches and cleans up.
- **Rationale:** sequential ownership makes state transitions and failure points inspectable. The exact original motivation is not recorded.
- **Tradeoff:** no async scheduling, parallel agents, retry policy, or notification delivery.
- **Status:** implemented and tested, including failure/cleanup cases.
- **Sources:** [`agents/orchestrator.py`](../agents/orchestrator.py), [`tests/test_orchestrator.py`](../tests/test_orchestrator.py).

## ADR-16 · Test with injected backends and simulated adapters

- **Problem:** Exercise orchestration and application logic without requiring model inference or a live Docker host in every unit test.
- **Chosen approach:** fake `ModelBackend`s, Docker subprocess stubs, and deterministic synthetic portal workflow fixtures.
- **Evidence:** `tests/test_episode_integration.py` labels its backend scripted and uses an in-process browser/sandbox; opt-in tests are separately marked by environment variables.
- **Rationale:** component tests stay repeatable and isolate failures; this is an engineering explanation supported by test design, not historical intent.
- **Tradeoff:** these tests prove wiring and state behavior under controlled responses, not model capability, Docker security, or hardware support.
- **Status:** test infrastructure exists. Documentation task did not execute the suite.
- **Sources:** [`tests/test_episode_integration.py`](../tests/test_episode_integration.py), [`tests/test_portal_workflow.py`](../tests/test_portal_workflow.py), [`tests/test_docker_sandbox.py`](../tests/test_docker_sandbox.py).

## ADR-17 · Separate scaffolding from a complete training/evaluation system

- **Problem:** Research modules may exist before an end-to-end learner, evaluator, or experiment runner is connected.
- **Chosen approach:** keep `rollouts/`, `rewards/`, `algorithms/`, `distributed/`, and `evaluation/` as distinct packages, but current root README and source indicate partial/scaffold status.
- **Evidence:** `core/trajectory.py` is currently a docstring-only module; `checkpointing/` and `experiments/` have no tracked implementation files. Evaluation package has helper modules but no complete task-verifier runner in this commit.
- **Rationale:** separation creates future extension points; no claim of completed RL training follows from folder names.
- **Tradeoff:** package layout can look more complete than its wired functionality; documentation must state this plainly.
- **Status:** partial infrastructure only.
- **Sources:** [`README.md`](../README.md), [`rollouts/`](../rollouts/), [`evaluation/`](../evaluation/), [`core/trajectory.py`](../core/trajectory.py).

## What Git history can and cannot tell us

The readable history has two recent feature commits relevant to this narrative: `5f0702d Add agent orchestration and Qwen3 backend` introduced contracts, scenario registry, prompt files, communication, and backend; `c6a49f2 Add agent orchestration and sandbox environments` added runtime/context/orchestration and the sandbox/browser/portal integration. Earlier history includes the KV-cache work (`1192cdf`, `bf219f4`). The subjects and diffs establish sequence and changed code. They do not establish every design discussion or the exact reason alternatives were rejected. Where a reason above is not in a source comment or clear history, it is labeled engineering reasoning rather than historical fact.

## Worktree-only changes

At review time, the current checkout has modifications to `README.md`, `agents/runtime.py`, `models/kv_cache.py`, `models/policy.py`, `models/qwen3_backend.py`, `models/text_generation.py`, `pyproject.toml`, `requirements.txt`, `tests/test_agent_runtime.py`, and `uv.lock`, plus untracked `evaluation/run_stage12_1_validation.py`, `models/device.py`, `tests/test_device.py`, and `tests/test_stage12_1_diagnostic.py`. These files are not part of `c6a49f2`; they are intentionally not presented above as committed Stage 12.1/12.2 features. The documentation-only change must preserve these files as-is.

## Evolution timeline

| Commit | Source-supported change | What it enabled |
|---|---|---|
| `1192cdf` / `bf219f4` | KV cache implementation and cached text generation | Incremental decoding could reuse K/V instead of recomputing the entire prompt at every token. |
| `c672433` | Restructure project into packages such as `core/`, `agents/`, `models/`, environments and research areas | Clearer package ownership; some later packages remain scaffolding. |
| `2fa2f4d` | README project status and package map | Publicly distinguishes model implementation from incomplete RL loop. |
| `5f0702d` | Core contracts, scenario/prompt registry, message board, Qwen backend/adapters | An agent identity and a communication/model-request boundary became representable. |
| `c6a49f2` | Runtime/action parser/context, orchestrator, sandbox and browser/portal environments, deterministic integration tests | Agent proposals could be routed through permissions and an episode-local simulated environment. |

This is a code-change timeline, not a reconstruction of undocumented private design discussions.
