Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Agents and scripts: the material card checks describe their exact parameters and reply (#11036) (#11037)

austin62jakee06d6e36d86e
diff --git a/crates/engine/src/cmd/material_properties.rs b/crates/engine/src/cmd/material_properties.rs
index 7e595ccca9..d4fa9df339 100644
--- a/crates/engine/src/cmd/material_properties.rs
+++ b/crates/engine/src/cmd/material_properties.rs
@@ -1,15 +1,24 @@
//! Read-only validation of candidate engineering data; no assignment or simulation.
use super::CommandSpec;
use crate::params::bad;
+use crate::schema::material_properties::{CardModulus, CardValidated, DirectionalModulusParams, ValidateCardParams};
+use crate::schema::{TypedContract, output_schema_for};
use crate::{Result, Session};
-use serde_json::{Value, json};
+use serde_json::Value;
-pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("material.properties.validate", "Validate Physical Material Data", validate)
+const VALIDATE_CONTRACT: TypedContract<ValidateCardParams> = TypedContract::new();
+const DIRECTIONAL_CONTRACT: TypedContract<DirectionalModulusParams> = TypedContract::new();
+
+pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("material.properties.validate", "Validate Physical Material Data", crate::checked!("material.properties.validate", validate))
.icon("material")
.noundo()
.doc_only()
+ .contract(&VALIDATE_CONTRACT)
+ .output(output_schema_for::<CardValidated>)
.params("card: schema_version 1 engineering material card in SI units. Returns numerical consistency, derived isotropic moduli, missing conditions and sources needing review. Read-only; does not assign/save properties or provide an analysis solver. See docs/physical-material-cards.md"),
- CommandSpec::new("material.properties.directional", "Directional Elastic Modulus", directional).icon("material").noundo().doc_only()
+ CommandSpec::new("material.properties.directional", "Directional Elastic Modulus", crate::checked!("material.properties.directional", directional)).icon("material").noundo().doc_only()
+ .contract(&DIRECTIONAL_CONTRACT)
+ .output(output_schema_for::<CardModulus>)
.params("card: schema_version 1 engineering material card; direction: three finite nonzero-vector components in the card's material-local axes. Returns normalized direction, Young modulus in Pa and source/condition review. Read-only constitutive query; no structural solver, persistence or body-axis assignment. See docs/physical-material-cards.md")];
fn directional(_: &mut Session, params: &Value) -> Result<Value> {
@@ -28,7 +37,7 @@ fn directional(_: &mut Session, params: &Value) -> Result<Value> {
let direction = [component(0)?, component(1)?, component(2)?];
let card = solidcraft_doc::physical_material::admit_card(value).map_err(|e| bad(cmd, e.to_string()))?;
let response = card.directional_modulus(direction).map_err(|e| bad(cmd, e.to_string()))?;
- serde_json::to_value(response).map_err(|e| bad(cmd, e.to_string()))
+ serde_json::to_value(CardModulus::from(response)).map_err(|e| bad(cmd, e.to_string()))
}
fn validate(_: &mut Session, params: &Value) -> Result<Value> {
@@ -38,13 +47,15 @@ fn validate(_: &mut Session, params: &Value) -> Result<Value> {
.ok_or_else(|| bad("material.properties.validate", "expected {card: ...}"))?;
let card = object.get("card").ok_or_else(|| bad("material.properties.validate", "missing card"))?;
let result = solidcraft_doc::physical_material::validate_card(card).map_err(|e| bad("material.properties.validate", e.to_string()))?;
- Ok(json!({"valid":true,"validation":result}))
+ let reply = CardValidated { valid: true, validation: result.into(), param_warnings: Vec::new() };
+ serde_json::to_value(reply).map_err(|e| bad("material.properties.validate", e.to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::doc::Document;
+ use serde_json::json;
use std::sync::Arc;
fn card() -> Value {
diff --git a/crates/engine/src/schema/material_properties.rs b/crates/engine/src/schema/material_properties.rs
new file mode 100644
index 0000000000..b04e1e017b
--- /dev/null
+++ b/crates/engine/src/schema/material_properties.rs
@@ -0,0 +1,184 @@
+//! Contracts and result types for the commands in `cmd/material_properties.rs`: checking an
+//! engineering material card, and its elastic modulus in a direction (#11036).
+
+use std::borrow::Cow;
+use std::collections::BTreeMap;
+
+use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
+use serde::de::Error as _;
+use serde::{Deserialize, Deserializer, Serialize};
+use serde_json::Value;
+use solidcraft_doc::physical_material::{DirectionalModulus, IsotropicModuli, MaterialAxes, Validation};
+
+use super::check::whole;
+
+/// Check an engineering material card: its numbers' consistency, the isotropic moduli they
+/// imply, and the conditions and sources still to review. Read-only: nothing is assigned or
+/// saved, and there is no analysis solver.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct ValidateCardParams {
+ #[schemars(schema_with = "card_schema")]
+ pub card: Value,
+}
+
+/// The Young modulus of an engineering material card in one direction, in the card's own
+/// material axes. Read-only: no load case or structural solver.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct DirectionalModulusParams {
+ #[schemars(schema_with = "card_schema")]
+ pub card: Value,
+ pub direction: CardDirection,
+}
+
+/// The card, checked by the handler (`admit_card`), with its messages.
+fn card_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "A schema_version 1 engineering material card in SI units (see docs/physical-material-cards.md).",
+ "type": "object"
+ })
+}
+
+/// A direction in the card's material axes: three numbers, not all zero, with the handler's
+/// messages.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct CardDirection(pub [f64; 3]);
+
+impl<'de> Deserialize<'de> for CardDirection {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let v = Value::deserialize(d)?;
+ let a =
+ v.as_array().filter(|a| a.len() == 3).ok_or_else(|| D::Error::custom(whole("direction: expected exactly three numeric components")))?;
+ let c = |i: usize| a.get(i).and_then(Value::as_f64).ok_or_else(|| D::Error::custom(whole("direction: expected numeric components")));
+ Ok(CardDirection([c(0)?, c(1)?, c(2)?]))
+ }
+}
+
+impl JsonSchema for CardDirection {
+ fn schema_name() -> Cow<'static, str> {
+ "CardDirection".into()
+ }
+ fn inline_schema() -> bool {
+ true
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "A direction in the card's material axes: three numbers, not all zero.",
+ "type": "array",
+ "items": {"type": "number"},
+ "minItems": 3,
+ "maxItems": 3
+ })
+ }
+}
+
+/// What `material.properties.validate` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct CardValidated {
+ /// Always true: a card that isn't valid is refused.
+ pub valid: bool,
+ pub validation: CardValidation,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// What `material.properties.directional` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct CardModulus {
+ /// The direction, made a unit vector.
+ pub direction: [f64; 3],
+ /// The card's material axes, when it has directional properties.
+ pub axes: Option<CardAxes>,
+ /// The Young modulus in that direction (Pa).
+ pub young_modulus_pa: f64,
+ pub validation: CardValidation,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+impl From<DirectionalModulus> for CardModulus {
+ fn from(m: DirectionalModulus) -> Self {
+ let DirectionalModulus { direction, axes, young_modulus_pa, validation } = m;
+ CardModulus { direction, axes: axes.map(CardAxes::from), young_modulus_pa, validation: validation.into(), param_warnings: Vec::new() }
+ }
+}
+
+/// A card's material axes.
+#[derive(Clone, Copy, Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum CardAxes {
+ /// The material's own axes 1, 2 and 3.
+ Material123,
+ /// Wood's longitudinal, radial and tangential axes.
+ WoodLrt,
+}
+
+impl From<MaterialAxes> for CardAxes {
+ fn from(a: MaterialAxes) -> Self {
+ match a {
+ MaterialAxes::Material123 => CardAxes::Material123,
+ MaterialAxes::WoodLrt => CardAxes::WoodLrt,
+ }
+ }
+}
+
+/// What checking a card found.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct CardValidation {
+ pub schema_version: u32,
+ /// The kinds of property the card gives.
+ pub property_kinds: Vec<String>,
+ /// The shear and bulk moduli an isotropic card's numbers imply.
+ pub isotropic_moduli: Option<CardModuli>,
+ /// The property kinds given without every condition they hold at (temperature, state, and
+ /// moisture for wood or strain rate for polymers).
+ pub unspecified_conditions: Vec<String>,
+ /// Per property kind: the condition fields it lacks.
+ pub missing_condition_fields: BTreeMap<String, Vec<String>>,
+ /// The sources the card's properties cite, which still need review.
+ pub source_review_required: Vec<String>,
+ /// Always false: there is no analysis solver.
+ pub analysis_solver_available: bool,
+ /// Always false: a card holds no rendering properties.
+ pub rendering_properties_available: bool,
+}
+
+impl From<Validation> for CardValidation {
+ fn from(v: Validation) -> Self {
+ // In full, so a field added to `Validation` fails here rather than going missing.
+ let Validation {
+ schema_version,
+ property_kinds,
+ isotropic_moduli,
+ unspecified_conditions,
+ missing_condition_fields,
+ source_review_required,
+ analysis_solver_available,
+ rendering_properties_available,
+ } = v;
+ CardValidation {
+ schema_version,
+ property_kinds,
+ isotropic_moduli: isotropic_moduli.map(|IsotropicModuli { shear_pa, bulk_pa }| CardModuli { shear_pa, bulk_pa }),
+ unspecified_conditions,
+ missing_condition_fields,
+ source_review_required,
+ analysis_solver_available,
+ rendering_properties_available,
+ }
+ }
+}
+
+/// The isotropic moduli a card's numbers imply.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct CardModuli {
+ pub shear_pa: f64,
+ pub bulk_pa: f64,
+}
+
+#[cfg(test)]
+#[path = "material_properties_tests.rs"]
+mod tests;
diff --git a/crates/engine/src/schema/material_properties_tests.rs b/crates/engine/src/schema/material_properties_tests.rs
new file mode 100644
index 0000000000..810460eb0d
--- /dev/null
+++ b/crates/engine/src/schema/material_properties_tests.rs
@@ -0,0 +1,58 @@
+use serde_json::{Value, json};
+
+use super::{CardModulus, CardValidated, DirectionalModulusParams, ValidateCardParams};
+use crate::Session;
+use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
+use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
+
+/// An isotropic card, as the command's own tests write one.
+fn card() -> Value {
+ json!({"schema_version":1,"designation":"Original synthetic card, not design data","family":"other",
+ "sources":[{"id":"fixture","title":"Original analytic constants","kind":"illustrative","license":"MIT OR Apache-2.0"}],
+ "properties":[{"source_id":"fixture","conditions":{"temperature_k":293.15,"state":"synthetic"},
+ "data":{"kind":"density","kg_m3":700.0}},
+ {"source_id":"fixture","data":{"kind":"elasticity","model":{
+ "symmetry":"isotropic","young_modulus_pa":12.25e9,"poisson_ratio":0.25}}}]})
+}
+
+#[test]
+fn schemas_and_the_key_check_agree() {
+ assert_keys(input_schema_for::<ValidateCardParams>(), &["card"]);
+ assert_keys(input_schema_for::<DirectionalModulusParams>(), &["card", "direction"]);
+}
+
+#[test]
+fn strict_keeps_todays_errors() {
+ assert_strict_keeps_todays_errors(&[
+ ("material.properties.validate", json!({"card": {}})),
+ ("material.properties.validate", json!({"card": null})),
+ ("material.properties.directional", json!({"card": {}, "direction": [1, 0, 0]})),
+ ("material.properties.directional", json!({"card": card(), "direction": [1, 0]})),
+ ("material.properties.directional", json!({"card": card(), "direction": "x"})),
+ ("material.properties.directional", json!({"card": card(), "direction": [1, "a", 0]})),
+ ("material.properties.directional", json!({"card": card(), "direction": [0, 0, 0]})),
+ ]);
+}
+
+/// #11036: both commands reply as their output schemas say, in Warn without warnings. Like the
+/// handlers, warn and strict refuse a key they don't take, so no reply carries a warning.
+#[test]
+fn card_commands_reply_with_their_schemas() {
+ let (validated, modulus) = (output_schema_for::<CardValidated>(), output_schema_for::<CardModulus>());
+ let matches = |schema: &schemars::Schema, r: &Value| {
+ let schema = schema.as_value();
+ assert!(conforms(schema, schema, r), "{r} doesn't match {schema}");
+ assert!(r.get("param_warnings").is_none(), "{r}");
+ };
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ let r = s.execute("material.properties.validate", &json!({"card": card()})).unwrap_or_else(|e| panic!("{e}"));
+ matches(&validated, &r);
+ assert!(r["valid"] == true && r["validation"]["isotropic_moduli"]["shear_pa"].is_number(), "{r}");
+ let r = s.execute("material.properties.directional", &json!({"card": card(), "direction": [1, 1, 0]})).unwrap_or_else(|e| panic!("{e}"));
+ matches(&modulus, &r);
+ assert!(r["axes"].is_null() && (r["young_modulus_pa"].as_f64().unwrap_or(0.0) - 12.25e9).abs() < 1.0, "{r}");
+ for level in [ParamCheck::Warn, ParamCheck::Strict] {
+ let mut s = Session { param_check: level, ..Session::default() };
+ assert!(s.execute("material.properties.validate", &json!({"card": card(), "crd": 1})).is_err(), "{level:?}");
+ }
+}
diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs
index 546cc80d87..a13d3c77c8 100644
--- a/crates/engine/src/schema/mod.rs
+++ b/crates/engine/src/schema/mod.rs
@@ -69,6 +69,7 @@ pub mod inspect;
pub mod joints;
pub mod libraries;
pub mod mass_properties;
+pub mod material_properties;
pub mod motion;
pub mod panels;
pub mod print_face;
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index 46d93a58a3..ea1c6f24c9 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -106,8 +106,6 @@ material.delete
material.edit
material.inspect
material.list
-material.properties.directional
-material.properties.validate
mesh.convert
motion.delete
motion.export