# `helix vehicle simulate`: drive a vehicle before it is published

A package's `targets` give its real-car figures (0-100 km/h 4.6 s ±8 %). Until now nothing checked them before a person drove the car on the live site. `vehicle simulate` puts the car on a flat pad, using the **runtime the platform serves today**: the same Rapier world and land solver v2 that players run. It measures the figures and judges each one against the package's own targets, plus an optional reference spec.

```
helix vehicle simulate <dir | vehicle-package.json | saved item JSON> [--spec <file>] [--json]
helix vehicle simulate --item <published-item-id> [--spec <file>] [--json]
    [--offline] [--runtime <bundle.mjs|url>] [--range ^0.3] [--api-url <url>]
```

Exit codes: `0` means every compared figure passes (or the car has no targets) and the keyboard launch does not FAIL. `1` means a figure is out of tolerance, the rest pose is wrong, or the car is not drivable on a keyboard. `2` means the car could not be simulated: the input was unreadable, no runtime was available, the engine refused the package, or the vehicle is not a land vehicle.

`helix vehicle validate` runs the same drive whenever the package has `targets`. A miss there is the error `SIMULATED_PERFORMANCE_OUT_OF_TOLERANCE` at `targets.<key>`, and `--no-simulate` skips the drive. Run it before sealing the Vehicle Package.

## The runtime it drives

1. `GET <api>/api/v1/instant-packages/humanoid-character/runtime/%5E0.3/index.js` returns a 307 to the CDN bundle. The request carries a browser user agent, because the CDN refuses bare clients.
2. The bytes are cached by sha256 under `~/.helix/cache/engine-runtime/<sha>/`. `HELIX_ENGINE_RUNTIME_CACHE` overrides the location. A per-(API, range) pointer remembers the last good fetch.
3. The bundle's only bare imports are rewritten to file URLs:
   - `three` → this CLI's `helix-runtime-three` alias (three 0.185.1, shared with `vehicle addon check`);
   - `@dimforge/rapier3d-compat` → rapier 0.14.0.

   Those are the versions the engine version's envelope declares (`manifest.three` / `manifest.rapier`). If a future engine declares other versions, the report warns and asks for a CLI update.
4. Every report starts with `engine runtime humanoid-character <SYSTEM_VERSION> (<source>; sha256 …)`. The source is one of:
   - `live`: fetched now;
   - `cache`: the same bytes as an earlier fetch;
   - `cache (offline fallback: <reason>; fetched <when>)`: the network was down and the last cached runtime was used;
   - `cache (offline, …)`: `--offline` was passed;
   - `file`: `--runtime <bundle.mjs>` was passed.

## What it measures

| Figure (target key) | How |
|---|---|
| `zeroToHundredKphS`, `zeroToSixtyMphS`, `quarterMileS`, `topSpeedKph` (+ converged), `ungovernedTopSpeedKph` | the runtime's `measureVehicle` card (full throttle, automatic shifts, 90 s) |
| `brakingSixtyToZeroM` | the card's 60-0 mph full-brake stop |
| `brakingHundredToZeroM`, and any stop a spec names | the runtime's `measureBraking` from that entry speed |
| `lateralG` | the card's steady-state skidpad (best 1 s average) |
| `turboLagS` | the roll-on below |
| rest pose | `allGrounded`, chassis clearance, ride height, pitch/roll. The pose FAILS when a wheel floats or the car tilts more than 3° |

**Tolerance semantics.** These are the same as the runtime's `compareToTargets`: `error = (simulated - target) / target`, and the figure passes iff `|error| <= tolerance`. `tolerance` is a fraction (0.08 = ±8 %). A figure the instrument could not measure FAILS.

**`--spec` formats.**
- A vehicle package, or `{ "targets": { … } }` (package-style `{ value, tolerance }`).
- A flat map of package-style keys.
- A reference spec with `perf.0_100_kmh_s`, `perf.0_60_mph_s`, `perf.quarter_mile_s`, `perf.top_speed_kmh`, `perf.skidpad_g` / `perf.lateral_g`, `perf.turbo_lag_s`, and `perf.braking_<N>_0_m` (from N km/h) or `perf.braking_<N>mph_0_m` (from N mph). A leaf there is a number or `{ value, tol_pct }`, where `tol_pct` is a percent. With no tolerance given, ±10 % applies, and the row says so.

Package targets and spec targets are reported as separate rows.

## Engine policy warnings (never errors)

`simulate` and `validate` print two named warnings from `src/vehicle/enginePolicy.ts`, both generic:

- `SPEED_LIMITER_IS_A_MARKET_GOVERNOR`: `physics.engine.speedLimiterKph` is below 0.9 x `targets.ungovernedTopSpeedKph` (or below 0.9 x
  the instrument's own ungoverned top speed when that target is absent). The live land solver never applies the field; only the
  instrument reads it, so a market or agreement governor just pins the instrument and the top-speed target while the platform car
  runs ungoverned. Set the limiter to null and `targets.topSpeedKph` to the ungoverned figure. No add-on can toggle it (the ECU slot has no
  speed-limiter tune path), so `check_vehicle_addon` and `vehicle addon check` measure add-ons ungoverned.
- `TORQUE_CURVE_EXCEEDS_DECLARED_CRANK_FIGURES`: an authored crank curve (`physics.engine.torqueCurve` or the solver's
  `simulation.land.driveline.engine.torqueCurve.points`), or the package's own `peakTorqueNm` / `peakPowerKw`, is more than 5 % above the
  maker's declared crank torque or power. Declared figures are read from `manufacturer` citation titles (N.m, kgm, lb-ft; kW, PS, hp;
  never a "at the wheels" or dyno line) and fall back to the package's own peak fields. Losses belong in `drivetrainEfficiency` and drag.
  It is a warning, not an error, because the figures are mined from prose and a market-capped maker figure can leave a car out of
  tolerance on its instrumented targets, which already fail as errors.

## Shift scheme (auto vs manual)

The report prints the gearbox's shift policy and, when it matters, a `⚠ shift` warning:

- `shift: gearbox kind manual, auto-shift ON, manual layer available (toggle ability7)` — a manual-kind gearbox with `gearbox.auto { enabled: true }`. The instrument shifts automatically, but the live drive also exposes a manual layer keyed on the standard action ids: **`ability7` toggles automatic ⇄ manual, `sprint` is the clutch, `ability1`–`ability6` select forward gears 1–6, `crouch` is neutral, `reload` is reverse.** For such a box the report adds **"simulated with auto-shift; live manual-shift unverified"** — this command proves the automatic path only, so you must still verify the live car upshifts before shipping.
- `shift: gearbox kind manual, auto-shift OFF` — the gearbox cannot shift itself. The instrument then holds 1st gear, the 0-100 / top-speed figures cannot be reached (they FAIL their targets), and the live car will pin 1st gear the same way unless the player uses the manual keys above. Author `auto { enabled: true, upRpm, downRpm }` for a road car the default drive should shift itself, or document the manual keys as the intended scheme.

Round 5's F40 passed the instrument's 0-100 in 4.28 s while the live car pinned 1st at ~20 km/h — a car whose shift scheme only works on one of the two surfaces. Read the `shift` line and the `⚠ shift` warning before you trust a green comparison.

## Keyboard launch (`--no-keyboard-launch` skips it)

The card's 0-100 is a digital launch too (`throttle: 1, steer: 0`), but on a perfectly symmetric pad nothing ever disturbs the heading, so a car that is directionally unstable under power still runs straight and posts its best figure. Round 8's turbo supercar posted 4.38 s here and hit the arena wall in 3 of 3 live keyboard launches. The live 993 reached 100 km/h in 3 of 3 with the same harness. `src/vehicle/keyboardLaunch.ts` adds two measurements in the same runtime:

- **The run.** It launches the car the way the live drive ability does:
  - an auto-hold stop, then W 0 → 1 in one tick (the platform does not ramp a digital throttle);
  - automatic shifts;
  - a player that taps A/D with 100 ms reactions to hold a 3.5 m lane from a start 2° off it.

  The `move` vector is normalised the way the platform does it, so W+A sends throttle 0.707 and steer −0.707. Reported: keyboard 0-100 against the card's (the gap), wheelspin time (driven slip ratio > 0.2) and peak slip per gear, the peak yaw rate, heading error and sideslip for 1.5 s after each upshift re-engages, and the worst lane offset.
- **The probe.** The same launch runs hands-off, with a 0.2 rad/s yaw-rate nudge at 20, 40, 60 and 100 km/h and as each of the first two upshifts re-engages. Each nudge is a fresh run in both directions, and the worse direction is kept.

Verdict:
- **FAIL** (not drivable on a keyboard): a nudge grows into a spin (sideslip ≥ 0.35 rad, or a yaw rate ≥ 3× the nudge), or the run spins or leaves its lane.
- **WARN**: heading error or sideslip above 0.1 rad in the run, a nudge still unsettled after 1 s, or a keyboard 0-100 more than 15 % slower than the card's.

FAIL makes the command exit 1. `vehicle validate` reports it as the warning `SIMULATED_KEYBOARD_LAUNCH_UNDRIVABLE` (WARN as `SIMULATED_KEYBOARD_LAUNCH_MARGINAL`). It is not an error because land v2 has no traction control to author, so a faithful no-TC car whose torque exceeds its rear grip in 1st gear may have no accurate way to pass. Tuning guidance is in the MCP skill reference `physics-from-specs.md`, "Drivable on a keyboard".

## Turbo lag

**Measurement.** The roll-on works like this:
1. Hold 3rd gear, or the top gear when there are fewer than four. Manual mode is used when the gearbox supports it.
2. Hold a fixed low rpm: max(2000, idle + 500, 1.1 × `clutch.launchStartRpm`), capped at half the limiter. An automatic box also stays above its `downRpm`.
3. Go to full throttle. `turboLagS` is the time until the 0.1 s-smoothed acceleration reaches 90 % of that pull's peak.

The report adds the start rpm and speed, the rpm at 90 %, and the start and peak acceleration. It also gives the torque curve's onset shape: peak torque and its rpm, the start rpm's share of peak, the rpm where the curve first reaches 50 % and 90 % of peak, and the steepest rise.

**Authoring rule.** On land solver v2, the engine torque each step is

```
evalLut(engine.torqueCurve, rpm) × throttle × limiterCut × boostFactor
boostFactor = curveBoostBar === undefined ? 1 + (boostTorqueCoef ?? 1) × boostBar
                                          : max(1, (1 + boostBar) / (1 + curveBoostBar))
```

This is runtime `src/core/vehicle/v2/driveline.ts`, `stepDriveline`. The curve is `simulation.land.driveline.engine.torqueCurve`, which `vehiclePackageToTuning` carries into `tuning.landV2.driveline.engine`.

With `boostTorqueCoef: 0` and no `curveBoostBar`, `boostFactor` is 1. A turbine block then makes sound and back-pressure, but **no torque**, so the static curve is the whole torque story. A full-boost dyno curve therefore pulls instantly at every rpm: no lag. (A set `curveBoostBar` only ever *raises* torque above the curve.) To author lag:

- below the boost-onset rpm, keep the curve at off-boost torque (about what the engine makes naturally aspirated);
- climb steeply through onset to the boosted plateau;
- run `helix vehicle simulate` and read `turbo lag` and `90 % at <rpm>`.

For reference, on engine 0.3.180 the round-1 F40 package measures 0.80 s from 2,840 rpm in 3rd; its curve is derated below about 3,300 rpm. The same car with a flat full-boost curve measures about 0.1 s. The naturally aspirated 993 measures 0.12 s. When forced induction is declared but adds no torque, and the curve already makes ≥ 85 % of peak at the roll-on rpm, the report prints a note saying the car will pull with no lag.

## Host manifest

The backend reads a vehicle's add-on host surface **only** from glTF `asset.extras.HELIX_vehicle` (backend `src/add-ons/host-manifest.ts`, `hostManifestOfGlb`). The runtime reads scene > document > asset. So a manifest written to the scene extras, which is what Blender's "Custom Properties" export does, drives fine but publishes a **silent non-host**: `verification.ok`, a board with no sockets and no tunable paths, and "0 compatible" in the customizer.

Put it on the asset:

```json
"asset": {
  "version": "2.0",
  "extras": {
    "HELIX_vehicle": {
      "version": 1,
      "class": "sports-car",
      "sockets": {
        "seat_dside_f": [0.34, 0.37, -0.10],
        "wheel_lf": [0.78, 0.33, 1.22],
        "exhaust": [0.30, 0.25, -2.10]
      }
    }
  }
}
```

Sockets are positions in the model frame: +X left, +Y up, +Z forward, metres. Names must match `^[A-Za-z0-9_.\-*]{1,64}$`; the backend drops anything else. `socketNodes` (`{ socketId: "node" | ["node", …] }`) must name real nodes.

After export with gltf-transform: `doc.getRoot().getAsset().extras = { ...doc.getRoot().getAsset().extras, HELIX_vehicle: manifest }`. You can also rewrite the GLB JSON chunk directly. Keep no differing copy in the scene or document extras.

`helix vehicle validate --glb` reports these codes as errors. `helix continuum publish-package` refuses to seal a `vehicle` Package descriptor whose model GLB (an object of media type `model/gltf-binary` carried as bytes) has any of them, before anything is uploaded:

| Code | Meaning |
|---|---|
| `HOST_MANIFEST_MISSING` | no `HELIX_vehicle` anywhere |
| `HOST_MANIFEST_MISPLACED` | found only in scene, document or node extras (the message says where) |
| `HOST_MANIFEST_EMPTY` | no usable socket |
| `HOST_MANIFEST_DIVERGENT` | a scene or document copy differs from the asset copy |
| `HOST_BIND_ROOT_MISSING` / `HOST_BIND_MOUNT_NODE_MISSING` / `HOST_BIND_ROOT_NOT_OWNER` | the host offers a `boot`/`bonnet` socket but the GLB lacks `vehicle_root`, the lid's mount node, or has the lid outside `vehicle_root` (the runtime throws while composing the car) |
| `HOST_MANIFEST_SOCKET_INVALID` | a socket value is not `[x, y, z]` |
| `HOST_MANIFEST_SOCKET_NAME_INVALID` | a socket name the backend drops |
| `HOST_MANIFEST_SOCKET_NODE_MISSING` | a `socketNodes` entry names a node that is not in the GLB |

To check a published car's board, read `GET /api/v1/universal-items/:id/slots`. A usable host has `hostKind: "vehicle"`, at least one socket, and, for a land car, the tunable paths its package resolves (backend #1677).

## Tests

`src/vehicle/simulate.spec.ts` and `src/vehicle/simulateRuntime.spec.ts` cover the comparison and tolerance rules, the spec formats, the specifier rewrite, the cache and the offline fallback. The smoke test drives the 993 fixture with the live runtime. It checks that the fixture passes its own targets and that targets 20 % slower FAIL. It runs in CI (`CI=true`) and with `HELIX_SIMULATE_SMOKE=1`; `HELIX_SIMULATE_SMOKE=0` turns it off.
