# World-Sim / v0.3 — your own living, simulated organisation

**World-Sim** gives you a whole company that actually operates — not a dataset, not a mock API.
Orders arrive. Simulated people key them into siloed business systems (ERP, MES, WMS, planning,
mail, logistics…) with realistic lag and mistakes. Goods are planned, produced with quirks, and
shipped — sometimes late. The clock ticks one simulated day every 30 seconds, around the clock,
and every system keeps its own records in its own storage.

Any organisation that produces something — a pump maker, a bakery, a brewery, a textile mill, a
coatings plant — fits the same world model, and there is a template for each. You get **your own
authenticated instance** with its own ports, its own data, and its own ground truth that only the
evaluation oracle knows.

Three things people use it for:

| Use it as… | What that looks like |
|---|---|
| **A training & evaluation gym for agents** | Point an agent at the silos and let it discover the processes, the friction between systems, and the work that happens in email — then score its proposed automations against hidden ground truth with the counterfactual oracle. |
| **A realistic demo-data generator** | Every silo fills with consistent, cross-referenced records (orders ↔ work orders ↔ stock movements ↔ shipments ↔ invoices ↔ emails) that evolve over time. Point your product at it instead of hand-written fixtures. |
| **An organisation model with flow analysis** | Edit the model live — add a quirk, change a lead time, automate the order clerk — and watch how the change ripples downstream into throughput, OTIF, WIP and cash KPIs. |

**Price:** €99 / month per simulation, charged from the first day (modules have no free trial), cancel any time to the end of the month.

---

## §0 — Your first five minutes

You bought a simulation and Account shows it **`ready`**. Here is the whole path from "provisioned"
to "scored an automation", copy-paste, no external docs needed. Set two things and go:

```bash
B=https://<your-tenant>.session-exchange.com   # the host you bought on; session-exchange.com for "default"
AGENT_MDX_TOKEN=<your login session or a machine (read/emit/admin) token>
```

**1. Mint a World-Sim JWT** — exchange any a4sx credential for a 1-hour RS256 token (`§3`). If
your tenant doesn't hold the `world-sim` addon this returns **402** — buy it first (Marketplace →
World-Sim, or `POST /billing/checkout {target:'module', item_id:'world-sim', plan:'subscribe'}`).

```bash
JWT=$(curl -sS -X POST "$B/auth/token" -H "Authorization: Bearer $AGENT_MDX_TOKEN" \
        -H "Content-Type: application/json" -d '{"aud":"world-sim","ttl_s":3600}' | jq -r .access_token)
```

**2. Find YOUR instance endpoints** — `GET /modules/mine` is where the host/ports live. It returns
each instance you own with its `status`, `host`, `port_base` and an `endpoints` block
(`silos[]`, `eval_oracle`, `helpdesk`); the `control` port is loopback-only and never listed for you.

```bash
curl -sS -H "Authorization: Bearer $AGENT_MDX_TOKEN" "$B/modules/mine" | jq '.instances[0]'
# pull the three you need into shell vars:
INST=$(curl -sS -H "Authorization: Bearer $AGENT_MDX_TOKEN" "$B/modules/mine" | jq '.instances[0]')
HELP=$(jq -r '.endpoints.helpdesk'    <<<"$INST")   # +10 — board + credential helpdesk
ORACLE=$(jq -r '.endpoints.eval_oracle' <<<"$INST") # +9  — the counterfactual oracle
SILO1=$(jq -r '.endpoints.silos[0]'   <<<"$INST")   # +1  — first business silo (usually ERP)
```

**3. Open the board** in a browser — the live IC/PCB-style process view for your company:

```bash
echo "$HELP"     # open this URL in a browser (it's the +10 helpdesk/board port)
```

**4. Get an in-world account and read one silo** — the helpdesk (`+10`) grants silo credentials, then
you call the silo (`+1`) with THAT credential, not the JWT (`§3`, Layer 2):

```bash
GRANT=$(curl -sS -H "Authorization: Bearer $JWT" -X POST "$HELP/access/request" \
          -H "Content-Type: application/json" -d '{"system":"erp","scope":"read"}')
ERP_AUTH=$(jq -r '.authorization' <<<"$GRANT")        # "Bearer …" for the silo
curl -sS -H "Authorization: $ERP_AUTH" "$SILO1/erp/sales_orders" | jq '.[0:3]'
```

**5. Score one ready-made automation** — paste this counterfactual as-is. It forks the live company,
runs 30 sim-days with and without your `behavior`, and returns the paired KPI delta + a signed
receipt. This one keys clean inbound email orders into the ERP the same day (the order-clerk loop on the
`rheinpump` default template). See **The World API** below for every `w` name it uses.

```bash
read -r -d '' BEHAVIOR <<'PY'
def run(w, params):
    import re   # imports go INSIDE run: module-level names are not visible to it
    # The order-clerk loop: key today's clean order emails into the ERP the same day,
    # instead of waiting days for a person to re-type them (with typos and losses).
    today = w._d()
    by_domain = {c.lower().replace("cu-", ""): c for c in CUSTOMERS}
    for m in w.emails:
        if m["date"] != today or not m["thread"].startswith("order-intake-"):
            continue
        cust = by_domain.get(m["from"].split("@")[1].split(".")[0])
        prod = re.search(r"\bP-\d{3}\b", m["body"])
        qty = re.search(r"(\d+)\s*(?:units|x)\b|quantity (\d+)", m["body"])
        due = re.search(r"\d{4}-\d{2}-\d{2}", m["body"])
        if not (cust and prod and qty and due):
            continue
        w.create_sales_order(cust, prod.group(0), int(qty.group(1) or qty.group(2)), due.group(0))
        for pe in w.pending_entries:          # the clerk no longer re-keys it later
            if not pe["done"] and pe["request_date"] == today and pe["true"]["customer"] == cust:
                pe["done"] = True
                break
PY
jq -n --arg b "$BEHAVIOR" '{behavior:$b, params:{}, days:30}' \
  | curl -sS -H "Authorization: Bearer $JWT" -H "Content-Type: application/json" \
         -X POST "$ORACLE/counterfactual" -d @- | jq '{delta, receipt}'
# → {"delta": {"on_time_ship_pct": …, "orders_lost": …, …}, "receipt": {alg,payload,sig}}
```

That's the loop: **mint → discover endpoints → read a silo → propose a behaviour → score it.** From
here, `§4` (act in it, change the model) and the **Oracle / World API** reference below go deeper.

> Every `w.*` name used in this spec is listed in **The World API** below — that section is the
> complete, supported surface; nothing else is needed to write a behaviour.

---

## 1. Get one

1. Sign in (GitHub or Google) and open **Marketplace**.
2. On the **World-Sim** card, pick a **company template** (see §5) and press *Start World-Sim*.
3. Complete the Stripe checkout. Your subscription is one simulation of that company.
4. Open **Account → Your World-Sims**. The card shows `requested` while your instance is being
   built (usually under two minutes), then flips to **`ready`** with your endpoints.

Behind the scenes the collector emits a governed provision request; the operator that owns the
simulation host builds your company from the template, allocates it a private port block, and
reports back. a4sx never reaches into the simulation host itself.

## 2. What you get

Your instance is one company on one host, on a block of **11 consecutive ports** starting at your
`port_base` (shown in Account as full URLs):

| Port | System | Exposure | What it is |
|---|---|---|---|
| `+0` | **control** | loopback only (not reachable by you) | The simulation's clock, scenario and ground-truth controls — reserved for the operator so an experiment can never peek at the answers. |
| `+1` … `+8` | **business silos** | public, credentialed | The company's systems, one per port: ERP, MES, WMS, planning, mail, TMS/QMS/LIMS/CMMS… (varies by template). Each needs its own credentials — see §3. |
| `+9` | **evaluation oracle** | tenant-gated | `POST /counterfactual` — fork the live company, run your candidate automation against the baseline, get the paired KPI delta and a signed receipt. |
| `+10` | **access / helpdesk** | tenant-gated | The in-world credential helpdesk: request accounts for silos, exactly like a new employee would. Also the live **board** for that company. |

The company's silos are deliberately heterogeneous: JSON documents here, a JSONL log there, SQLite,
CSV, a mailbox. That's the point — real organisations look like this, and the structure that matters
often exists only *between* systems and in email.

## 3. Authenticate

Two layers, on purpose:

**Layer 1 — who you are (a4sx → your sim).** The tenant-gated ports (`+9`, `+10`) and the
operator's management API accept a short-lived **JWT issued by a4sx**. Your tenant is the issuer,
so the sim knows which tenant you belong to without any shared secret.

- In the UI: **Account → Your World-Sims → Get access token** (copies a 1-hour token).
- From a script or an agent, exchange any a4sx credential — your login session *or* a machine
  token (read/emit/admin) — for a JWT:

```bash
B=https://<your-tenant>.session-exchange.com     # the host you bought on; session-exchange.com for default
JWT=$(curl -sS -X POST "$B/auth/token" -H "Authorization: Bearer $AGENT_MDX_TOKEN" \
        -H "Content-Type: application/json" -d '{"aud":"world-sim","ttl_s":3600}' | jq -r .access_token)

# who does the sim think I am?
curl -sS -H "Authorization: Bearer $JWT" http://<host>:<port_base+10>/whoami
```

Tokens are RS256 JWTs; the sim verifies them against `$B/.well-known/jwks.json`. Claims: `iss`
(your tenant base URL), `sub` (your user id, or the machine token's owner), `aud: world-sim`,
`tenant`, `exp` (≤ 1 h). Nothing to rotate on your side — just mint a new one.

**Layer 2 — who you are *inside the company* (the silos).** Each silo has its own accounts, like a
real company. Ask the in-world helpdesk:

```bash
H=http://<host>:<port_base+10>
curl -sS -H "Authorization: Bearer $JWT" "$H/access/catalog"          # what exists, what you may request
curl -sS -H "Authorization: Bearer $JWT" -X POST "$H/access/request" \
     -H "Content-Type: application/json" -d '{"system":"erp","scope":"read"}'
# → {"granted": true, "authorization": "Bearer …", "usage": "send header Authorization: … to http://<host>:<port_base+1>"}
```

Low-tier accounts (standard readers, service accounts) are granted immediately; write access to
external portals and personal mailboxes are higher tiers that the company's policy may refuse —
the response tells you why and what escalation would be needed. This *is* part of the world: an agent
that wants to automate dispatch has to notice it needs the dispatcher's mailbox and ask for it.

## 4. Use it

**Watch it.** Open the board on `+10` in a browser: an IC/PCB-style process diagram, one chip per
stage, LEDs pulsing on activity, quirks flagged as faults, a live KPI strip and event feed. Click a
chip to drill into its live records. Tabs switch between Process · Physical · Systems · Data layers
(ISA-95 view). The **data browser** shows every silo's tables with live row counts.

**Read the silos** (with the credentials from §3): e.g. `GET /erp/sales_orders`, `GET /mes/workorders`,
`GET /wms/stock`, `GET /planning/mrp`, `GET /mail/messages?thread=…`, `GET /tms/shipments?status=…`.
Every silo has `GET /docs`-style discovery on its root; the exact set depends on the template.

**Act in it.** Silos accept writes where a real one would: `POST /erp/sales_orders`,
`POST /erp/purchase_orders`, replying to mail threads, confirming work orders. Actuation is how an
agent's automation shows up in the KPIs.

**Score a candidate automation.** The evaluation oracle forks the live company and runs *with* and
*without* your behaviour for N simulated days:

```bash
curl -sS -H "Authorization: Bearer $JWT" -X POST http://<host>:<port_base+9>/counterfactual \
  -H "Content-Type: application/json" \
  -d '{"behavior":"def run(w, params):\n    # e.g. auto-confirm clean email orders into the ERP\n    ...","params":{},"days":60}'
# → paired KPI delta (throughput, OTIF, WIP, cash, cost) + a signed receipt you can attach to a report
```

You propose your **own** behaviour built from what you discovered — built-in toggles are not
enumerated to you, so there is nothing to memorise.

**Change the model.** The board's ⚙ editor (and `GET/POST /model` on the board port) lets you add,
tune or disable quirks (`supplier_delay`, `node_defect_rate`, `manual_process_lag`,
`tacit_email_process`, `unreliable_resource`), add custom segments (`def run(w, params): …` over the
World object), rewire stages, rename or re-silo them. Changes hot-apply — no restart. This is the
"flow analysis" use: change one part of the organisation, watch the downstream KPIs.

## Oracle / World API (mini-reference)

The flagship action — "score an automation" — is one call and one small function. Everything you need is
here: the call below, and **The World API** further down for what a behaviour can do.

### `POST {eval_oracle}/counterfactual` — the oracle contract

`{eval_oracle}` is the `+9` endpoint from `GET /modules/mine` (`endpoints.eval_oracle`), tenant-gated,
so send your World-Sim `JWT` (`§3`, Layer 1). The oracle forks the live company and runs it **with and
without** your candidate for `days` simulated days, then returns the paired KPI delta.

Request — send **exactly one** candidate (a named built-in `automation` XOR your own `behavior`;
sending both, or neither, is a 400):

```jsonc
{
  "behavior": "def run(w, params):\n    ...",   // your automation as Python source (XOR "automation")
  "params":   { },                               // free-form dict passed through to run()'s params
  "days":     60                                  // simulated days to run each arm (default 60)
}
```

Response:

```jsonc
{
  "delta": {                     // per-KPI (candidate − baseline); sign is "good up" for rates,
    "on_time_ship_pct": 28.9,    // "good down" for losses/cost. Keys vary by template.
    "orders_lost": -2,
    "ap_paid": 19
  },
  "receipt": {                   // tamper-evident, attach to a report
    "alg": "hmac-sha256",
    "payload": { "fitness": 30.9, "delta": { } },
    "sig": "…"
  }
}
```

Observed KPI keys include `on_time_ship_pct` / `otif`, `throughput`, `wip`, `cash`, `cost`,
`scrap_rate`, `orders_lost`, `ap_paid` — the set depends on the template. `fitness` in the receipt is
the collector's scalarisation of the delta (see `reference/improvement-loop/counterfactual_fitness.py`);
the raw `delta` is authoritative for your own scoring.

### The `behavior` — `def run(w, params)`

Your candidate is a single Python function, `run(w, params)`, executed inside the forked world each
simulated tick. `w` is the **World** object — the same handle a custom segment gets — and `params` is
the dict you sent. You build behaviours from what you discovered in the silos; the built-in toggles
are deliberately not enumerated, so there's nothing to memorise.

### The World API

This is the surface a behaviour gets on the `rheinpump` template — the same one a custom segment in
the simulator's model editor gets. It runs **once per simulated day**, at the end of the day's work.
Other templates share the core but differ in purchase-order arguments, stock and master data; the full
per-template reference is `specs/world-api/v0.1`.

| On `w` | What it is |
|---|---|
| `w.day`, `w._d()` | The simulated date (`date`) and the same as an ISO string. |
| `w.rng` | A seeded `random.Random`. Use it (not `random`) so paired runs stay comparable. |
| `w.kpis(n)` | The trailing-`n`-day KPI dict (the same keys the counterfactual `delta` reports). |
| `w.so`, `w.po`, `w.wo`, `w.mes`, `w.invoices`, `w.shipments`, `w.emails`, `w.wms_txns`, `w.pending_entries` | The silos' records, as lists of dicts (read them; append only via the calls below). |
| `w.inv_fg`, `w.inv_comp` | On-hand stock: product → qty, component → qty (dicts; writable). |
| `w.create_sales_order(cust, product, qty, due_iso)` | Key a sales order into the ERP. |
| `w.create_purchase_order(vendor, component, qty)` | Key a purchase order. |
| `w._email(frm, to, subject, body, thread)` | Send an email into the mailbox silo. |
| `w._wms(kind, item, qty, ref)` | Record a warehouse transaction. |
| `w.after(days, tag, payload)`, `w.due(tag)`, `w.pending(tag)` | Human-loop timing: schedule work, pop the payloads whose wait has elapsed (call every day), see what is still waiting. |
| `w.book_dock(kind, ref, earliest_iso)` | Reserve the earliest free loading-ramp slot on/after a date → `{date, bay, bumped}`. Inbound and outbound share the ramps. |

Also in scope, without importing: the master data `PRODUCTS CUSTOMERS COMPONENTS VENDORS CARRIERS
DRIVERS BOM PRICE LINES SHIFTS`, plus `timedelta`, `date`, `random`.

Two rules that trip people up:
- **Put imports inside `run`.** Names imported at the top of your code are not visible to `run`
  (`import re` at module level → `NameError` at run time).
- **`behavior_run_error` shows only the last day's error.** A day that runs cleanly clears it, so a
  behaviour that fails only on days with work can report `null`. Test on a day with matching records.

### Example behaviours

Each was run through the counterfactual on the `rheinpump` template (seed 7, 30 sim-days); the
deltas quoted are what that run returned. Your instance's history differs, so your numbers will too.

**A. Key email orders the same day** (the order-clerk loop; on-time shipments +6.1 pts):

```python
def run(w, params):
    import re   # imports go INSIDE run: module-level names are not visible to it
    # The order-clerk loop: key today's clean order emails into the ERP the same day,
    # instead of waiting days for a person to re-type them (with typos and losses).
    today = w._d()
    by_domain = {c.lower().replace("cu-", ""): c for c in CUSTOMERS}
    for m in w.emails:
        if m["date"] != today or not m["thread"].startswith("order-intake-"):
            continue
        cust = by_domain.get(m["from"].split("@")[1].split(".")[0])
        prod = re.search(r"\bP-\d{3}\b", m["body"])
        qty = re.search(r"(\d+)\s*(?:units|x)\b|quantity (\d+)", m["body"])
        due = re.search(r"\d{4}-\d{2}-\d{2}", m["body"])
        if not (cust and prod and qty and due):
            continue
        w.create_sales_order(cust, prod.group(0), int(qty.group(1) or qty.group(2)), due.group(0))
        for pe in w.pending_entries:          # the clerk no longer re-keys it later
            if not pe["done"] and pe["request_date"] == today and pe["true"]["customer"] == cust:
                pe["done"] = True
                break
```

**B. Human-in-the-loop reorder** (a buyer emails the vendor, waits for the confirmation, then keys the
PO; on-time shipments +17.5 pts, open orders 17 → 8). Try `params: {"floor": 10, "qty": 30}`:

```python
def run(w, params):
    # Human-in-the-loop reorder: a buyer emails the vendor when stock runs low, waits for the
    # confirmation (2-4 days), then keys the purchase order.
    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))
```

**C. An observational digest** (records a signal, changes nothing — its `delta` is all zeros, which is
a good sanity check that the oracle is paired):

```python
def run(w, params):
    # Observational: a Monday KPI digest by email. Records a signal, changes nothing,
    # so its counterfactual delta should be ~0 (a useful sanity check for the oracle).
    if w.day.weekday() == 0:
        k = w.kpis(7)
        w._email("controlling@rheinpump.de", "management@rheinpump.de", f"Weekly KPIs {w._d()}",
                 f"on-time {k['on_time_ship_pct']}%, open orders {k['open_orders']}", "weekly-kpi")
```

Run any of these via the `POST /counterfactual` call above; compare `delta` across variants of
`params` to tune, and keep the `receipt` for an auditable score.

## 5. Company templates

Every template is a different *kind* of organisation, chosen so the structure an agent must discover
is genuinely different — not the same plant with new labels.

| Template | Company | Industry · process type | What's interesting |
|---|---|---|---|
| `rheinpump` (default) | Rheinpump GmbH | Industrial pumps · discrete, assemble-to-order | The flagship: 8 silos incl. QMS and CMMS, 44 inefficiency kernels, email-driven order intake and carrier dispatch — two human loops you can automate from the board. |
| `nordbrot` | Nordbrot GmbH | Gluten-free bakery · batch/recipe, perishable lots | Received material is not stock until a LIMS test releases it from quarantine; lots expire. |
| `almtal` | Almtal Dairy | Farmstead cheese creamery · perishable, long aging | Milk is a living raw material; cheese sits in a cellar for weeks — a slow, quality-gated flow where timing decides what ships. |
| `hopfquell` | Hopfquell Brewery | Craft brewery + bottling/kegging · process-batch biology | Fermentation batches, returnable-keg logistics, excise-duty accounting. |
| `eichhof` | Eichhof Furniture GmbH | Make-to-order solid-wood furniture · configure-to-order | A CPQ configurator resolves each order's options into a BOM; wood and finish quality gates drive rework. |
| `farbwerk` | Farbwerk Coatings GmbH | Industrial paints & coatings · reactor-batch chemistry | Colour/QC control and EHS/VOC compliance — a batch that misses shade or emissions limits is reworked or scrapped. |
| `textilwerk` | Textilwerk Weberei | Integrated textile mill · long chain, lot genealogy | Fibre → yarn → greige → finished with dye-lot shade control and first-class lot genealogy. |
| `roestwerk` | Röstwerk Kaffeerösterei GmbH | Specialty coffee roastery · batch/recipe | Green-coffee intake → blend → roast profiles → degas → grind → pack, with an incoming-quality gate. |
| `spritzwerk` | Spritzwerk Kunststofftechnik GmbH | Plastic injection moulding · asset/tooling/yield | Multi-cavity moulds with finite tool life, hygroscopic resins, yield that depends on maintenance. |

All templates share the same world engine (a capacitated transformation-graph simulator with mass
conservation) and the same 11-port layout, so anything you build against one carries to the others.

## 6. Limits & lifecycle

- **One subscription = one simulation.** Want two companies? Two subscriptions.
- **Ports.** Your block is yours for the life of the subscription. The control port (`+0`) is never
  reachable from outside; ground truth is only ever revealed through the oracle's paired deltas.
- **Rate.** The clock runs at one sim-day per 30 s; pause/step/rate are operator-controlled in v0.1.
- **Data.** Your instance keeps ~60 days of history and snapshots every 10 sim-days. Cancelling the
  subscription **deprovisions the instance at period end; a snapshot of its world is kept for 30 days,
  then deleted**. Account shows it as `gone`. Export anything you need (the silos are plain HTTP)
  before you cancel.
- **Your World-Sims actions** (`/world-sims`, owner only). *Cancel World-Sim* schedules the end at
  the period end (`POST /modules/instances/{id}/cancel`); *Keep it running* withdraws that until the
  period ends (`POST /modules/instances/{id}/resume`). There is no pause and no immediate end. For an
  ended (`gone`) instance: *Delete snapshot now* asks for the snapshot to be deleted before its 30
  days are up (`POST /modules/instances/{id}/snapshot/delete`; cannot be undone), and *Remove from
  list* hides it (`POST /modules/instances/{id}/hide`; display only — `GET /modules/mine?include_hidden=1`
  still lists it).
- **Fair use.** It's a simulation, not a load-test target; the silos are single-process services.

## 7. FAQ

**Is this the "factory simulator"?** Yes — renamed. It was never only about factories: the same
world model runs a bakery, a brewery, a mill, a coatings plant. Any organisation that produces
something. The module id is `world-sim`; the old id still works.

**Where does it run?** On a4sx's own infrastructure, in an isolated, unprivileged container
runtime that the operator controls. Endpoints are shown as the host's IP and port for now.

**Can my agents use it without me logging in?** Yes — any a4sx machine token can be exchanged
for a World-Sim JWT at `POST /auth/token`. Give your operator a token from your tenant and it can
mint its own.

**Why two credential layers?** Because that's what real organisations have: an identity (who you
are to the company) and system accounts (what each system lets that identity do). Agents that can
navigate the second layer are the ones that work in the real world.

**Can I bring my own company?** Not from the marketplace yet — the operator's API does accept custom
worlds (`world.py` + `server.py`) for tenants who build their own. Ask.

**Where's the deep documentation of the world model?** The simulator engine is **private**. Everything
you need to write and score behaviours is in this spec and in `specs/world-api/v0.1` (the complete
behaviour surface, per template). The company templates (§5) describe each world's processes.

---
*Integrators and operators: the provision/deprovision event contract and the identity bridge are
specified in `docs/world-sim-operator-contract.md` in the platform repository.*
