# OptiLab — Harness-Agnostic Agent Onboarding Contract

OptiLab is a zero-LLM deterministic optical bench CAD, differentiable physics digital twin, and live SLM/Camera closed-loop facility.
Humans inspect and co-edit live in the Web UI; external agents operate via the `optilab` CLI (preferred in shell harnesses) or HTTP API (`/api/v1/*`, optional `/api/v1/mcp`).

---

## 1. Idempotent Deploy & Start (Linux / macOS / Windows)

Check prerequisites: Python 3.12+, `uv`, Node.js 22+, `npm`. Run from the repo root.

**First-time install (skip if `.venv` already exists):**
- Linux / macOS:
  ```bash
  uv venv
  uv pip install --torch-backend=cpu -e '.[dev]'   # or --torch-backend=auto for CUDA
  npm --prefix frontend ci
  ```
- Windows PowerShell (use `npm.cmd` if PowerShell blocks `npm.ps1`):
  ```powershell
  uv venv
  uv pip install --torch-backend=cpu -e '.[dev]'
  npm.cmd --prefix frontend ci
  ```

**Start single-port facility (UI + API + WS + `/JOIN.md`) and verify:**
- Linux / macOS:
  ```bash
  .venv/bin/optilab up --build-ui                  # add --cpu for deterministic CPU or --data-dir PATH to isolate
  .venv/bin/optilab doctor
  ```
- Windows PowerShell:
  ```powershell
  .\.venv\Scripts\optilab.exe up --build-ui
  .\.venv\Scripts\optilab.exe doctor
  ```

On success, hand the printed `ui_url` (default `http://127.0.0.1:8000`) to the human immediately.
When using a custom `--port`, set `export OPTILAB_URL=http://127.0.0.1:<PORT>` (or pass `--url` to any command).
To stop later: `optilab down --port <PORT>`. For frontend hot-reload dev mode, see `README.md`.

---

## 2. Progressive Topic Docs (Load Only What You Need)

Offline (embedded in CLI) or over HTTP (`GET /api/v1/docs/<topic>`):
```bash
optilab doc design      # CAD ports, SE(3)/SVD DoF, atomic transaction loop
optilab doc align       # Frozen geometry, error_spec, 4-tier triage, escalation
optilab doc hardware    # Windows/Linux local_driver vs external_stream, hw selftest, worker
optilab doc ir          # Exact `optilab apply` transaction op grammar
optilab doc eval        # Pluggable read-only evaluator toolbox (`eval list/run/selftest/register`)
optilab doc exit-codes  # Semantic CLI exit codes (0/1/2/3/4/5)
```

---

## 3. Core Collaboration Loop (Shared With Human Browser UI)

1. **Observe compact state & drill down losslessly when needed**:
   ```bash
   optilab digest                        # compact stage-aware summary + revision + warnings
   optilab diff --since <REV>            # exact changes made since <REV> (e.g. human UI drags)
   optilab show node <ID>                # lossless raw drill-down (node|constraint|beam|solve|project|hardware)
   ```
2. **Propose, pre-validate (`--dry-run`), and commit atomically**:
   ```bash
   optilab project fork "exp-candidate"  # optional: branch before risky topology changes
   optilab apply --file plan.json --dry-run
   optilab apply --file plan.json --expected-revision <REV>
   ```
3. **Evaluate physics & pluggable checks (metrics to stdout, images/data to files)**:
   ```bash
   optilab sim merit
   optilab sim tolerance --trials 200 --out ./tol.json
   optilab sim camera --engine diffraction --out ./cam.png
   optilab eval list
   optilab eval run bench_integrity --gate
   optilab eval selftest ./my_eval.py && optilab eval register ./my_eval.py
   ```
4. **Escalate physical actions to the human**:
   When `optilab triage` reports `human_must_adjust` or `optilab hw auto-expose` exits `3` (`SaturationError`), raise a UI banner instead of optimizing on clipped/invalid physics:
   ```bash
   optilab escalate raise --title "..." --reason "..." --node <ID> --knob "<physical instruction>"
   ```

---

## 4. Real Lab Hardware Decision Tree (Windows & Linux)

Run `optilab doctor` first to detect installed SDKs (`slmsuite`, `slmsuite_hamamatsu`, `mvsdk`, `cv2`, `pylablib`, `pypylon`) and Windows `SLMdriver` USB volumes, then load `optilab doc hardware`.

- **No hardware / dry testing**: `optilab hw config --mode virtual_rig`
- **Topology A (`local_driver`)**: SDK imports in OptiLab `.venv` (built-in `slmsuite_hamamatsu` / `slmsuite_mindvision`, or a ~25-line `CallableSLMAdapter` / `CallableCameraAdapter` module `my_driver:factory`).
- **Topology B (`external_stream`)**: Vendor SDK requires a separate Windows Python version / 32-bit / Admin process. Set `optilab hw config --mode external_stream`, then run `optilab hw worker --slm mod:slm --camera mod:cam --url http://127.0.0.1:8000` inside the hardware environment.
- **Mandatory Hardware Gate**: Always pass `optilab hw selftest --slm SPEC --camera SPEC [--live-smoke]` before closed-loop calibration.

---

## 5. Non-Negotiable Facility Invariants

1. **Units**: `mm` (lengths/poses), `rad` (`pose.rx/ry/rz`), `deg` (polarization/bend), `nm` (wavelength), `um` (pixel pitch), `mW` (power), `mrad` (tilt errors).
2. **Stage Freeze**: Nominal `pose`, `fixed`, and `constraints` are mutable ONLY in `design`. In `align`/`live`, geometry is frozen (exit `2`); put mechanical offsets strictly in `error_spec`.
3. **Array Orientation**: Hardware `resolution` is `(nx, ny) = (width, height)`; 2D NumPy arrays MUST be row-major `(ny, nx) = (height, width)`.
4. **Radiometric Safety**: Keep `auto_exposure=False` on real cameras; match dark-frame exposure/gain; never optimize on saturated frames (exit `3`) or unsynced external frames (`is_synced_to_slm=false`).
5. **Optimistic Concurrency**: On exit code `5` (`revision_conflict`), run `optilab diff --since <REV>` to absorb human browser edits before retrying.
