Metadata-Version: 2.4
Name: auto-mdp-solver
Version: 0.12.1
Summary: MDP solver pipeline: IR schema + interpreter, conformance harness, eval gates, and Optuna tuning driver for building trained RL policies from formalized decision problems.
Author: Tong Wang
License-Expression: MIT
Project-URL: Repository, https://github.com/tong-wang/auto-mdp-solver
Project-URL: Issues, https://github.com/tong-wang/auto-mdp-solver/issues
Requires-Python: >=3.12
Description-Content-Type: text/markdown
Requires-Dist: numpy<3,>=2.1
Requires-Dist: pydantic<3,>=2
Requires-Dist: gymnasium<1.2,>=1.1
Requires-Dist: optuna<5,>=4.6
Provides-Extra: domain
Requires-Dist: stable-baselines3[extra]<3,>=2.6; extra == "domain"
Requires-Dist: sb3_contrib<3,>=2.6; extra == "domain"
Requires-Dist: pandas<3,>=2.2; extra == "domain"
Requires-Dist: plotly<8,>=5.20; extra == "domain"
Requires-Dist: auto-mdp-solver[dev]; extra == "domain"
Provides-Extra: dev
Requires-Dist: pytest<10,>=8; extra == "dev"

# auto-mdp-solver — the harness

The Python toolchain behind the [auto-mdp-solver](https://github.com/tong-wang/auto-mdp-solver)
Claude Code plugin: a pipeline that turns a verbal dynamic-decision problem
into a trained, deployable RL policy. This package is the executable half —
the IR schema and interpreter, the gates, and the tuning driver. The plugin
(skills, spec, examples) ships separately and installs this package into the
workspace venv on first run.

| package | what it is | entry point |
|---|---|---|
| `mdp_ir` | MDP-IR schema (pydantic), reference interpreter, catalog ⊕ selection layering, execution laws, bit-exact differential runner | `python -m mdp_ir <schema>`, `python -m mdp_ir.laws <dir>`, `python -m mdp_ir.differential <schema>` |
| `mdp_conformance` | spec-conformance checks on a generated domain | `python -m mdp_conformance <dir>` |
| `mdp_gates` | eval-gate comparison of a candidate against baselines under the shared seed protocol | `python -m mdp_gates` |
| `mdp_tuning` | Optuna tuning driver over a domain's training script | `python -m mdp_tuning <dir> ...` |
| `mdp_stage` | the pipeline's entry gates — where a domain folder stands, and whether an op may start | `python -m mdp_stage <dir> [--for <op>]` |
| `mdp_agent` | the headless front door — one unattended run from a job bundle to a packaged policy, under caps, with a manifest, transcript, event log and a scheduler-readable exit code | `mdp-agent check|run|report …` |

## Install

```bash
pip install "auto-mdp-solver[domain]"   # everything a generated domain needs (SB3 + torch + pandas + plotly + pytest)
pip install auto-mdp-solver             # harness only, torch-free: IR, conformance, gates, tuning
pip install "auto-mdp-solver[dev]"      # harness + pytest
# the same, straight from the repo at a release tag (no PyPI needed):
pip install "auto-mdp-solver[domain] @ git+https://github.com/tong-wang/auto-mdp-solver@v0.10.17#subdirectory=harness"
```

Requires Python ≥ 3.12. The version number tracks the plugin release it was
cut from (`v0.10.17` ↔ plugin `0.10.17`), so the skills and the harness a
workspace holds are comparable by one number.

## Agent mode (`mdp-agent`)

The same pipeline with no human in the loop. Phase A — the interview that
produces the signed-off model — is done once, in an agent session, by a
person. Phase B — build, solve, interpret, package — can then be run as many
times as wanted, unattended, under caps, by a scheduler that reads one exit
code. The launcher drives the *unchanged* plugin skills inside a host coding
agent; it adds no solver of its own.

```bash
pip install "auto-mdp-solver[domain]"
mdp-agent check  my_bundle/                 # validate the bundle, show the launch it would make
mdp-agent run    my_bundle/ --out runs/     # one unattended run; the exit code is the outcome
mdp-agent report runs/*/                    # one TSV row per run folder
```

### The bundle

A bundle is a folder holding `job.json` and the domain folder `{name}/` with
the four files Phase B starts from:

| file | where it comes from |
|---|---|
| `{name}_schema.json` | the frozen IR — written by the interview (`mdp-formalize`) |
| `{name}.signoff.json` | its sign-off record, same source |
| `{name}.restatement.md` | the plain-English restatement the sign-off approved |
| `{name}.runplan.draft.json` | the run plan `mdp-solve` would otherwise confirm with you: take an attended run's `{name}.runplan.json`, or write one in that shape, and save it under this name |

The verbal problem statement is deliberately **not** part of the bundle: the
brain works from the frozen IR, as the pipeline does after sign-off. A
bundle holding `{name}/STALL.md` is refused — that file is a stalled run's
question, not an input.

`job.json` names the domain, the caps and the brain:

```json
{
  "name": "secretary",
  "variant": "frozen",
  "caps": {
    "walltime": "6h",
    "compute_preapproved": "90m",
    "escalation_rounds": 1,
    "cores": 4,
    "tokens": 3000000,
    "cache_read_tokens": 300000000,
    "max_turns": 3000,
    "budget_usd": 25
  },
  "brain": {
    "host": "claude",
    "model": "claude-opus-5-5",
    "effort": "high",
    "plugin_dir": "/opt/auto-mdp-solver/plugin"
  }
}
```

`caps` are the answers to every question the skills would have asked a
person, plus the hard stops:

| cap | meaning | enforced by |
|---|---|---|
| `walltime` (required) | wall-clock limit for the whole run; the process group is terminated at the limit | launcher, every host |
| `compute_preapproved` | the training launch length approved in advance — the skills' ">30 minutes?" question, answered | the brain, by the prompt |
| `escalation_rounds` | how many L2+ rounds the run plan may open | the brain, by the prompt |
| `cores` | cores available to training, stated to the brain | the brain, by the prompt |
| `tokens` | fresh tokens (input + output + cache writes) the brain may consume | launcher, every host |
| `cache_read_tokens` | cached context re-read across the run — its own cap, since it is the larger number | launcher, every host |
| `max_turns`, `budget_usd` | the host's own turn and dollar limits | Claude Code only; recorded unenforced on Codex |

`brain` picks the host and the model. `host` is `claude` (Claude Code in
print mode), `codex` (Codex CLI in exec mode) or `command` (any program that
emits one of the two stream shapes — the test double). `model` and `effort`
are required: a host's headless default can sit below the plugin's tested
floor (Opus 5 or above; GPT-5.6 at medium or higher), and the manifest must
say what ran. `plugin_dir` is the plugin checkout the skills load from; its
version must equal the installed harness version. Optional: `rates` (USD per
million tokens for input / output / cache_read / cache_create, for a cost
figure when the host reports none), `tools_denied` (the network-fetching
commands, denied on Claude Code by default; recorded, not enforced, on
Codex), `env` and `extra_args` passed to the host.

**Authentication is the operator's own.** On Claude Code the run uses the
login of whoever launches it. On Codex the launcher creates a fresh
`CODEX_HOME` inside the run folder and logs the key from `OPENAI_API_KEY`
(or a file named by `OPENAI_API_KEY_FILE`) into it, then deletes the stored
key when the run ends; setting `brain.env.CODEX_HOME` instead points Codex
at a home with its own login (a ChatGPT account, say — note that a plan
account rejects API-only models and brings its managed requirements along).

### What a run produces

`mdp-agent run` copies the domain folder into a fresh run folder
`{name}-{timestamp}/`, writes the manifest *before* the brain starts,
launches the host under the caps, and exits with:

| code | status | meaning |
|---|---|---|
| 0 | `complete` | the package gate passes and `{name}/{name}_policy.py` exists |
| 2 | `bundle` | the bundle or the host fails validation (nothing was launched) |
| 3 | `stall` | the brain needed a human answer — `stall.json` holds the question |
| 4 | `cap` | walltime, tokens, turns or budget stopped it |
| 5 | `brain` | the host program failed |
| 6 | `incomplete` | the brain ended cleanly without completing |

The run folder holds `manifest.json` (the launch, the caps, what the host
reports it actually ran, warnings, tokens, cost and the final report),
`prompt.md` (the brain's one instruction), `transcript.jsonl` (the host's
raw stream), `events.jsonl` (the same, normalized so rows from either host
compare), `progress.json` (rewritten at every gate and every 15 s — what a
person watching a queue reads), `brain.stderr`, `gate_final.txt`,
`report.tsv`, and the domain folder with everything the brain built —
`results/`, the leaderboard, the readback, the policy wrapper. Each tool
call in the event log is tagged with the pipeline stage it fell in, so a
web call during `mdp-solve` or later is counted as a protocol violation
(`web_in_solve`), while one during `mdp-build` — a benchmark's source, a
published heuristic — is allowed and logged. A shell command counts as a
network call by what it runs (`curl`, `wget`, `ssh`, a `git` transfer, a
package installer's fetch), never by a URL in the text it writes. Token
totals come from the host's own result events, summed over every turn the
run had, with the launcher's per-call sum beside them as the cross-check.

### What the host must provide

`mdp-agent check` tests the first five and reports the sixth; the rest a
person arranges.

- Python 3.12 or newer with `auto-mdp-solver[domain]` installed — or pass
  `--python`, or set `$MDP_SOLVER_PYTHON`; the brain is told to use that
  interpreter and to install nothing.
- The installed harness version equal to the plugin's version at
  `brain.plugin_dir`.
- The host CLI on `PATH`: `claude` or `codex`.
- `brain.model` and `brain.effort` stated.
- For Codex, a key in the environment or an operator home in `brain.env`.
- A non-root user: Claude Code refuses to bypass permissions as root, and an
  unattended run needs that bypass.
- Network to the model API, and nothing else is needed: the pipeline's
  packages are installed ahead of time.
- **A container.** The launcher bypasses the host's permission prompts,
  because nobody is there to answer them, so the container the run sits in
  is its sandbox — one bundle, one operator, one credential, built from
  the reference image in the repository's `env/` folder. A run outside one
  is the bundle author's own-machine case and nothing else: the bundle's
  files reach the model's context, and a crafted bundle could direct the
  brain to misuse the key the run was given. The launcher detects where it
  runs; outside a container, `check` prints a caution, every manifest
  records it under `containerized`, and the report carries the column, so
  an evidence row shows where it was made.
- Cores and memory for the training the run plan asks for; `caps.cores`
  tells the brain what it has.

Verified hosts, as of this version: Claude Code 2.1.319 and codex-cli
0.167.0, in a `python:3.12-slim` container with Node, CPU-only torch and the
plugin checkout, under a batch scheduler — the image recipe and a
one-command run script are in the repository's
[`env/`](https://github.com/tong-wang/auto-mdp-solver/tree/main/env) folder. The Claude route has run blind end to end (two complete campaigns,
one capped); the Codex route has run end to end through an operator home,
and its API-key login is verified to authenticate.

### The cost of carried context

Everything the brain has read is re-read on every call: a complete campaign
re-reads 20–30 M cached tokens over 90–130 calls, about a quarter million
per call, on either host. Two optional knobs under `job.context` are
recorded in the manifest and the report so runs with and without compare:
`"lean_reading": true` adds a reading-discipline rule to the prompt (only
the slices the current step names), and `"autocompact_tokens": N` passes
the host's auto-compaction window (`--autocompact` on Claude Code,
`model_auto_compact_token_limit` on Codex) — a window the host compacts
within at its own moments, not a compaction at the stage seams. The
report's `cache_read_max / mean / slope` columns are how their effect is
read; Codex reports usage once per turn, so its slope is empty.

A four-run A/B on one bundle settled what the knobs do. `lean_reading`
moved the build-phase ramp by about 2 %: the brain was already reading only
what it needed, and the ramp is the conversation itself. `autocompact_tokens`
at a window below the run's natural peak cut cache reads by a third and cost
more anyway: after each compaction the brain re-read its files (cache writes
up by two thirds), re-issued launch commands, ended turns to wait, and
delivered less — one training seed instead of three, a smaller evaluation,
and no campaign log; the manifest lists each boundary under `compactions`.
The context is the brain's working memory, and the lever that paid was the
training instruction below: 37 % fewer cache reads, 23 % less cost, 25 %
less wall, the same leaderboard to the digit. What the earlier runs paid for
was waiting.
A brain that ends its turn to wait for a training job is re-woken by every
job notification, and each wake re-reads the whole conversation; a run
launched under a host's default time limit is killed, never scored, and
launched again. The prompt therefore names the mechanism and the limit
for its host — on Claude Code, `run_in_background` with an explicit
`timeout` of at least the pre-approved compute; on Codex, a foreground
command or a detached `nohup setsid` job — and tells the brain to wait
inside the turn with long blocking checks. Both failure modes are counted:
`turn_ends` (the host's result events, one per wake) and `relaunches`
(training commands run again with the same arguments) are in the manifest
and the report, beside `effort_reported` — from the host's own record where
it keeps one (Codex's rollout), else `not reported by host` (Claude Code's
stream carries no effort field).

Documentation, the per-domain spec, the frozen example domains and the test
cases live in the repository. MIT license.
