# World API / v0.1 — the behaviour surface of a World-Sim instance

This is the reference for **what your code can do inside a World-Sim world**: the `w` object a
behaviour receives, the names in scope, the per-template differences, and the counterfactual oracle
that scores it. The product guide is `specs/world-sim/v0.1` (buying, endpoints, credentials,
templates). This spec is the engine contract underneath it.

The simulator engine itself is private. Everything listed here is **supported surface**: it is kept
stable within `v0.x` (additions only). Anything else you can reach on `w` is internal state — it
works today, but it can change or disappear without a version bump, and the oracle will not treat
your reliance on it as a contract.

---

## 1. Where your code runs

A **behaviour** is Python source that defines one function:

```python
def run(w, params):
    ...
```

You submit it in two places, and it runs the same way in both:

| Where | How |
|---|---|
| The counterfactual oracle | `POST {eval_oracle}/counterfactual` with `"behavior": "<source>"` (§5). Runs in a forked copy of your world; the live world is untouched. |
| A custom segment in the model editor | Adds the behaviour to your live world. Changes hot-apply, no restart. |

**Execution model.**

- `run(w, params)` is called **once per simulated day**, as the last step of that day, after the
  simulated staff have done the day's baseline work. `w.day` is still the day that just ran.
- `params` is the dict you sent with the behaviour (default `{}`). Treat it as read-only
  configuration; keep state in the world instead (`w.after`/`w.due`, or records you created).
- The source is compiled once. A syntax error, or source that defines no callable `run`, is a
  **compile error**: the oracle answers `400 {"error": "behavior failed to compile", "detail": …}`.
- An exception inside `run` is caught and recorded as the **run error** (type and message, at most
  200 characters). The world keeps ticking. A day that runs cleanly clears it, so the oracle's
  `behavior_run_error` shows only the **last** day's error — test on a day that has matching records.

**Names in scope.** Only these are visible to `run` without an import:

- `timedelta`, `date` (from `datetime`) and the `random` module;
- the template's **master data** (§4), for example `PRODUCTS`, `CUSTOMERS`, `PRICE`;
- the Python builtins.

**Put imports inside `run`.** Module-level names in your source are not visible to `run`
(`import re` at the top → `NameError` at run time). This is the most common first failure.

**Use `w.rng`, not `random`.** The oracle compares two forks of the same world. `w.rng` is the world's
own seeded generator, so both forks draw the same sequence until your behaviour changes something.
Drawing from `random` makes the comparison noisy.

## 2. The core surface (every template)

| On `w` | Type / signature | What it does |
|---|---|---|
| `w.day` | `date` | The simulated date that just ran. |
| `w._d()` | `→ str` | `w.day` as an ISO string (`"2026-02-03"`). Record dates use this format, so compare with it. |
| `w.rng` | `random.Random` | The world's seeded generator (see above). |
| `w.kpis(n=30)` | `→ dict` | The trailing-`n`-day KPI dict. Keys are the template's KPIs (§4) plus `sim_day`, `window_days`, `open_orders`, `on_time_ship_pct` and `automations_on`. A rate can be `None` when its window has no data. |
| `w.so`, `w.po`, `w.invoices`, `w.shipments`, `w.emails` | `list[dict]` | The silos' records: sales orders, purchase orders, customer invoices, shipments, mail. Read them freely. Create records only through the calls in this table. |
| `w._email(frm, to, subject, body, thread)` | `→ str` (message id) | Sends a mail into the mailbox silo, dated today. `thread` groups a conversation. |
| `w.after(days, tag, payload=None)` | `→ None` | Schedules `payload` (a dict) to become due under `tag` after `days` simulated days. This is the human-loop timer: send a mail now, act when the reply would have come. |
| `w.due(tag=None)` | `→ list[dict]` | **Pops** and returns the payloads whose wait has elapsed, optionally only those under `tag`. Call it every day: a payload that is not popped stays due. |
| `w.create_purchase_order(…)` | `→ dict` (the PO) | Keys a purchase order into the ERP. The arguments differ per template (§4). |

Example — a human-in-the-loop follow-up that works on every template:

```python
def run(w, params):
    # Every Tuesday, ask ops a question; 2-4 days later the answer "arrives" and we log it.
    tag = "weekly-check"
    if w.day.weekday() == 1:
        w.after(w.rng.randint(2, 4), tag, {"asked": w._d()})
    for p in w.due(tag):
        w._email("ops@example.com", "ops@example.com", "weekly check done",
                 "asked " + p["asked"] + ", answered " + w._d(), tag)
```

Example — an observational digest (changes nothing, so its oracle `delta` should be all zeros, which
is a quick check that the oracle is paired):

```python
def run(w, params):
    if w.day.weekday() == 0:
        k = w.kpis(7)
        w._email("controlling@example.com", "management@example.com", "Weekly KPIs " + w._d(),
                 f"on-time {k['on_time_ship_pct']}%, open orders {k['open_orders']}", "weekly-kpi")
```

## 3. Surface that only some templates have

| On `w` | Templates | What it does |
|---|---|---|
| `w._wms(kind, item, qty, ref)` | all except `almtal` (`textilwerk` adds a trailing `uom="m"`) | Records a warehouse transaction. |
| `w.wms_txns` | all | Warehouse transactions (`list[dict]`). |
| `w.wo` | `rheinpump`, `eichhof`, `nordbrot`, `roestwerk`, `spritzwerk`, `textilwerk` | Work orders / production batches. |
| `w.mes` | `rheinpump`, `farbwerk`, `nordbrot`, `roestwerk`, `spritzwerk` | Shop-floor execution records. |
| `w.pending_entries` | `rheinpump`, `nordbrot`, `roestwerk`, `spritzwerk` | Order requests waiting for a clerk to key them. Each has `done`; setting it to `True` means the clerk no longer re-keys it. |
| `w.inv` | all except `rheinpump`, `textilwerk` | On-hand raw stock: item → quantity (writable dict). |
| `w.inv_fg`, `w.inv_comp` | `rheinpump` | On-hand finished goods (product → qty) and components (component → qty). Writable dicts. |
| `w.create_sales_order(cust, product, qty, due_iso)` | `rheinpump` | Keys a sales order into the ERP (→ the order dict). |
| `w.pending(tag=None)` | `rheinpump` | Lists what is still waiting under `tag` without popping it — use it to avoid double-triggering. |
| `w.book_dock(kind, ref, earliest_iso)` | `rheinpump` | Reserves the earliest free loading-ramp slot on or after a date (weekends closed; a full day rolls forward) → `{date, bay, bumped}`. Inbound and outbound share the ramps. |

On a template without `w.pending`, avoid double-triggering by checking what you already did, for
example whether `w.emails` already holds a message on your `thread` that is still unanswered.

## 4. Per template: purchase orders, master data, KPIs

`create_purchase_order` arguments, and the master-data names in scope for `run`:

| Template | `w.create_purchase_order(…)` | Master data in scope |
|---|---|---|
| `rheinpump` | `(vendor, component, qty)` | `PRODUCTS CUSTOMERS COMPONENTS VENDORS CARRIERS DRIVERS BOM PRICE LINES SHIFTS` |
| `nordbrot` | `(supplier, ingredient, qty)` | `PRODUCTS CUSTOMERS INGREDIENTS SUPPLIERS RECIPES PRICE LINES SHIFTS` |
| `roestwerk` | `(supplier, ingredient, qty)` | `PRODUCTS CUSTOMERS INGREDIENTS SUPPLIERS RECIPES PRICE LINES SHIFTS` |
| `almtal` | `(item, qty)` | `PRODUCTS CUSTOMERS RECIPES RAWS FARMS VENDORS CELLARS` |
| `hopfquell` | `(material, qty)` | `BEERS SKUS CUSTOMERS MATERIALS RECIPES PRICE SUPPLIERS HOP_ALPHA` |
| `eichhof` | `(item, qty, kind="material")` | `PRODUCTS PRODUCT_LIST CUSTOMERS SPECIES MATERIALS SUPPLIERS SIZES FINISHES KILNS` |
| `farbwerk` | `(material, qty, expedite=False)` | `PRODUCTS CUSTOMERS MATERIALS SUPPLIERS FORMULAS PRICE REACTORS BATCH_KG` |
| `textilwerk` | `(kind, item, qty)` | `PRODUCTS CUSTOMERS FIBRES DYES SUPPLIERS PRODUCTS_DEF PRICE LOOMS COLLECTION` |
| `spritzwerk` | `(resin, qty)` | `PRODUCTS CUSTOMERS RESINS RESIN_SUPPLIERS PARTS PART_MOLD PRICE MACHINES MATERIALS PRESSES FINISH_MACHINES` |

KPI keys `w.kpis(n)` returns (besides `sim_day`, `window_days`, `open_orders`, `automations_on`).
The oracle's `delta` covers the numeric ones:

| Template | KPIs |
|---|---|
| `rheinpump` | `on_time_ship_pct order_entry_mean_lag_days order_entry_error_rate orders_lost orders_via_automation orders_via_manual scrap_rate late_shipments_total breakdowns_total breakdown_unlogged_rate line_down_now ncr_open ncr_overdue_capa ncr_never_closing ap_paid ap_exceptions_open ap_stalled_missing_gr ap_duplicate_invoices ap_po_double_paid labor_unreported_rate labor_error_rate labor_hours_variance freight_overpaid_count freight_overpay_eur freight_disputed freight_spend_eur sched_release_lag_mean phantom_fg_units inventory_accuracy_pct cc_writeoffs_total md_error_active component_stockout_days eco_in_transition` |
| `nordbrot` | `on_time_ship_pct lots_in_quarantine incoming_release_rate lots_rejected coa_holds gluten_test_fails allergen_qc_scrap expiry_writeoffs_total ingredient_stockout_days` |
| `roestwerk` | `on_time_ship_pct lots_in_quarantine incoming_release_rate lots_rejected coa_holds moisture_test_fails scorch_scrap_units roast_scrap_rate expiry_writeoffs_total green_stockout_days` |
| `almtal` | `on_time_ship_pct order_fill_rate milk_accept_pct batch_conformance_pct milk_reject_count aging_scrap_kg cold_chain_breach_count yogurt_return_count culture_offspec_batches whey_unbooked_liters deviation_count expiry_writeoff_units` |
| `hopfquell` | `on_time_ship_pct order_fill_rate batch_pass_rate stuck_fermentation_count dumped_batches extra_tank_days ibu_offspec_holds underfill_reject_cases kegs_lost keg_shrinkage_value_eur keg_return_rate duty_gap_liters duty_gap_eur late_orders` |
| `eichhof` | `on_time_ship_pct order_fill_rate first_pass_yield_pct warping_rework_count config_error_count finishing_rework_count lumber_overrun_pct complex_order_late_pct scrap_pieces` |
| `farbwerk` | `on_time_ship_pct order_fill_rate first_pass_qc_pct voc_compliance_pct retint_count viscosity_oos_count contamination_scrap_batches missing_manifest_count resin_late_orders resin_expedite_count scrap_kg` |
| `textilwerk` | `on_time_ship_pct order_fill_rate first_quality_pct shade_reject_count redye_count shade_reject_rate seconds_metres avg_shrink_pct denim_shrink_pct off_count_yarn_lots late_orders` |
| `spritzwerk` | `on_time_ship_pct oee_pct first_pass_yield_pct scrap_units unplanned_downtime_events micro_stop_unlogged_rate molds_over_shotlife pm_overdue_count resin_stockout_days` |

A `rheinpump` example that uses its extensions (a buyer emails the vendor when stock runs low,
waits for the confirmation, then keys the PO):

```python
def run(w, params):
    floor = params.get("floor", 10)
    for comp, (vendor, _lead, _cost) in COMPONENTS.items():
        tag = "reorder:" + comp
        if w.inv_comp[comp] < floor and not w.pending(tag):
            w._email("purchasing@rheinpump.de", f"sales@{vendor.lower()}.example",
                     f"RFQ {comp}", f"Please confirm {params.get('qty', 30)} x {comp}.", tag)
            w.after(w.rng.randint(2, 4), tag, {"vendor": vendor, "comp": comp})
        for pl in w.due(tag):
            w.create_purchase_order(pl["vendor"], pl["comp"], params.get("qty", 30))
```

## 5. The oracle: `POST {eval_oracle}/counterfactual`

`{eval_oracle}` is `endpoints.eval_oracle` from `GET /modules/mine`. Send your World-Sim JWT
(`specs/world-sim/v0.1` §3). `GET` on the same path returns a one-line usage string.

**Request**

```jsonc
{
  "behavior": "def run(w, params):\n    ...",  // your candidate (required under access control)
  "params":   { },                              // passed to run() as `params` (default {})
  "days":     60                                // simulated days per arm; clamped to 5..180 (default 60)
}
```

The oracle forks the live world into two identical copies (same state, same generator), attaches
your behaviour to one, runs both for `days` days, and compares their KPIs over the trailing
`min(days, 30)` days.

**Response `200`**

| Field | Meaning |
|---|---|
| `days_simulated` | The `days` actually run (after clamping). |
| `kpi_window_days` | The comparison window, `min(days, 30)`. |
| `behavior_attached` | `true` when a behaviour was run. |
| `behavior_run_error` | The last day's run error, or `null` (§1). A non-null value means your numbers may describe a behaviour that did nothing. |
| `kpis_without_candidate`, `kpis_with_candidate` | The two arms' full KPI dicts. Present on `rheinpump`. |
| `delta` | Per numeric KPI: with − without. The keys are the template's KPIs (§4). This is authoritative for your own scoring. |
| `fitness` | The oracle's direction-signed sum of `delta`: a KPI that is better higher counts `+`, one that is better lower counts `−`, and a KPI with no declared direction is ignored. Positive = improvement. |
| `receipt` | `{alg: "hmac-sha256", payload, sig}`. `payload` binds a SHA-256 of your candidate, `days`, the fork's `sim_day`, `fitness` and `delta`. Attach it **verbatim** when you report a score; a gate holding the key can verify the score was measured, not self-reported. |
| `automation` | Always `null` for a behaviour. |

**Errors**

| Status | `error` | When |
|---|---|---|
| `400` | `behavior failed to compile` | Syntax error, or no callable `run`. `detail` has the message. |
| `400` | `provide 'automation' … or 'behavior' …` | Neither was sent. |
| `403` | `toggle_automations_require_system_access` | You named a built-in `automation` on an access-controlled instance (every sold instance is). Which automations exist is knowledge you earn from the systems; submit a `behavior` instead. |

Send exactly one candidate. The built-in `automation` field exists only on instances without access
control (local authoring); it is not part of the sold product.

## 6. Versioning

`world-api` follows `AGENTS.md` §6: within `v0.x` changes are additive (new names on `w`, new KPIs,
new templates). A KPI key or a `w` name listed here is removed or changed only with a `v1.0`, and
behaviours written against `v0.1` keep running.
