Skip to content
Back to skills

Test Via Api

ASecurity

How to verify luncosim changes end-to-end without asking the user to click. Trigger whenever a UI flow needs verification — a new diagram, a fix to drill-in, a screenshot to confirm a regression, a smoke test of any reflect-registered Event command. The workbench exposes a small HTTP API on `--api PORT`; this skill is the runbook for driving it from curl, capturing screenshots, diagnosing failures, and adding new commands when the existing surface isn't enough. Also trigger when you catch you...

  • 112 stars
  • 0 votes
  • 0 copies
  • 1 view
  • Added November 7, 2026
testingjavascriptpythonrustgojavabashnodeexpresstestingapi

Works with

  • cursor
  • terminal
  • cli
  • api

Security analysis

A96/100
  • mediumUses curl or wget to download content

Pro shows the line behind each finding and how to fix it

Scanned November 25, 2026

npx -y skills add LunCoSim/lunco-sim --skill test-via-api --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Test Via Api?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Test Via Api
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/luncosim-test-via-api/badge)](https://www.skillsdirectory.com/skills/luncosim-test-via-api)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: test-via-api
description: >
  How to verify luncosim changes end-to-end without asking the
  user to click. Trigger whenever a UI flow needs verification — a new
  diagram, a fix to drill-in, a screenshot to confirm a regression, a
  smoke test of any reflect-registered Event command. The workbench
  exposes a small HTTP API on `--api PORT`; this skill is the runbook
  for driving it from curl, capturing screenshots, diagnosing failures,
  and adding new commands when the existing surface isn't enough. Also
  trigger when you catch yourself about to `pkill lunica`,
  write a temp `.rs` test binary to inspect rumoca state, chain a
  `sleep 30 && tail` poll, or ask the user "can you check the
  screenshot?". The right move is always: send a command, take a
  screenshot, read it, decide.
---

# Test the workbench via API

The production `luncosim` exposes a reflect-registered Event API on
`--api PORT` (default 4101). Always pass this flag when launching the luncosim, including
visual checks; use another explicit free port if 4101 is occupied. UI verification — diagrams rendering,
drill-ins, simulations, file ops — should be driven from this API
rather than asking the user to click.

## Mode policy

Use a **headful windowed `luncosim` session by default** whenever the work
concerns a scene, Editor, viewport, UI, motion, layout, or any result the user
needs to watch. Start the production binary with `--api PORT` and a graphical
display; do not add `--no-ui`, `--offscreen`, or another windowless flag. Keep
that window alive while iterating so the user can see each coherent change.

Use `--no-ui`/`luncosim-server` only for explicitly numeric or API-only checks
where there is no visual acceptance claim. Use `--offscreen` only when the user
specifically requests an offscreen recording or a graphics test that is meant
to run without a visible window. If a requested visual check cannot run
headfully, stop and report the display/session blocker instead of silently
falling back to headless mode.

For Time-menu throughput, use the ordinary-pacing acceptance driver in
[`inspect-simulation`](../inspect-simulation/SKILL.md). Synthetic gesture flags
and repeated API requests can mask the host-pacing defect that this gate measures.
Its `--check-modelica-hud` option runs ten authored checks for live completion
FPS, pause and the negative cleared-scene case, with running/cleared screenshots.
This checks actual completed-step throughput independently of requested cadence.

The shared `ProductionSession` lifecycle checks the actual process exit code
as well as API Exit and port release. Native crashes fail acceptance even when
the preceding command assertions passed. `test_runtime_lifecycle.py` covers the
harness boundary; `test_ui_review_followup.py --port <free-port>` covers terminal
shader/scene editing results, preserved shader files, and rapid GPU/watcher shutdown.
Require a clean render log as well as exit code zero: a background watcher panic
can occur during teardown without changing the process exit code.

## Live shader iteration

Shader source edits are a live-test path. Keep the production luncosim running, edit the
WESL under `assets/shaders/`, then dispatch `ReloadShader` through the same API. A bare
engine path such as `shaders/starfield.wesl` resolves the canonical `lunco://`
asset identity; an explicit `lunco://…` or `twin://…` path is exact. An empty
path reloads every currently loaded WESL asset, not an arbitrary hard-coded file list.
The response reports the queued paths and fails if no active asset matches. Confirm the
command result, then inspect the unchanged window; shader compiler errors remain in the
render log. Do not relaunch the app just to pick up a shader edit.

## Tutorial and Rhai iteration

For stable scene-URI regressions, run
`python3 scripts/api/test_twin_source_uri.py --port <free-port>` with this
checkout's production `LUNCOSIM_BIN`. The windowed driver opens one Twin, then
requests its stable scene URI while the default document source is still being
prepared, and repeats `LoadScene`, `ResetSceneRuntime`, `RestartScene`, and the
authored scenario-menu loader for three cycles. It also replaces that Twin three
times, requires a fresh internal mount lease each time, and reloads with the
same stable public URI after every remount. The early request must wait for the
document's stage-input lease; readiness must finish without an authority-change
load failure.
The `assets/scenarios/tests/twin_source_uri.rhai` verdicts require the unchanged display
name, a stable public scene URI, and a retained Twin/mount during scene
operations. Each load uses the canonical URI derived from its source
identity. An unmounted identity, a live mount URI, and a retired mount URI
must be rejected without changing the current scene.
The authored verdict also checks that readiness progress reasons stay generic
and each pending API `scene_load` label equals the canonical source URI. The
workbench loading notice displays the Twin name and relative scene path. The
driver captures that notice for visual review,
checks the mounted projection after reloads and resets, captures the final
window, and verifies API Exit and port release. It also runs
`twin_identity_boundary.rhai` under the Twin execution route; this authored
verdict checks that Twin execution context, lifecycle status, contract queries,
and command/query discovery, including `ScriptComplete`, contain no workspace
Twin selectors. Twin scripts that query `ScriptingCatalog` must select the
needed `sections` so the typed result stays inside the shared Rhai value limit.

To include a composed asset dependency authored with a stable Twin source URI,
run the same driver against the maintained SysML fixture scene:

```bash
LUNCOSIM_BIN=target/debug/luncosim python3 scripts/api/test_twin_source_uri.py \
  --port <free-port> \
  --twin assets/scenes/tests/sysml_async_analysis \
  --scene power_budget.usda \
  --root-prim /World
```

That scene's `info:sourceAsset` is authored as
`twin://sysml_async_analysis/verify_power_budget.rhai`; readiness must resolve
the stable source identity to the current mount, and the same scene URI must
remain reusable through reset, restart and remount.

For Twin lifecycle regressions, open an editor document in Twin A, replace it
with Twin B, and inspect `ListOpenDocuments` plus USD preview state. No old
document ID or preview may survive; repeat `OpenTwin` on B to verify fresh
admission. A rejected Twin path must preserve the current documents. Twin
replacement closes loose/library editor documents as well as Twin-owned files.
`ResetSceneRuntime` tears down scene-owned simulation state while retaining the
current Twin and stable stage source URI. Twin-scoped scripts and status facts
must not expose the workspace Twin ID or private mount lease. Check typed
query, command, hook, and policy-status result data too: workspace selector
fields must be absent recursively in Twin scope, while app-level APIs retain
workspace selectors. Exercise reflected `get()` and `get_setting()` with both a
whole compound value and a direct selector-field path. Verify script values and
diagnostics expose stable source URIs without the private mount lease. Verify
Twin-scoped `ScriptingCatalog` and `ScriptComplete` omit workspace selectors
from command and query discovery.
`RestartScene` is the source reload and preserves editable documents. On reload,
require fresh stage readiness before inspecting terrain or Modelica
participants: the reused root waits for the prepared reload, and the document's
serialized generation joins that loaded revision before later edits project.
Pending editor and workspace-restore work must not recreate old tabs after
replacement. Modelica `CloseDocument` is owned by the headless core, so exercise
scratch-document closure in both headless and windowed hosts.
`modelica_compiled_metadata.rhai` also verifies that closing an API scratch
document retires its live Modelica participant through the shared close owner.

The maintained document-close scene gate is
`scenes/tests/twin_session_retirement/twin_session_retirement.usda` with verdict
channel `TWIN_DOCUMENT_CLOSE`. Run it through `$LUNCOSIM_BIN test`. The
gate covers dirty SysML drafts as well as Modelica scratch documents; assert
actual domain retirement rather than only removal from workspace metadata.
The windowed switch/reopen/rejected-candidate gate is
`python scripts/api/test_twin_session_retirement.py`; set `LUNCOSIM_BIN` and
an explicit free `LUNCOSIM_API_PORT`. Its assertions are authored in
`assets/scenarios/tests/twin_session_retirement.rhai`, and its process wrapper
verifies API `Exit` and port release.
The driver waits for the fresh document's scene projection and readiness after
each replacement and captures generated
documents as well as editor documents. `LUNCOSIM_TEST_TWIN_A` and
`LUNCOSIM_TEST_TWIN_B` select exact native Twin roots; otherwise it uses the
maintained fixtures. `LUNCOSIM_TEST_SCREENSHOT` optionally captures the final
replacement before cleanup. Require the `TWIN_BROWSER_RETIREMENT` Rhai verdict
for the current file index and runtime owners, `TWIN_MODELICA_RETIREMENT` for
the Models document registry, and `TWIN_CATALOG_RETIREMENT` for retired metadata
and spawn sources. The driver covers OpenTwin, OpenFolder and native/file-URI
OpenFile replacement. Include a round trip: reopening
a Twin must resolve its authored logical dependencies through the fresh mount,
while requests from its retired origin remain rejected.
`python3 scripts/api/test_twin_loading_replacement.py --port <free-port>`
exercises the native File menu while a scene is pending, then queues
`RestartScene`/`ClearScene` before replacing that owner and submits rapid
successive replacements. It requires final projection and repeated authored
retirement verdicts after delayed preparation can arrive. Clear/restart requests
use the serialized scene transaction; replacement retires the outgoing owner's
pending intent through the shared lifecycle boundary.
The driver also clears a pending load without a successor, checks that delayed
work leaves the viewport empty and ready, and then proves recovery by loading
another Twin. The default `--phase all` also clears late participant admission
and a terminal Modelica initialization fault, then verifies an empty fault-free
world and a fresh successor. Use `--phase loading` or `--phase late` to isolate
one boundary. The driver establishes a completed physics sample before fault
injection: `PhysicsPerformance` explicitly rejects timing queries before the
first Avian step, even when the scene is otherwise ready.
Retired deferred compile requests must be discarded before any
worker failure or diagnostic can publish into the cleared scene.

`SESSION_INPUT_API_PORT=<free-port> python3 scripts/api/test_session_input_admission.py`
checks fixed-tick input admission for USD-projected Modelica participants and
control release. Discover names with `ListPorts`; `ReadPorts` requires an explicit
`port_names` selection. Live Modelica commits use the target model identity,
including participants without an editor document link. Authority-release
preservation uses a document-authored control endpoint without a local
self-driver; a free-flight avatar continuously publishes its own input and
cannot isolate that assertion.

`python3 scripts/api/test_modelica_lifecycle.py --port <free-port>` runs both
parameterized Modelica lifecycle scenarios sequentially in owned UI sessions.
It authors isolated Twin entries through document commands, supplies an admitted
scene clock without an initial workspace Twin, and limits native experiments to
one worker slot. The runtime-retirement gate proves cancellation of running and
queued outgoing work, rejection of retired documents and sibling imports, and
successful replacement work. The Command host admits each exact mounted scene
before signaling the retained Application orchestrator; that script must not
read a Twin Simulation route from Application Simulation scope.

Set `LUNCOSIM_TEST_RECENT_MENU=1` to exercise the actual native Recent Twin menu
at the default desktop scale (the same coordinates as the loading-replacement
driver). The scene-only LoadScene and RestartScene checks preserve the open
Twin and require the replacement/restarted projection before their verdicts.
AddTwin and AddFolderToWorkspace preserve the existing documents and active
Twin; subsequent replacement must retire all added source catalogs too.
Each replacement also requires `TWIN_SCRIPT_SOURCE_SCOPE`: the stable
`twin_source_identity()` must resolve the replacement SysML source set. A Twin
reopen preserves that source identity while the Rust asset owner retires and
replaces its internal mount lease. A scene can finish loading even when its mission script failed;
inspect `ScriptStatus` and actual propulsion when verifying ignition.

Tutorial behavior is authored in `assets/tutorials/**/*.rhai` and should be
tested through its production scene gate in `assets/scenes/tests/` with the
observer in `assets/scenarios/tests/`. After editing either Rhai file, rerun
`./scripts/run_scene_tests.sh --no-build --exact <scene-name>` for a single
scene, or `./scripts/run_scene_tests.sh --no-build <scene-substring>` for a
group; the runner uses four independent headless processes by default, and
`-j/--jobs N` changes that bound (`-j 1` is the serial diagnostic mode). This
does not change each gate process's deterministic `--threads 1 --jitter 0`, and
graphics assertions remain a separate serial offscreen pass. Do not rebuild the
Rust core for a script-only change. The observer must verify public `cmd:*`
events plus the resulting live state and emit a real verdict. Parsing or
`--validate` is only preflight evidence.

For native selected-light response, run
`python3 scripts/api/test_directional_light_response.py --port <free-port> --output <artifact-dir>`
with the matching production `LUNCOSIM_BIN`. The Rhai observer configures the
existing Sun precision fixture through transient USD operations and scopes its
fill through reflected native `RenderLayers`. The GPU control checks both
lights, Sun-only scaling, default/missing selection and bounded negative inputs;
the host checks pixel verdicts, diagnostics, source preservation and owned Exit.

For experiments on USD-generated Modelica networks, query
`GeneratedModelicaSource { network_root, include_source: false }` to read
bounded metadata. Require `document_source_matches == true` and retain its
`document_id` and `document_generation`; reject changed metadata before
admission or during observation. Run the original generated document rather
than copying its equations. `scenarios/tests/generated_source_metadata.rhai`
accepts a composed `network_root` parameter and checks the linked document,
source omission, absent roots and invalid query types in the production host.

The generic model-authoring facades have the same production gate. The focused
fixture is `model_authoring`:

```bash
./scripts/run_scene_tests.sh --no-build --exact model_authoring -j 4
```

Its Rhai observer exercises `model_context`, `readiness_report`,
`scene_recipe`, `port_graph`, `wiring_plan`, and `publish_component`, including
fail-loud missing endpoint, control, asset, identity, and provenance cases.
Use this narrow gate after changing the tool or its authored fixture; a parse
pass alone does not prove the namespaced calls work in production.

Terminal runtime faults end scene tests during startup preparation as well as
stepped execution. Inspect the exact fault and fix its owner or authored
negative action; extending the readiness timeout cannot clear a terminal fault.
Model recompilation holds fixed execution, so assert retained model-state
revisions and the resulting output instead of requiring a Simulation observer
to see the temporary absence of an output during preparation.

The live port-owner collision contract is covered the same way:

```bash
./scripts/run_scene_tests.sh --no-build --exact port_owner_collision -j 4
```

Its USD fixture owns the duplicate and clean control cases; the Rhai observer
calls `RunLint` and verifies the structured `LintReport` winner, shadowed owner,
property paths, and precedence. Prefer this authored pair for observable lint
behavior instead of embedding USDA or fake backend components in Rust tests.

Public USD query-provider behavior belongs in authored `.usda` fixtures and
Rhai scene gates, exercised through the production query bridge. Keep Rust
tests for provider internals only when the behavior cannot be observed through
that public surface; do not construct `DocumentRegistry` worlds with inline
USDA to duplicate inspection, target-resolution, or synchronization behavior.
The `usd_query_api` gate covers those public contracts, while the assembly
proposal lifecycle gate covers edit-session inspection.

Editor material edits belong in an authored USD fixture plus an editor Rhai
scenario, not a Rust test with a multiline USDA string. The
`usd_material_edit_projection` fixture exercises typed material edits,
whole-source replacement, and the preview's projected-generation lifecycle
through the production editor runner. Keep Rust coverage for the focused
USD-to-render-intent mapping mechanism, where the mapping itself is the subject.
When the current root cannot compose, exercise recovery with a single root
`ReplaceSource`: the command owner prepares dependencies from the candidate,
validates the candidate composition, and rejects invalid replacements before
generation changes. Save successful edits through `SaveDocument` and read the
document back through the API. A valid replacement must leave a failed scene
stopped and publish an actionable Recent Events entry; only its explicit Load
Scene action may start a new transition. Verify that composed document queries
report the failed stage until that action completes.
The material-edit gate also adds and removes a primitive in two leases of one
document. Framing reads actual projected mesh bounds, so a native USD edit alone
cannot satisfy that gate while stale or missing preview entities remain.
Wait for preview readiness before composing its document inspection. The
`preview_domain_isolation` gate uses explicit electrical inputs, declared query
dependencies, and an atomic `MovePrim` plus `SetDefaultPrim` plan before proving
that preview copies do not admit Modelica execution.

For source-preview isolation, run `scripts/api/test_usd_source_isolation.py`
with an exact `--scene`, `--source`, composed `--selection-path`, free `--port`
and `--log`. Its `RunScenarioAsset` invocation supplies all required parameters
to `assets/scenarios/tests/usd_source_isolation.rhai` and requires eight authored
checks, including invalid-source rejection, unchanged Twin/topology and
advancing physics. `--screenshot` records the exact viewport/selection context;
the shared `ProductionSession.capture_screenshot` requires fresh publication
before API Exit. Pair the resulting image with those handles when checking
Prim-tree reveal and highlight.

For spatial safety coverage, keep malformed authored transforms in the USD
projection layer: that layer must reject them before ECS materialization. Test
runtime-state admission at the `lunco-usd-avian` bridge owner, where a finite
but f32-unrepresentable pose must raise a named `RuntimeFaults` record and
`PhysicsHolds::SAFETY_FAILURE` before Avian runs. Test public `Raycast` and
`GroundHeight` with a finite but unrepresentable query origin through an
authored production scene; the expected result is `{hit:false}`, not a
terminal simulation fault. This distinction keeps query-input validation from
masking an engine-state failure and avoids duplicating guards in sensors,
terrain, and vehicle callers.

For terminal runtime-fault recovery, verify the two owners separately and then
the lifecycle seam. `RuntimeFaults` must pause `Time<Physics>` with a zero delta
while leaving `Time<Virtual>` available for diagnostics and teardown. The bad
scene itself is never resumed in place. `SceneTeardown` clears only the outgoing
scene's terminal fault and `PhysicsHolds::SAFETY_FAILURE`; the physics owner
also resets scene-owned holds, deliberate-step debt, and the physics clock
before a user-requested replacement transition. The focused regression names are
`terminal_runtime_fault_pauses_physics_until_cleared` in `lunco-physics` and
`fault_then_scene_reload_can_admit_a_replacement_runtime` in `lunco-usd-sim`.

The scene-test runner stops stepping at a terminal runtime fault. A declared
`expect_runtime_fault(kind)` satisfies that negative fixture; an unexpected
fault fails immediately with the owner's structured diagnostic. A separate
process cannot prove same-process recovery. Use a lifecycle test or a live API
session that explicitly submits teardown,
loads the replacement, and checks the new scene's admission/status. Do not add
an automatic repair, retry, process restart, or fault-clearing fallback to make
the invalid scene continue. A validated user `ReplaceSource` followed by the
explicit Recent Events Load Scene action is a new scene transition, not an
in-place resume.

Scene, render, and editor acceptance runs are isolated by default and use a
fresh production process. Their launchers keep settings in memory and disable
runtime-overlay reads and writes regardless of Twin policy. The production
scene runner fails before scenario start if a file-backed authored USD
document is already dirty; runtime setup must not turn a clean fixture into
unsaved authored work.

For a one-shot assertion that needs the currently loaded USD stage, use
`./scripts/api/run_rhai_test.sh <port> <test.rhai> [probe-prim]`. It prepends
the test libraries and delegates to the native `luncosim rhai --stdout` client,
which calls `RunRhai` on the existing production session. Editing and rerunning
the test does not restart the app. It reads authored verdict lines before the
CLI's expression result and fails if any verdict reports `TESTS_FAIL`.
Use `./scripts/api/run_scenario.sh`
when the assertion should remain attached as a persistent observer.

When a test depends on a Twin-scoped Rhai tool, register or reload that library
in the same session first, confirm it with `ListToolLibraries`/`GetToolLibrary`,
and make a minimal namespaced call before running the real observer. Discovery
does not prove that the current Rhai engine has rebuilt its static module set.
For a user-requested same-session workflow, use `RunRhai` or an attached
`RunScenario`; do not substitute the multi-process scene-test runner.

For an interactive lesson, keep one production session and use
`RunScenarioAsset` through `/api/commands`, then inspect the HUD and event
stream. `RunScenario` is the live hot-reload path for a script attached to an
existing host. Restart only when changing Rust or when a clean scene lifecycle
is itself under test.

To exercise a discrete semantic action, address the target's `api_id` and send
one `SimulateIntentEdge` command; do not model a pulse as two API requests:

```json
{
  "type": "ExecuteCommand",
  "command": "SimulateIntentEdge",
  "params": {
    "target": 1234,
    "intent": "release",
    "edge": "pulse",
    "producer_id": 4123
  }
}
```

The response includes the canonical `intent`, `edge`, `producer_id`,
`correlation_id`, and command `id`. Reuse the same nonzero `producer_id` for
commands from one API producer. API submissions also include `admission` with
the committed scene generation, effective simulation tick, and per-tick
sequence. Confirm
delivery through the `intent.edge` telemetry event (`source`,
`value.target_gid`, and `value.correlation_id` identify the same target/action);
its admission fields carry the same stamp. Use the returned `correlation_id`
for the exact edge's trace, even when the scene emits later edges:

```json
{
  "type": "ExecuteCommand",
  "command": "CausalTrace",
  "params": {"target": 1234, "correlation_id": 5678}
}
```

The response composes the authored binding, selected `PortRegistry` owner,
USD connection/native-joint admission, current retained measurements, and the
producer's admission stamp. An empty/pending stage is a real incomplete path.
A target-scoped command still passes the normal ownership/authority gate; an
acknowledgement alone does not prove that a consuming Twin policy acted on the
edge.

For a held control, send one `SimulateIntent` command with `held: true` or
`false` and a stable nonzero `producer_id`, reusing that ID for later commands
from the same API producer. An external command targeting fixed-simulation
state returns a correlation id and next-tick admission stamp; verify the
matching `intent.hold` event has the same producer, target, held value, and
stamp. The held state changes at that fixed tick. Local-embodiment commands
remain on the interaction cadence.

## Live runtime HTML/CSS iteration

The native `luncosim` UI watches the retained runtime surfaces under
`assets/ui/`. Edit a surface's `.html` or `.css` in place and inspect the same
window; HUI rebuilds the affected template and Flair reapplies the stylesheet
without a binary rebuild or relaunch. Editing `runtime_surfaces.json` rebuilds
the registered surface roots and action bindings. Rust exposure producers and
action observers still require a rebuilt production binary.

Use `ReadExposures` to verify the data side independently of the pixels:

```bash
curl -s -X POST http://127.0.0.1:4101/api/commands \
  -H 'content-type: application/json' \
  -d '{"type":"ExecuteCommand","command":"ReadExposures","params":{"surface":"driven-vessel"}}' | jq .
```

The response's `revision` tracks changed values, visibility, namespace withdrawal
and scene retirement. Scene namespaces and their properties are removed on
reload; only explicitly application-owned surfaces survive. If the revision is
stable, an unchanged runtime surface should not rebuild its
view-model. Use `CaptureScreenshot` for the visual check. `ReloadShader` and
`RunScenario` reload WESL and Rhai respectively; neither reloads HTML/CSS.

Runtime UI is a small native HUI/Flair language, not a browser DOM. Do not
expect JavaScript, forms, text inputs, full CSS, or host-font fallback. Read the
[runtime UI skill](../runtime-ui/SKILL.md) for the supported surface contract,
placement/dock ownership, font rules, and performance gates.

## Session lifecycle

Each agent doing runtime work owns a luncosim session on a distinct explicit free
API port. Concurrent agent sessions are allowed on different ports. Launch from
the same repository checkout and working directory as that agent's terminal,
using that checkout's production binary. Before replacing your own session, send
`Exit` and verify its process and port are gone; never control another agent's
session or reuse an occupied port. Keep your current process for live shader/Rhai
edits; restart only when a rebuilt binary or an explicit clean session is required.

## Lifecycle (start → drive → stop)

```bash
# 1. Resolve the production binary in this checkout, choose a free API port
#    owned by this agent, and start it from this checkout's working directory.
#    Keep it alive in the runner's background session.
"$LUNCOSIM_BIN" --api 4101

# 2. Wait for the readiness contract, not just an open socket:
until curl -s http://127.0.0.1:4101/api/ready 2>/dev/null \
  | jq -e '.data.ready == true and .data.world_hold == false and .data.pending_count == 0' >/dev/null; do
  sleep 1
done

# 3. Send commands (see catalog below).

# 4. Stop with Exit, NEVER pkill / kill (user has to confirm those):
curl -s -X POST http://127.0.0.1:4101/api/commands \
  -H "Content-Type: application/json" \
  -d '{"type":"ExecuteCommand","command":"Exit","params":{}}'
```

After `Exit`, verify that the process and `:4101` listener are gone before
starting another session. A queued command or a reachable socket is not proof
that a scene is ready; `/api/ready` is the gate for scene load, Modelica compile
and participant initialization. For a requested Twin scene, `preparation`
includes its pending workspace scan, document preparation and the admitted
transition until the scene lifecycle takes over. Independently verify authored
operator controls when readiness of the presentation is part of the test.
For coupled Modelica admission, also inspect
`CosimStatus.last_coupled_initialization` and the actual participant outputs.
Successful constructors alone do not prove the connected initial coordinate was
certified. The initialization-only worker preparation has no live actor or
telemetry publisher. See [run-modelica](../run-modelica/SKILL.md#omitted-library-inputs)
for checked-interface admission, state constraints and native port ownership.
When checking a Twin transition, inspect `/api/ready.pending` entries with
`kind == "scene_load"`: their `label` must be the stable
`twin://<source-identity>/<relative-path>` URI, never the internal mount lease.
For scene replacements that change `ActivePhysicsFrame`, also query each new
dynamic body with `QueryPhysicsState` and require `physics_pose_seeded == true`
before declaring admission complete; this catches a physics clock blocked
before the replacement scene's first pose is written.

## Curl shape

Every typed command uses the tagged envelope
`{"type":"ExecuteCommand","command":"<Name>","params":{...}}`.
Include `params` even for parameterless commands. Built-in discovery and entity
listing use their own explicit `type` values.

```bash
curl -s -X POST http://127.0.0.1:4101/api/commands \
  -H "Content-Type: application/json" \
  -d '{"type":"ExecuteCommand","command":"OpenClass","params":{"qualified":"ControlLibrary.Controllers.PID"}}'
```

Successful fire-and-forget response: `{"data":{"accepted":true}}`. Typed result
commands place their payload in the same `data` envelope. Malformed envelopes
reject at transport admission; invalid typed parameters return HTTP 422.
Completion belongs to the command's owner: `RunExperiment` returns its exact
`experiment_id` after registration, then `RunStatus` and `GetExperimentResult`
report the asynchronous solve. `CompileModel` resolves only after the requested
session installs initialized state or fails; a paused initialized session is a
successful completion. Retirement or supersession rejects that pending compile.
Rhai's `cmd` may return a pending command id; await `command_result(id)` for its
terminal owner result. There is no generic HTTP command-id polling endpoint,
and experiment callers must not infer run identity from a label or list order.

Queued Rhai invocations publish `CommandOutcome::Pending` at admission and a
terminal outcome only at execution or owner retirement. Test cancellation
through `command_result(id)` as well as the original transport response.
Synchronous admission failures must return on the original request even when
no work was queued. See the [deferred response contract](../../docs/architecture/12-api.md#deferred-command-responses).

### Loading a scene or model

Choose the command that owns the address type and check its result:

| command | takes | notes |
|---|---|---|
| `OpenTwin` | a **folder** containing `twin.toml` | loads `[usd] default_scene` when the effective scene-loading setting enables it |
| `LoadScene` | `lunco://` or stable `twin://<source-identity>/…` | mounts a scene address; internal mount authorities are rejected |
| `OpenFile` | a filesystem path or supported URI | extension-routes the document to its owning domain; USD paths resolve their Twin root |

Passing the `.usda` *file* to `OpenTwin` fails the `twin.toml` check and is
refused with a `warn!`.

`LoadScene` accepts `lunco://…` or a stable logical-source address in the form
`twin://<source-identity>/…`. Internal mount authorities are rejected even
while live. Bare and absolute filesystem paths are refused with

```
[scene] `…` is not a root-qualified scene address — LoadScene takes `lunco://…` or a stable `twin://<source-identity>/…`
```

The command returns a terminal rejection before admission; the currently mounted
scene remains active. Read the command result and query the active scene before
trusting a screenshot. Use `OpenFile`
for a filesystem path; it resolves the workspace layer and preserves the
document-first mounting contract.

`CaptureScreenshot` returns the PNG as the **response body**; write those bytes
yourself rather than relying on `save_to_file`.

### Validate an asset without loading it

`ValidateAsset` prepares fresh file facts without mounting a scene. Its initial
query returns `pending` with an `operation_id`; poll the same query with only
that ID. The consumed `ready` result contains `report` and actual
`source_revisions`; `failed` contains a terminal diagnostic. Retired or consumed
IDs reject. Do not resubmit the initial path while waiting.

```bash
curl -s -X POST http://127.0.0.1:4101/api/commands \
  -H "Content-Type: application/json" \
  -d '{"type":"ExecuteCommand","command":"ValidateAsset","params":{"path":"lunco://models/LunCo/Electrical/Battery.mo"}}'
```

The native CLI uses the same validators without constructing an app:

```bash
"$LUNCOSIM_BIN" --validate assets/models/LunCo/Electrical/Battery.mo
```

Full runbook — per-extension checks, exit codes, and the CWD path-resolution
trap: [`validate-assets`](../validate-assets/SKILL.md).

### Validate a Twin namespace without loading a scene

`ValidateTwin` is the read-only Twin-wide counterpart. Pass an explicit local
folder and use `policy: "error"` in CI when a resolver collision must fail:

```bash
curl -s -X POST http://127.0.0.1:4101/api/commands \
  -H "Content-Type: application/json" \
  -d '{"type":"ExecuteCommand","command":"ValidateTwin","params":{"path":"/work/rover-twin","policy":"error"}}'
```

Poll the returned `operation_id`; `ready.report` contains indexed entries,
resolver scopes, collisions, source-read errors, and namespace findings. For a
mounted browser Twin pass its stable `twin://<source-identity>` address instead
of a native folder. For the active Twin after `OpenFolder`/`OpenTwin`, use
`cmd("RunLint", #{scope: "twin", policy: "warn"})` and read
`query("GetDiagnostics", #{scope: "twin"})` for the returned lint revision.
The queued Ack is admission information; the scope's pending/ready/failed state
is the terminal report. Native and mounted browser Twin lint share the same
async preparation. Unreadable or invalid sources fail the scope even with
`policy: "warn"`; retirement or supersession discards the exact operation.
Loaded-stage lint remains available on both platforms.

## Command ownership

This skill owns the generic API envelope, runtime lifecycle, screenshots, and
end-to-end evidence. For Modelica-specific loading, compile/run, experiment,
and plot commands, use [`run-modelica`](../run-modelica/SKILL.md); keep that
catalog in one place.

## Verification workflow

```
1. Start workbench (run_in_background:true).
2. Monitor until READY.
3. OpenFile or OpenClass to load model.
4. Wait ~3-5s for rumoca parse + projection (background tasks).
5. OpenClass or drill action if scoping to a sub-class.
6. Wait ~3-5s for the post-drill projection to land.
7. FitCanvas + sleep 1.
8. CaptureScreenshot → /tmp/foo.png.
9. Read the PNG to inspect.
10. Check the process log for lines like `[Projection] import done in Xms: N nodes M edges`.
11. Exit when done.

## Rover modeling loop: reload the live scene, then measure it

For a world-direction tracker, use the API to verify one complete coordinate
chain after reload: target vector in the mount frame, controller setpoint,
measured joint angle, and rendered boresight. Do not accept a controller's
internal `locked` state alone; it can be self-consistent with an incorrect axis
or boresight convention.

Keep one luncosim process running while iterating on a rover. Edit the USD, then
use `OpenFile` for a file-backed asset, `RestartScene` for the mounted scene, or
`ApplyUsdOp` for an in-place authored opinion. Reattach a diagnostic script with
`RunScenario`; this hot-reloads only that script. Read `ScriptInspect`,
`QueryEntity`, `rover_status`, and relevant ports while the simulation is live.

A rover test must report measured telemetry and movement, not merely compile or
compare two values at rest. Use `luncosim test` for deterministic CI verdicts,
but keep the live API check because it exercises the production reload and
command paths. Do not add a second reload command or a standalone rover test
binary.

For presentation work, establish the acceptance chain in order: builtin
raycast drive first (`DRIVETRAIN PARITY: PASS`), then the Modelica drive-law
overlay (`MODELICA DRIVE LAW: PASS`), then optional power/thermal/autonomy.
Never use a visual screenshot as a substitute for either verdict: a rover that
does not move, or one still driven by the builtin kernel after a failed Modelica
overlay, can look plausible in a parked frame.

Partial USD object/reference reload is intentionally not exposed yet. Until its
composition, connection, and Modelica-worker lifecycle are implemented as one
operation, use the full `RestartScene` reload for rover tests. A successful full
reload must re-run USD prim projection, cosim model creation/compilation, and
connection rewiring before the test verdict is trusted.

```

For a placed rover, also query the composed USD transform after reload. Check
that every authored rotation op appears in `xformOpOrder` and that the effective
heading comes from one placement layer. For a fixed solar panel, list the
composed `SolarPanel`, `Battery` and rover-root network entities, then read the
rover-root boundary ports. Presence of a panel mesh is not a power verdict: require
positive `solar_power`/panel `power_out`, a valid incidence, and battery current
or changing `soc`.

## Production tutorial tests

Tutorial acceptance belongs to the production `$LUNCOSIM_BIN` binary.
Build that binary in the worktree, run the scene-test command directly, and
capture its exit code and authored verdict. `--validate` proves only USD
parsing; a successful acknowledgement proves validation and dispatch, not that
the simulation has finished its work. A live API check must also wait for `/api/ready` to report `ready:true`,
`world_hold:false`, and `pending_count:0`.

Autopilot checks should observe the same `AcquireControl` and port-write events
as a human control sequence, plus a real movement/port predicate and the final
goal. Keep declared cosim topology separate from current samples: a connection
may resolve before the first sample, but an absent value is not a valid zero.
The complete boundary is in
[`tutorial-autopilot-and-port-contracts`](../../docs/architecture/tutorial-autopilot-and-port-contracts.md).

For source-backed program authoring, query `ListOpenDocuments` for the USD
document, dispatch `AttachProgram`, then verify `ListPorts`, `CosimStatus`, and
`GetBrokenConnections`. The production Rhai gate is:

```bash
"$LUNCOSIM_BIN" test \
  --scene scenes/tests/program_attach_command.usda --max-ticks 3000
```

Its ten assertions cover a declared Modelica participant, rejection of a source
with no port contract, its named `program_failed` readiness item, and retirement
of that item when the program is removed while its host survives.
Do not treat a prim appearing in the
scene tree or a fire-and-forget command acknowledgement as a running model.

Scene-test `_EVIDENCE` telemetry crosses the process boundary as bounded typed
`LUNCO_SCENE_TEST_EVIDENCE` JSON lines. Keep internal observations as typed maps
and arrays; emit separate owner records rather than a single run-wide Rhai
string. For exact-state reference maintenance, use
`scripts/capture_deterministic_physics_reference.py` to capture paired production
profiles into a separate candidate. All behavior and deliberate-mismatch checks
remain enabled. Require exact paired agreement and replay the maintained profiles
before accepting a reference update. The contract and capture ownership are in
[deterministic runtime boundaries](../../docs/architecture/62-deterministic-runtime-and-async-boundaries.md#scene-test-evidence-transport).

## Diagnosing common failures

- **Non-Unicode native CLI arguments**: the process rejects them with exit code
  2 before startup. Use the storage-owned file URI conversion when a native
  filesystem address must cross a Unicode command boundary.
- **Empty diagram after drill-in**: read `InspectActiveDoc` and the canvas
  projection diagnostic. The selected class and its dependencies must be in
  the shared Rumoca session. Source-root completion requests reprojection;
  unresolved or cyclic declarations are terminal snapshot errors. The palette
  cannot supply missing types or ports.
- **"Command 'X' not found or not API-accessible"**: the Event isn't
  reflect-registered. Put a shared Modelica-facing payload in
  `lunco-modelica-ui-core`; keep its observer in the owning UI package, give
  its observer the `#[on_command(X)]` attribute, and list that observer in the
  `register_commands!(...)` block in
  `crates/lunco-modelica-ui/src/ui/commands/mod.rs` (see [§ Add a command](#add-a-command)).
- **API returns 500 / silent no-op**: check `params` includes the
  empty object `{}` even for parameterless commands.
- **Projection deadline exceeded**: inspect shared source-root admission and
  engine query timing. Projection consumes an immutable declaration snapshot;
  source reads and parsing belong to the asynchronous admission owner.
- **A rebuilt binary is not visible**: replace the session through `Exit`, verify
  port 4101 is free, then start the rebuilt production binary.

## Add a command

When testing reveals a missing API surface, add the command immediately
rather than asking the user:

1. Put a shared command payload in its domain's contract crate when another
   package must emit it (for example, Modelica-facing payloads in
   `lunco-modelica-ui-core`, or shared scene-edit payloads in
   `lunco-scene-command-contracts`). Define it with `#[Command]`. Keep the
   observer in the behavior-owning package and mark it with `#[on_command(...)]`
   (both attributes come from `lunco_core`). For the Modelica UI, the observer
   file is under `crates/lunco-modelica-ui/src/ui/commands/`:
   ```rust
   use lunco_core::{Command, on_command};

   #[Command(default)]              // or `#[Command]` if you impl Default
   pub struct MyCommand { pub foo: String }

   #[on_command(MyCommand)]
   pub fn on_my_command(trigger: On<MyCommand>, mut commands: Commands) {
       let foo = trigger.event().foo.clone();
       commands.queue(move |world: &mut World| { /* ... */ });
   }
   ```
   `#[Command]` emits the `Event`/`Reflect`/`reflect(Event)` derives and
   `#[on_command]` generates the `register_type` + `add_observer` wiring —
   you don't write them by hand.
2. Add the observer fn to the `register_commands!(...)` list in
   `crates/lunco-modelica-ui/src/ui/commands/mod.rs` (use the
   `module::fn` path form, e.g. `inspect::on_my_command`).
3. Build, restart workbench, curl it.

## What NOT to do

- Don't `pkill -f lunica`. The user has to confirm; use
  `Exit` command.
- Don't write standalone test binaries / temp `.rs` files to verify
  rumoca behaviour. Add an `Inspect*` command if the workbench can't
  already surface what you need.
- Don't chain `sleep 30 && tail ...`. Use Monitor with an `until` loop.
- Don't ask the user to take a screenshot or check anything visually
  unless API verification is genuinely impossible.

### Native mouse look

Before synthetic keyboard editing, compose `InjectWindowInput` with
`Focus { focused: true }` and the pointer click. This delivers logical focus to
Bevy/egui through `WindowFocused` and the Window state, mirroring Winit's event
fan-out; it does not activate the operating-system window. Focus loss uses
`focused: false`. This makes keyboard tests independent of desktop activation
policy; the AT-SPI driver separately checks the actual OS accessibility route.
Physical-key `text` is printable input, not a paste operation: bevy_egui ignores
character strings containing control characters. Compose Enter/Tab key events
separately rather than putting a newline or tab into the character string.


`InjectWindowInput` distinguishes absolute `PointerMove { x, y }` from raw
relative `MouseMotion { delta_x, delta_y }`. Cursor coordinates drive picking
and egui; raw motion drives the native camera input map. For mouse look, hold
the configured `input_binding("look_button")`, emit raw motion, and release the
button. Cursor positioning alone does not rotate a camera. The bridge emits
both the native `WindowEvent::MouseMotion` and typed Bevy `MouseMotion` message.

For path interoperability, run the production `twin_search_paths` scene gate:
it exercises layer/Twin search precedence and imports, tool discovery, and
timeline discovery with literal `#`, `%`, and spaces in filenames. Distinguish
Linux runtime evidence from Windows-native CI tests. Root resolution and
application builders are fallible; an invalid `LUNCO_ASSET_ROOT` must exit with
a diagnostic rather than panic or silently discover another library.

`python scripts/api/test_path_interoperability.py` uses an owned windowed
production session on `LUNCOSIM_API_PORT` (default 4193) and a fresh temporary
Twin below `target/`. Its Rhai observer verifies Modelica documents through
literal filenames, canonical-root and case-only renames, rejected existing or
nonportable targets, and save/readback at the renamed path. It authors a USD
document through typed document operations, saves it with a literal filename,
and admits it through the Twin's default scene to verify its Modelica source
equation and loaded canonical stage. API `Exit` must release both the process
and port.

The scene wrapper supplies the maintained deterministic-physics reference to
each headless run. Override its path with `LUNCOSIM_DETERMINISM_REFERENCE`; a
missing reference is a harness error. Keep exact-reference mismatches visible.
For one telemetry channel, use `ListTelemetryChannels {name}` before querying
its retained history instead of materializing the complete catalog in Rhai.
An intermediate milestone must not emit a terminal PASS payload when the
observer still owes later assertions. Publish milestone facts as structured
data and reserve the terminal verdict for the complete gate.

Resolve authored camera and avatar probes through their exact USD path. A retired
application camera can retain its presentation name while its viewport role has
ended; a display-name scan does not identify the current scene's avatar.

For gizmo acceptance, inject pointer events through the production input API. Both
the picking backend and transform frontend consume Bevy `PointerLocation`; do not
move the OS cursor or mutate the native `Window` to make a test gesture work.

### Simulation lifecycle notices

Use `python3 scripts/api/test_simulation_lifecycle.py --output <evidence-dir>`
with `LUNCOSIM_BIN` set to the production binary. The retained application
observer checks 11 transport and teardown assertions while paused and after
scene replacement; `--windowed` also captures the terminal presentation. The
fresh-host observer waits for its first admitted simulation tick before the
initial clear; presentation work can start while scene admission is pending.
The four `SIMULATION_*` Info channels describe actual start, user pause/unpause and
scene stop. Readiness/solver/manual holds are separate facts, and rejected or
idempotent transport requests must not create additional lifecycle events.

For terminal runtime failures, inspect `GetReadiness.fault` even when
`RuntimeDiagnostics.errors` is zero: they are distinct owners. A windowed
negative fixture must also show the first fault's subject, kind, and original
cause in the visible `Simulation stopped` Error in Recent Events. The presentation
bridge publishes once per scene and resets with scene history.

`python3 scripts/api/test_fixed_step_assertions.py --port <free-port> --output <directory>`
checks six authored failure assertions in a windowed production session and
captures Recent Events. It supplies an invalid parameter to the shared rover
guidance model with fixed RK4: the original Modelica assertion must reach the
startup diagnostic, the failed participant must stay at time zero, and the
application must remain available. Pair it with the solver's focused
`fixed_step` integration target and the affected Twin's loading/control gates.

`python3 scripts/api/test_vehicle_program_outputs.py --port <free-port> --output <directory>`
checks eleven authored assertions on a mobility root with a direct Modelica
program. Its declared output starts at zero in USD while the checked solver
produces positive inertia. Require the wire to retain the program prim and port,
and physics to receive the solver observation. The negative case deliberately
produces zero inertia: binding must reject it with source/sink context, preserve
the body's previous inertia, and keep the application available. Pair this gate
with the affected Twin's reopen/control acceptance.

For co-located Modelica and native vehicle facets, run
`python3 scripts/api/test_native_vehicle_projection.py --port <free-port> --twin <path> --subject-path <prim> --minimum-support-contacts <count> --output <directory>`.
Its six authored checks require clear readiness, an advancing model, complete
native body admission, real wheel-support probes, and current support samples.
Require the footprint count appropriate to the authored raycast vehicle; model
startup alone does not prove the native facet was projected.

### Native solver-profile advisory

Use `scripts/api/test_physics_solver_profile.py --port <free-port> --log <path>`
with `LUNCOSIM_BIN` pointing to the production executable. Its authored Rhai
observer uses `GetDiagnostics {scope: "physics"}` and the native status event to
verify high substeps remain enabled, error severity reaches the Recent Events
feed once, restoration clears current findings, and invalid values preserve the
admitted setting. The driver owns its window/session and captures the high
profile before restoring eight. `RunLint {domain: "physics"}` refreshes the same
owner report; it does not change the solver setting.

For UI editor regressions, use `InspectWorkbench.rendered_panels` to prove actual
presentation and `InspectBehaviourEditor` for draft retention and compile/admission
state. A draft-run acknowledgement does not prove compilation, document authoring,
or disk save. `ExportText` likewise acknowledges an immutable export request;
wait for its terminal Export status and read back the destination bytes.

Use `scripts/api/test_stable_asset_references.py --port <owned-free-port>` for
script metadata, catalog remount IDs and disposable-Twin shader source commands.
Shader journal paths stay stable while their document/undo state retires with the
exact Twin root. Native load addresses must not enter API responses or saved USD.

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in testing →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.