# Architecture

One crate, `aas-rs`, containing a library and a CLI binary. The optional
`rig` feature adds the Rig-based LLM agent. A workspace split has not been
needed: the modules are small and share types.

```mermaid
flowchart TB
    subgraph Rust["aas-rs (Rust)"]
        CLI["main.rs<br/>inspect / run / official / report"]
        DS["dataset.rs<br/>tasks.jsonl, pair validation"]
        AG["agent.rs<br/>Agent trait, ToolBox"]
        RIG["rig_agent.rs (feature rig)<br/>LLM tool loop"]
        POL["policy.rs<br/>baselines"]
        RUN["runner.rs<br/>lifecycle, limits, concurrency"]
        ENV["env.rs<br/>rmcp client, child process"]
        SC["scoring.rs<br/>commit_check, run errors, outcome"]
        AGG["aggregate.rs<br/>slices, CAR, macro"]
        OFF["official.rs<br/>eval.json, judge, combined"]
        REP["report.rs"]
    end
    subgraph Py["Upstream AgentAbstain (Python, unmodified)"]
        SRV["src/runtime/task_mcp_server.py<br/>MultiEnvironment + export tool"]
        EVR["eval/runner.py<br/>commit_check + LLM judge"]
    end
    LLM[("LLM endpoint<br/>OpenAI-compatible")]
    JUDGE[("Judge model<br/>OpenAI")]

    CLI --> RUN
    RIG --> AG
    POL --> AG
    RUN --> AG --> ENV
    ENV <-->|MCP stdio| SRV
    RIG <-->|HTTPS| LLM
    RUN --> SC --> AGG --> REP
    RUN -->|run_result.json| EVR
    EVR <-->|HTTPS| JUDGE
    EVR -->|eval.json| OFF --> AGG
    DS --> RUN
```

## Components

| module | responsibility |
|---|---|
| `dataset` | parse `tasks.jsonl`; validate pair invariants; DAG topological order |
| `env` | spawn the official server with a cleared environment; MCP handshake; list/call tools; export snapshot; shutdown; capture stderr |
| `agent` | `Agent` trait; `ToolBox` records every call (`Response`, `Failed`, `Rejected`), enforces the call budget, hides and refuses the export tool |
| `rig_agent` | LLM agent: Rig completion model + tool loop; tool-name encoding; config from `AAS_LLM_*` |
| `policy` | baselines: always-abstain, replay act DAG, seeded random |
| `runner` | per-task lifecycle; failure staging; bounded concurrency; official results writer |
| `scoring` | official commit check; run-error classification; diagnostic outcome |
| `aggregate` | official slice, category and macro aggregation |
| `official` | read official `eval.json`; latest-run selection; judge and `combined` metrics; optional evaluator subprocess |
| `report` | counts, JSON report, text rendering |

## Python boundary

Python owns environment semantics, which is the core of the benchmark:
- state;
- the 541 tool implementations;
- injected failures (`broken_tools`) and hidden tools (`available_tools`);
- the execution log.

Python also owns the official LLM judge. AAS-RS reimplements neither.
Reimplementing them would fork the benchmark.

Rust owns everything a Rust agent author programs against:
- the agent interface and the tool-calling loop;
- transport, process lifecycle, limits and observation;
- deterministic scoring, aggregation and reports;
- CI integration.

The environment server is started exactly as the official harnesses start it
(`src/runtime/common.py::build_runtime_server_args`): upstream repo as working
directory, `AGENTABSTAIN_DATA` pointing at the dataset.

## Task lifecycle

1. Spawn `python -m src.runtime.task_mcp_server --category C --task-id T --task-type act|abstain`. The environment is cleared; stderr is drained into an 8 KiB ring buffer.
2. MCP `initialize` (observed protocol `2025-11-25`), within the startup timeout.
3. `tools/list`; the `__runtime_export_snapshot` tool is removed from what the agent sees.
4. Export the initial snapshot.
5. Run the agent under the task wall-clock timeout. Every `ToolBox::call` is a `tools/call` with the per-call timeout and counts against `--max-tool-calls`.
6. Export the final snapshot. This also happens after an agent error, as upstream does.
7. Cancel the MCP service and shut the child down. `kill_on_drop` covers cancellation and panics.
8. Score with the commit check on the **environment's** execution log. Compute diagnostics.

## Rig agent loop

```
history = [user: instruction]
repeat up to AAS_LLM_MAX_TURNS:
    response = model(system = task system prompt, history, tools = environment tools)
    if no tool calls: return response text as the final answer
    for each tool call:
        known tool and JSON-object arguments -> ToolBox::call -> result text (error flag kept)
        otherwise -> ToolBox::reject (recorded, budgeted) -> error result to the model
    append assistant turn and tool results
max turns exceeded -> run error "max turns (N) exceeded" (excluded from scoring, as upstream)
```

Tool names `<env>.<tool>` are encoded as `<env>__<tool>`, the same rule as the
official OpenAI harness. Names longer than 64 characters get a stable hash
suffix. Collisions are an error.

## Event capture

Each task keeps three records:
- `tool_events` is client-side. It holds every call the agent made or tried,
  including rejected ones and calls that never got a result.
- `execution_log` is environment-side. Scoring uses only this one.
- `trace_consistent` compares the multisets of successful tool names in the
  two. A mismatch points to a bug in the client or the environment.

## Error handling

- Library errors use `thiserror` enums: `DatasetError`, `EnvError`,
  `ToolCallError`, `OfficialError`, `RigConfigError`. Agent errors are boxed
  `dyn Error`.
- Every task produces a `TaskResult`. Failures are data, with
  `failure.stage ∈ {environment, agent, agent_timeout}`, never panics.
- Environment failures are excluded from scores, counted separately, and make
  the CLI exit with status 3.

## Security boundaries

See [SECURITY.md](SECURITY.md). In short:
- secrets are not inherited by environment processes;
- the LLM key goes only to the configured endpoint;
- judge credentials go only to the evaluator subprocess;
- there is no OS sandbox.
