# Command schemas Every command has an input schema and an output schema (JSON Schema 2020-12), generated by `schemars` from two Rust types: - a **contract**: the parameters type, checked in front of the handler (see `crates/engine/src/schema/mod.rs`); with the session's check level at warn or strict, a misspelt key or a wrong-typed value is reported or refused instead of silently ignored; - a **reply type**: what a successful call returns. `engine.describe` and the MCP tool `describe_command` serve both, so agents and scripts read a command's exact parameters instead of guessing from prose. ## When the check fails The tests in `crates/engine/src/schema/coverage_tests.rs` say what to do. A command without schemas is only a warning for now (the test prints the list); it will become required once the PR backlog is down, so give new commands both schemas now. Set `SOLIDCRAFT_SCHEMA_RULE_STRICT=1` to make the missing-schema check fail today. - **"`x.y` has no input or output schema"** (or "no input schema", "no output schema"): a new command. Give it what it lacks, as below. Don't add it to `schema/unconverted.txt`: that list holds only the commands that predate the rule. - **"`x.y` has its schemas now: remove its line from unconverted.txt"**: you converted an old command. Delete its line. - **"`x.y` is a planned! placeholder, which needs no line in unconverted.txt"**: delete its line. - **"unconverted.txt names commands that don't exist"**: a command was removed or renamed. Delete its line. - **"unconverted.txt must be sorted, each id once"**: keep the list in byte order (`LC_ALL=C sort`). - **"`x.y` ran with an unknown key in strict"** or **"`x.y` should refuse with …"**: it has a contract, but its `run` isn't `crate::checked!("x.y", )` (step 5): the wrapper is missing or names another command's id. ## Writing a contract ### 1. List the keys the handler reads The contract's keys are exactly the keys the handler reads, no more and no fewer. Read the handler and everything it passes `p` to: - direct reads: `p.get("k")`, `params::expr(p, "k")`, `req_expr`, `str_`, `num`, `bool_`, `vec3`, `string_list` and the like; - `features::add_feature` (every feature command) reads `name`, `body_name`, `body_names` and `participants`: take them with [`FeatureCommon`](#shared-types). What `participants` changes depends on the feature, and for some it changes nothing in the result: check where the feature is evaluated (`crates/doc/src/eval.rs`). `participants` takes its description from `FeatureCommon`, shared by every feature, so say what it does for this one elsewhere: where it and another key override each other (a primitive's `targets` gives way to it; an extrude's `targets` overrides it), in that key's description; where it has no effect, in the summary or in the description of the key it might seem to change (bounding solid's `bodies`). A feature that makes no body (scale) declares `name` and `participants` itself instead, as `body_name` and `body_names` would do nothing; a construction axis, point or plane flattens `ConstructionCommon` or `PlaneCommon`, which hold just those two. It keeps `participants` because `timeline.redefine` passes a feature's own back, though for a scale it changes nothing either; its own description says so. For the primitives (box, cylinder, sphere, torus, cone) `add_feature` also reads `targets`; a new primitive must join the `primitive` match in `add_feature_in`, and its contract declares `targets`. The commands that combine bodies read `operation` (and usually `targets`) in their own handlers; - keys read around the command: `frames::to_local` reads `body` (and `face_body`) for commands that take picks; - `live`, for a command with `.live(…)` (today `sketch.drag` and `sketch.edit_text`): a call with `live: true` goes to the live runner, which `checked!` doesn't wrap, so live calls aren't checked yet. Leave those two on the list until the engine checks the live path too. A new command that needs a live runner still gets its contract (declare `live` as an optional `bool`); say in its pull request that its live calls aren't checked. A key the handler reads only in some situations (thin-wall keys with `thin: true`) is still a field; its description says when it applies. Contracts don't check combinations of keys (`sketch` with `face`); the handler does. ### 2. Put it in the module for its command file Contracts for `cmd/features.rs` live in `schema/features.rs`, for `cmd/inspect.rs` in `schema/inspect.rs`, and so on, each with its tests in a file next to it (`schema/features_tests.rs`). For a command file's first contract, create the module and add its `pub mod` line, sorted, under "The contracts, by command file" in `schema/mod.rs`. A new module starts like this (keep the imports it uses): ```rust //! Contracts and result types for the commands in `cmd/wedge.rs`. use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use super::types::{FeatureCommon, LengthExpr, OperationParam, PointExpr3, StringList, feature_common, present}; // …the parameters and reply types… #[cfg(test)] #[path = "wedge_tests.rs"] mod tests; ``` ### 3. Write the parameters type ```rust /// Add a wedge primitive. #[derive(Debug, Deserialize, JsonSchema)] #[schemars(deny_unknown_fields)] pub struct WedgeParams { /// Size along X. pub length: LengthExpr, /// Size along Y. pub width: LengthExpr, /// Height at the thick end, along Z. pub height: LengthExpr, /// The wedge's minimum corner. Default: the origin. #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] #[schemars(with = "PointExpr3")] pub corner: Option, /// How the wedge combines with existing bodies. Default: new. #[serde(default)] pub operation: Option, /// The bodies a join, cut or intersect works on. Default: every body in the feature's /// component, not its sub-components (an intersect removes those the wedge doesn't meet). /// Ignored when `participants` lists bodies. #[serde(default)] pub targets: Option, #[serde(flatten, deserialize_with = "feature_common")] pub common: FeatureCommon, } ``` - **Descriptions are the documentation.** The struct's doc comment is the command's summary and each field's doc comment is its description in the schema, so put nothing else on those lines. Say the unit or form, the default (`Default: …`) and when the key is ignored. Write for someone who has only the schema. Check what each value does where the feature is evaluated (`crates/doc/src/eval.rs` and the kernel), not only how the handler reads it: a limit the evaluation enforces (a torus's `minor` must be less than its `major`) or a key it ignores belongs in the description. A scale's `factor`, for one, has no effect when `factors` is given, though it must still evaluate. - **Required or optional** follows the handler: a key it can't do without is a plain field; any other is `#[serde(default)] Option`. - **`null`:** the common readers (`str_`, `num`, `bool_`, `expr`, `string_list`) read `null` as absent, which a plain `#[serde(default)] Option` matches. Readers that parse `p.get(k)` themselves (`features::feature_sketch`, `features::profiles`, the pick lists) refuse `null`; for those keys use `#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]` with `#[schemars(with = "T")]`. The key may then be absent but not `null`, the schema has no `null` branch, and `skip_serializing_if` stops schemars publishing `default: null`, which the schema itself would refuse. - **Use a shared type** for every value it fits (below) rather than `String` or `f64`: shared types accept exactly what the handlers' readers accept, give the handlers' messages, and publish the matching schema. ### 4. Write the reply type A feature command whose handler returns `add_feature`'s reply unchanged returns `FeatureResult` (in `schema/features.rs`): use it, don't copy it. A command that returns anything else, including a feature command that reshapes the reply (`solid.thread` returns `{feature, name, thread}`), gets its own reply type: ```rust /// What `wedge.measure` returns. #[derive(Debug, Serialize, JsonSchema)] pub struct WedgeMeasureResult { /// The wedge's volume, in mm³. pub volume: f64, /// 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, } ``` - Build the handler's reply from the type (`serde_json::to_value(reply)`), as `add_feature_in` builds `FeatureResult`, rather than a `json!` literal next to it. Then the schema can't drift from what the command returns. - Warn mode adds `param_warnings` to a successful reply that is a JSON object, so an object reply type keeps that field. A reply that isn't an object (a list) is returned unchanged and has no such field. ### 5. Register them In the command file, next to its `COMMANDS`: ```rust use crate::schema::features::FeatureResult; use crate::schema::wedge::WedgeParams; use crate::schema::{TypedContract, output_schema_for}; const WEDGE_CONTRACT: TypedContract = TypedContract::new(); // in COMMANDS: CommandSpec::new("solid.wedge", "Wedge", crate::checked!("solid.wedge", prim_wedge)) .at("SOLID", "CREATE") .icon("wedge") .contract(&WEDGE_CONTRACT) .output(output_schema_for::) .params("length, width, height: expr; corner?: [x,y,z] …"), ``` `.contract` and `.output` publish the schemas, and `checked!` checks each call against the contract that its id publishes, in front of the handler, so what is checked is always what is published. The handler itself doesn't change: it still reads the raw parameters. Keep the `.params(…)` prose: the command list, the palette and `describe_command`'s `params` still show it, until it is generated from the schemas. ### 6. Test it In the module's tests file: - **`schemas_and_the_key_check_agree`:** add `assert_keys(input_schema_for::(), &[…])` with the keys, sorted, `FeatureCommon`'s included. The keys then change only on purpose. - **`strict_keeps_todays_errors`:** for calls the handler already refuses (a malformed value, an unknown spelling), add cases to `assert_strict_keeps_todays_errors`: strict must give the same message as the handler. Leave out the cases its documentation lists as different on purpose, such as a missing required key (strict says `` `length` is required ``, the handler something else). - **A reply test:** run the command and check the reply matches its output schema with `conforms` (`replies_match_the_output_schema` in `schema/features_tests.rs` shows how; its misspelt-key call checks that a reply carrying warnings still matches). Run every form the command takes (each alternative key, such as `corner` or `center`, each `operation`, one name and a list of names) in Warn, and check those replies have no `param_warnings`: Warn runs a call the contract refuses anyway, so a matching reply doesn't show the contract accepts the call. A reply that isn't an object never carries `param_warnings`; run those calls in Strict, where a refused call is an error. In the same file, `converted_primitives_and_body_commands_reply_with_feature_result` shows the Warn and no-`param_warnings` checks across several commands. `schema_defaults_are_valid` checks the `default` of each top-level parameter on its own; a nested type's defaults are yours to check. ### 7. Converting a command that already exists Do steps 1 to 6, remove its line from `schema/unconverted.txt`, then check the contract against every caller the tests have: run the whole suite with the audit recorder and summarise it. ```text mkdir -p audit SOLIDCRAFT_PARAM_AUDIT=$PWD/audit cargo test --workspace --no-fail-fast --features solidcraft-engine/param-audit python3 scripts/param_audit.py audit ``` The recorder doesn't create the directory, and it writes nothing if it can't, so check the summary's first line says at least one file. Each line under "SUCCEEDS TODAY, STRICT WOULD REFUSE" is a call that works today and that strict would refuse: a form the contract is missing (fix the contract) or a caller's mistake, such as a misspelt key (fix the caller). Put the summary in the pull request. ## Shared types In `crates/engine/src/schema/types.rs`. Each accepts exactly what its reader accepts, most by calling that reader. | Type | For | Matches | | --- | --- | --- | | `LengthExpr`, `AngleExpr` | a number or an expression (`"w / 2"`, `"30 deg"`) | `params::expr` | | `NumberExpr` | a number or an expression with no unit (a ratio, a factor) | `params::expr` | | `Point3`, `Point2` | `[x, y, z]` / `[x, y]` or `{x, y, z}` of numbers, in mm | `params::vec3`, `params::vec2` | | `PointExpr3` | a placement point whose coordinates may be expressions | `features::point_param` | | `IdOrName` | a feature by id or name (extrude's `sketch`) | `features::feature_sketch` | | `SketchRef` | a sketch by id or name, with `features::sketch_id`'s message | `features::sketch_id` | | `StringList` | one name or a list of names | `params::string_list` | | `OperationParam` | new, join, cut, intersect and their spellings | `Operation::parse` | | `FaceRef` | a face by a point on it or its name | `face::face_ref` | | `FaceRefs` | the `faces` list of shell, draft, offset face, split face and `face.delete` (not `solid.replace_face`, whose messages differ) | `features::face_points` | | `EdgeRef`, `EdgeRefs` | an edge by a point on it or `{body, index}`; fillet's and chamfer's `edges` | `features::edge_points` | | `ProfilesParam` | which sketch profiles | `features::profiles` | | `ScaleFactors` | scale's `factors`: three `NumberExpr`s (strict words a bad item differently; see its doc) | `features::scale` | | `AxisDir` | X, Y or Z, or a non-zero `[x, y, z]` / `{x, y, z}` (cylinder's, cone's and coil's `axis`) | `features::axis_dir_form` | | `FeatureCommon` | `name`, `body_name`, `body_names`, `participants`, flattened | `features::add_feature` | | `ConstructionCommon`, `PlaneCommon` | `name` and `participants` of a construction axis or point, or of a construction plane (whose `name` is a `PlaneName`), flattened | `features::add_feature` | | `PlaneName` | a construction plane's name, which may not be an origin plane's (strict names the command called; see its doc) | `features::check_plane_name` | | `PlaneParam` | a plane: an origin or construction plane's name, a construction plane's id, or `{origin?, x_dir, y_dir}` / `{origin?, normal}` | `features::plane_param` | | `PlaneOrFace` | a plane, or a planar face of a body `{face, body?, index?, path?, fixed?}` (offset and at-angle planes' `base`) | `features::plane_param`, `sketch::face::face_pick_form` | | `GeoRefParam` | geometry a construction feature is built from: a picked face, edge or vertex, a sketch point or curve, a point, a plane, an axis, a construction point | `construct::geo_form` | | `AxisLine` | an at-angle plane's `axis`: X, Y, Z, a construction axis, `{origin?, dir}` or a model edge or face | `features::axis_line_object`, `construct::geo_form` | ### When no shared type fits Add one to `types.rs`, next to the reader it mirrors: - Its `Deserialize` calls the **handler's own reader**, so "the contract accepts it" means "the handler accepts it". Don't re-implement the parsing. Many readers are private to their command file or need the design (`features::point_param` takes the `Session`). Split out the part that only looks at the JSON as a `pub(crate)` function, have the handler call it, and re-export it from `cmd/mod.rs`, as `face_ref_form` and `edge_ref_form` are; whether the value finds something in the design stays in the handler. - On failure it gives the **handler's message**. Wrap a message that is already a whole sentence, such as the handler's ``unknown operation `x` (…)``, in `whole(…)`, and the check passes it on as it is. Otherwise start it with "must": the check names the key, so "must be a point [x, y, z] of numbers" becomes ``"`corner` must be a point [x, y, z] of numbers"``. (Any other message comes out as ``"`corner`: …"``.) Where the handler puts serde's own message after the key (``"`point`: missing field `p`"``), wrap it in `keyed(…)`: the check puts the key and a colon in front and leaves the rest as it is, instead of rewording "missing field" and "invalid type" as it does for the type's own fields. - Its `JsonSchema` describes the same values, with a description. Where JSON Schema can't say something the reader checks (ignoring case, a byte length), say it in the description. A pattern that allows surrounding whitespace must allow exactly what Rust's `trim` removes: build it from `WHITESPACE`, as `not_blank_pattern` and `AxisDir` do, rather than writing a regex's whitespace class by hand (it differs, and the escapes are easy to get wrong). `conforms` doesn't read patterns, so pin the pattern's text in a test. - Test both: values the reader accepts and refuses are accepted and refused by the type, and they match the schema (the `conforms` helper in `schema/tests.rs`; see `face_and_edge_refs_match_the_pick_readers`). - A handler that reads a key more leniently than any type can (a wrong-typed value read as if the key were absent) gets the stricter type: that difference is what warn and strict report. - A reader that tries forms in order, where some forms, once chosen, refuse the value rather than letting a later form take it (`construct::geo`: `{sketch, point: [1, 2, 3]}` is a sketch reference without a point, never a fixed point), needs a schema that keeps that order: give each later form a `not` naming the keys of the earlier forms that refuse, as `GeoRefParam` does, and test values that two forms would read differently. ## Checklist 1. The contract's keys are exactly the handler's reads, including `add_feature`'s (less `body_name` and `body_names` for a feature that makes no body), the frame mapping's and `live`. 2. The struct and every field have descriptions, with defaults and when a key is ignored. 3. Shared types wherever they fit; a new type calls the handler's reader and gives its message. 4. `FeatureResult` for a command that returns `add_feature`'s reply unchanged, else a reply type the handler builds its reply from. 5. `checked!`, `.contract` and `.output` on the `CommandSpec`, and the `.params` prose kept. 6. `assert_keys`, error-message cases, a reply test. 7. For an existing command: its `unconverted.txt` line removed and the audit summary in the PR.