use commandagi::design::ontology::*;
use commandagi::design::{declare, Declared};
fn document(root: El) -> (String, Json, Json) {
match declare(root).unwrap() {
Declared::Document { format, document, sources } => (format, document, sources),
Declared::Graph(_) => panic!("a document, not a graph"),
}
}
fn bad(root: El) -> String {
declare(root).unwrap_err()
}
fn j(text: &str) -> Json {
Json::parse(text).unwrap()
}
fn site(el: &El) -> Json {
el.source_json().unwrap()
}
#[test]
fn a_world_declares_its_units_and_space_each_site_by_its_path() {
let arm = unit().uid("arm").name("arm").device("../../devices/so-101/definition.tsx").position([100, 0, 0]).rotation(90);
let arm_site = site(&arm);
let file = world([space().origin_mm([0, 0, 0]).size_mm([4000, 3000, 2500]), arm]).name("Shop");
let root_site = site(&file);
let (format, doc, sources) = document(file);
assert_eq!(format, "world");
assert_eq!(
doc,
j(r#"{"name": "Shop", "space": {"origin_mm": [0, 0, 0], "size_mm": [4000, 3000, 2500]},
"units": [{"uid": "arm", "name": "arm", "device": "../../devices/so-101/definition.tsx", "position": [100, 0, 0], "rotation": 90}]}"#)
);
assert_eq!(sources.get(""), Some(&root_site));
assert_eq!(sources.get("unit#arm"), Some(&arm_site));
assert!(sources.get("space").is_some(), "every element by its path: {}", sources.text());
assert!(bad(world([]).name("Shop").kind("physical")).contains("world().kind: a world names real things: it has no kind"));
assert!(bad(world([scene([body().id("cube")]).hz(240)]).name("Shop")).contains("scene() in a world(): a world declares no scene"));
let links = r#"[{"node": "ram", "joint": {"unit": "press-1", "channel": "axes", "name": "z", "type": "prismatic", "axis": "z", "origin_mm": [0, 0, 0], "home": 0}}]"#;
let (_, posed, _) = document(world([]).name("Press").model("press.3d.tsx").links(json(links)));
assert_eq!(posed, j(&format!(r#"{{"name": "Press", "model": "press.3d.tsx", "links": {links}, "units": []}}"#)));
let policies = r#"[{"id": "sim-control", "kind": "follow", "robot": "arm", "reality": "physical", "leader": {"unit": "arm", "run": "twin"}, "hz": 30}]"#;
let (_, followed, _) = document(world([]).name("Cell").policies(json(policies)));
assert_eq!(followed, j(&format!(r#"{{"name": "Cell", "policies": {policies}, "units": []}}"#)));
let w = |children: Vec<El>| world(children).name("W");
assert_eq!(document(world([]).name("W")).1, j(r#"{"name": "W", "units": []}"#));
assert!(bad(w(vec![unit().uid("a").name("a").device("d.json").speed(3)])).contains(r#"unit().uid("a"): speed is not read"#));
assert!(bad(w(vec![unit().uid("a").name("a").device("d"), unit().uid("a").name("b").device("d")])).contains(r#"two unit() in world() have uid "a""#));
assert!(bad(w(vec![body().id("b")])).contains("body() stands in scene(), not in world()"));
assert!(bad(w(vec![node().id("n")])).contains("node() is not an element of a world"));
let (_, shelved, _) = document(world([
group().uid("shelf").name("machine shelf").size_mm([2440, 760, 2600]).position([0, 3600, 0]).rotation(0),
group().uid("shelf-1").name("level 1").group("shelf").size_mm([2440, 760, 650]).position([0, 3600, 150]).rotation(0),
unit().uid("cnc-01").name("router").device("../../devices/cnc/definition.tsx").group("shelf-1").position([-900, 3600, 150]).rotation(0),
])
.name("Shop")
);
assert_eq!(
shelved,
j(r#"{"name": "Shop",
"groups": [{"uid": "shelf", "name": "machine shelf", "size_mm": [2440, 760, 2600], "position": [0, 3600, 0], "rotation": 0},
{"uid": "shelf-1", "name": "level 1", "group": "shelf", "size_mm": [2440, 760, 650], "position": [0, 3600, 150], "rotation": 0}],
"units": [{"uid": "cnc-01", "name": "router", "device": "../../devices/cnc/definition.tsx", "group": "shelf-1", "position": [-900, 3600, 150], "rotation": 0}]}"#)
);
assert!(bad(w(vec![group().uid("g").name("g").device("d")])).contains(r#"group().uid("g"): device is not read"#));
}
#[test]
fn a_device_definitions_channels_are_channel_elements() {
let def = device([channel()
.id("joints")
.dir("duplex")
.medium("records")
.format("servo-bus")
.transport("serial")
.limits(json(r#"{"j1": [-90, 90]}"#))
.min_interval_ms(20)])
.name("Arm")
.interface("USB serial")
.model(json(r#"{"file": "model.glb"}"#));
let (format, doc, _) = document(def);
assert_eq!(format, "device");
assert_eq!(
doc,
j(r#"{"name": "Arm", "interface": "USB serial", "model": {"file": "model.glb"},
"channels": [{"id": "joints", "dir": "duplex", "medium": "records", "format": "servo-bus", "transport": "serial", "limits": {"j1": [-90, 90]}, "minIntervalMs": 20}]}"#)
);
assert!(bad(device([]).name("A").channels(json("[]"))).contains("each channel as a channel() element"));
let (_, cnc, _) = document(device([channel().id("gcode").dir("duplex").medium("records").format("gcode-chat").rapid_mm_per_min(1000)]).name("Router"));
assert_eq!(cnc, j(r#"{"name": "Router", "channels": [{"id": "gcode", "dir": "duplex", "medium": "records", "format": "gcode-chat", "rapidMmPerMin": 1000}]}"#));
}
#[test]
fn bounds_and_interlocks_are_elements() {
let requires = r#"[{"channel": "switches", "field": "home", "eq": true}]"#;
let (_, def, _) = document(
device([
channel().id("gate").dir("duplex").medium("records").format("json-records"),
channel().id("switches").dir("out").medium("records").format("json-records"),
bound().channel("gate").field("lift").min(0).max(420).max_rate(200),
interlock().name("gate-closes-only-with-shuttle-home").channel("gate").when(json(r#"{"field": "lift", "lt": 420}"#)).requires(json(requires)).why("the gate would close on the tray"),
])
.name("Hatch"),
);
assert_eq!(
def,
j(r#"{"name": "Hatch",
"channels": [{"id": "gate", "dir": "duplex", "medium": "records", "format": "json-records", "bounds": [{"field": "lift", "min": 0, "max": 420, "maxRate": 200}]},
{"id": "switches", "dir": "out", "medium": "records", "format": "json-records"}],
"interlocks": [{"name": "gate-closes-only-with-shuttle-home", "channel": "gate", "when": {"field": "lift", "lt": 420}, "requires": [{"channel": "switches", "field": "home", "eq": true}], "why": "the gate would close on the tray"}]}"#)
);
assert!(bad(device([bound().channel("x").field("f").max(1)]).name("A")).contains("is not a channel() of this device"));
let (_, w, _) = document(
world([unit().uid("tray").name("tray").device("d"), interlock().name("shuttle-needs-hatch-open").unit("tray").channel("shuttle").requires(json(r#"[{"unit": "hatch", "channel": "gate", "field": "open", "eq": true}]"#)).why("the tray would strike the gate")])
.name("Unit")
,
);
assert_eq!(w.get("interlocks").and_then(|l| if let Json::Arr(l) = l { l[0].get("unit").cloned() } else { None }), Some(Json::Str("tray".into())));
}
#[test]
fn a_definition_names_its_firmware_and_a_firmware_declares_its_channels() {
let cam = || channel().id("cam").dir("out").medium("video").format("video");
let (_, def, _) = document(device([cam()]).name("Cam").firmware("../../firmware/cam").revision("rev-a"));
assert_eq!(def, j(r#"{"name": "Cam", "firmware": "../../firmware/cam", "revision": "rev-a", "channels": [{"id": "cam", "dir": "out", "medium": "video", "format": "video"}]}"#));
let (format, fw, _) = document(commandagi::design::firmware::firmware([commandagi::design::firmware::supports().revision("rev-a"), cam()]).name("cam"));
assert_eq!(format, "firmware");
assert_eq!(fw, j(r#"{"name": "cam", "supports": [{"revision": "rev-a"}], "channels": [{"id": "cam", "dir": "out", "medium": "video", "format": "video"}]}"#));
}
#[test]
fn a_dashboards_layout_is_nested_splits_of_panes_its_params_and_regions_elements() {
let file = dashboard([
param().id("unit").type_("unit"),
split([pane().id("a").kind("world").world("${unit.world}"), pane().id("b").kind("devices").theater(true)]).axis("x").ratio(0.5),
region().side("left").tab("nav"),
])
.name("cockpit")
.focus("b");
let (format, doc, sources) = document(file);
assert_eq!(format, "dashboard");
assert_eq!(
doc,
j(r#"{"format": "commandagi-dashboard", "name": "cockpit", "focus": "b", "params": [{"id": "unit", "type": "unit"}],
"layout": {"kind": "split", "axis": "x", "ratio": 0.5, "children": [{"kind": "leaf", "paneId": "a"}, {"kind": "leaf", "paneId": "b"}]},
"panes": {"a": {"kind": "world", "world": "${unit.world}"}, "b": {"kind": "devices", "theater": true}},
"regions": {"left": {"tab": "nav"}}}"#)
);
let keys: Vec<&str> = match &sources {
Json::Obj(e) => e.iter().map(|(k, _)| k.as_str()).collect(),
_ => vec![],
};
assert_eq!(keys, ["", "param#unit", "split@0", "split@0/pane#a", "split@0/pane#b", "region#left"]);
assert!(bad(dashboard([split([pane().id("a")]).axis("x").ratio(0.5)]).name("x")).contains("a split() has two sides"));
assert!(bad(dashboard([pane().id("a"), pane().id("b")]).name("x")).contains("has one layout"));
let (_, live, _) = document(dashboard([pane().id("live").kind("files").with_attr("repeat", "live-stream")]).name("everything live"));
assert_eq!(
live,
j(r#"{"format": "commandagi-dashboard", "name": "everything live", "layout": {"kind": "leaf", "paneId": "live"},
"panes": {"live": {"kind": "files", "repeat": "live-stream"}}}"#)
);
assert!(bad(dashboard([pane().id("live").kind("files").with_attr("repeat", "runs")]).name("x")).contains("repeat is \"live-stream\""));
assert!(bad(dashboard([pane().id("live").kind("files").with_attr("repeat", "live-stream").with_attr("selected", "runs/r/run.json")]).name("x")).contains("names no file of its own"));
assert!(bad(dashboard([pane().id("live").kind("devices").with_attr("repeat", "live-stream")]).name("x")).contains("shows files"));
}
trait Theater {
fn theater(self, v: impl Into<Value>) -> El;
}
impl Theater for El {
fn theater(self, v: impl Into<Value>) -> El {
self.with_attr("theater", v)
}
}
#[test]
fn a_geo_projects_date_range_and_camera_are_elements() {
let (format, doc, _) =
document(geoproject([date_range().start("2015-01").end("2030-01"), camera().center_lng(40).center_lat(25).scale(320)]).id("p1").name("Chokepoints"));
assert_eq!(format, "geo");
assert_eq!(
doc,
j(r#"{"type": "geoeconomics/project", "schemaVersion": "1.0", "id": "p1", "name": "Chokepoints",
"data": {"defaultDateRange": {"start": "2015-01", "end": "2030-01"}, "defaultCamera": {"centerLng": 40, "centerLat": 25, "scale": 320}}}"#)
);
}
#[test]
fn a_geo_projects_shock_scenario_model_and_parameter_set_are_their_envelopes() {
let (format, doc, _) =
document(shock([]).id("closure").name("Hormuz closure").event_type("route-disruption").targets(json(r#"["cp-hormuz"]"#)).start("2028-03").magnitude(0.7));
assert_eq!(format, "shock");
assert_eq!(
doc,
j(r#"{"type": "geoeconomics/event", "schemaVersion": "1.0", "id": "closure", "name": "Hormuz closure",
"data": {"eventType": "route-disruption", "targets": ["cp-hormuz"], "start": "2028-03", "magnitude": 0.7}}"#)
);
let (_, scen, _) = document(
scenario([]).id("s").name("Hormuz").baseline_date("2028-03").events(json(r#"["./shocks/closure.shock.rs"]"#)).models(json(r#"["models/commodity-shock.geomodel.rs"]"#)),
);
assert_eq!(scen, j(r#"{"type": "geoeconomics/scenario", "schemaVersion": "1.0", "id": "s", "name": "Hormuz",
"data": {"baselineDate": "2028-03", "events": ["./shocks/closure.shock.rs"], "models": ["models/commodity-shock.geomodel.rs"]}}"#));
let (_, model, _) = document(
geomodel([parameter().name("priceElasticity").default(0.2).min(0.05).max(0.6)]).id("m").name("Commodity shock").runtime("commodity-shock").version("1.0"),
);
assert_eq!(model, j(r#"{"type": "geoeconomics/model", "schemaVersion": "1.0", "id": "m", "name": "Commodity shock",
"data": {"runtime": "commodity-shock", "version": "1.0", "parameterSchema": {"priceElasticity": {"default": 0.2, "min": 0.05, "max": 0.6}}}}"#));
let (_, params, _) = document(geoparams([]).id("p").name("Severe").for_model("commodity-shock").values(json(r#"{"priceElasticity": 0.25}"#)));
assert_eq!(params, j(r#"{"type": "geoeconomics/params", "schemaVersion": "1.0", "id": "p", "name": "Severe",
"data": {"forModel": "commodity-shock", "values": {"priceElasticity": 0.25}}}"#));
}
#[test]
fn a_geo_projects_layer_formula_view_report_and_graph_are_their_envelopes() {
let scale = r##"{"kind": "linear", "ramp": [{"t": 0, "color": "#e9e9ec"}, {"t": 1, "color": "#141418"}]}"##;
let (format, layer, _) = document(
geolayer([reference().role("source").path("datasets/energy/throughput.dataset")])
.id("l")
.name("chokepoints")
.renderer("point")
.category("Energy")
.source_dataset("datasets/energy/throughput.dataset")
.scale(json(scale))
.opacity(1)
.units("mb/d"),
);
assert_eq!(format, "geolayer");
assert_eq!(
layer,
j(r##"{"type": "geoeconomics/layer", "schemaVersion": "1.0", "id": "l", "name": "chokepoints",
"references": [{"role": "source", "path": "datasets/energy/throughput.dataset"}],
"data": {"renderer": "point", "category": "Energy", "sourceDataset": "datasets/energy/throughput.dataset",
"scale": {"kind": "linear", "ramp": [{"t": 0, "color": "#e9e9ec"}, {"t": 1, "color": "#141418"}]}, "opacity": 1, "units": "mb/d"}}"##)
);
let (_, formula, _) = document(geoformula([]).id("f").name("output-per-gdp").inputs(json(r#"{"gdp": "datasets/gdp.dataset"}"#)).expression("1 / gdp").output_unit("share").missing_value("skip"));
assert_eq!(formula, j(r#"{"type": "geoeconomics/formula", "schemaVersion": "1.0", "id": "f", "name": "output-per-gdp",
"data": {"inputs": {"gdp": "datasets/gdp.dataset"}, "expression": "1 / gdp", "outputUnit": "share", "missingValue": "skip"}}"#));
let (_, view, _) = document(geoview([]).id("v").name("global-energy").camera(json(r#"{"centerLng": 45, "centerLat": 25, "scale": 340}"#)).enabled_layers(json(r#"["layers/energy/oil.geolayer.rs"]"#)));
assert_eq!(view, j(r#"{"type": "geoeconomics/view", "schemaVersion": "1.0", "id": "v", "name": "global-energy",
"data": {"camera": {"centerLng": 45, "centerLat": 25, "scale": 340}, "enabledLayers": ["layers/energy/oil.geolayer.rs"]}}"#));
let (_, report, _) = document(georeport([]).id("r").name("impact").blocks(json(r##"[{"kind": "markdown", "text": "# Impact"}]"##)));
assert_eq!(report, j(r##"{"type": "geoeconomics/report", "schemaVersion": "1.0", "id": "r", "name": "impact", "data": {"blocks": [{"kind": "markdown", "text": "# Impact"}]}}"##));
let (_, graph, _) = document(geograph([]).id("g").name("links").nodes(json(r#"[{"id": "a", "label": "A"}]"#)).edges(json(r#"[{"from": "a", "to": "a"}]"#)));
assert_eq!(graph, j(r#"{"type": "geoeconomics/graph", "schemaVersion": "1.0", "id": "g", "name": "links",
"data": {"nodes": [{"id": "a", "label": "A"}], "edges": [{"from": "a", "to": "a"}]}}"#));
}
#[test]
fn a_node_graph_is_the_editors_op_graph_with_wires_into_ports_and_the_literal_kept() {
let g = node().id("g").type_("gradient").x(40).y(80).shade_a(40);
let into_b = wire().from("g:out").to("b:in");
let (g_site, w_site) = (site(&g), site(&into_b));
let file = opgraph([
g,
node().id("b").type_("blur").x(300).y(80).radius(6).output(true),
node().id("m").type_("mix").inputs(json(r#"{"layers.2": null}"#)),
into_b,
wire().from("g:out").to("b:radius"),
wire().from("b:out").to("m:layers.1"),
])
.name("Mix");
let Declared::Graph(graph) = declare(file).unwrap() else { panic!("a node graph is a graph") };
let want = j(&format!(
r#"{{"id": "nodegraph", "nodes": {{
"g": {{"id": "g", "type": "gradient", "inputs": {{"shadeA": 40}}, "meta": {{"x": 40, "y": 80, "source": {g}}}}},
"b": {{"id": "b", "type": "blur", "inputs": {{"radius": {{"wire": {{"node": "g", "port": "out"}}, "value": 6}}, "in": {{"wire": {{"node": "g", "port": "out"}}}}}},
"meta": {{"x": 300, "y": 80, "source": {b}, "sources": {{"wire:in": {w}, "wire:radius": {r}}}}}}},
"m": {{"id": "m", "type": "mix", "inputs": {{"layers.2": null, "layers.1": {{"wire": {{"node": "b", "port": "out"}}}}}}, "meta": {{"source": {m}, "sources": {{"wire:layers.1": {l}}}}}}}}},
"outputs": ["b"], "meta": {{"name": "Mix", "domain": "nodegraph"}}}}"#,
g = g_site.text(),
w = w_site.text(),
b = graph.get("nodes").and_then(|n| n.get("b")).and_then(|n| n.get("meta")).and_then(|m| m.get("source")).unwrap().text(),
r = graph.get("nodes").and_then(|n| n.get("b")).and_then(|n| n.get("meta")).and_then(|m| m.get("sources")).and_then(|s| s.get("wire:radius")).unwrap().text(),
m = graph.get("nodes").and_then(|n| n.get("m")).and_then(|n| n.get("meta")).and_then(|m| m.get("source")).unwrap().text(),
l = graph.get("nodes").and_then(|n| n.get("m")).and_then(|n| n.get("meta")).and_then(|m| m.get("sources")).and_then(|s| s.get("wire:layers.1")).unwrap().text(),
));
assert_eq!(graph, want);
assert!(bad(opgraph([node().id("a").type_("t").inputs(json(r#"{"radius": 1}"#))])).contains("write radius as a method"));
assert!(bad(opgraph([node().id("a").type_("t"), wire().from("a:out").to("z:in")])).contains(r#"no node().id("z")"#));
assert!(bad(opgraph([node().id("a").type_("t"), wire().from("a").to("a:in")])).contains(r#""node:port""#));
assert!(bad(opgraph([node().id("a").type_("t"), wire().from("a:out").to("a:in"), wire().from("a:out").to("a:in")])).contains("have to"));
assert!(bad(opgraph([node().id("a:b").type_("t")])).contains("an id has no colon"));
}