modewise_operations/
catalogue.rs

1//! Self-description of the built-in operations: a JSON catalogue for tools and agents, and the
2//! generated reference page (docs/reference/operations.md).
3
4use modewise_pipeline::{Operation, Port};
5use serde_json::{Value, json};
6
7use crate::builtin_registry;
8
9fn ports(ports: &[Port], optional: &[&str]) -> Value {
10    ports.iter().map(|p| {
11        let mut port = json!({"name": p.name, "kinds": p.kinds.iter().map(ToString::to_string).collect::<Vec<_>>()});
12        if optional.contains(&p.name) {
13            port["optional"] = json!(true);
14        }
15        port
16    }).collect()
17}
18
19fn entry(name: &str, op: &dyn Operation) -> Value {
20    let d = op.descriptor();
21    json!({
22        "name": name,
23        "version": d.version,
24        "summary": op.summary(),
25        "inputs": ports(d.inputs, op.optional_inputs()),
26        "outputs": ports(d.outputs, &[]),
27        "params": op.params_schema(),
28    })
29}
30
31/// Every built-in operation: name, version, summary, ports and parameter JSON Schema.
32pub fn catalogue() -> Value {
33    let registry = builtin_registry();
34    let operations: Vec<Value> = registry
35        .names()
36        .filter_map(|n| registry.get(n).map(|op| entry(n, op.as_ref())))
37        .collect();
38    json!({ "operations": operations })
39}
40
41fn resolve<'a>(schema: &'a Value, spec: &'a Value) -> &'a Value {
42    match spec.get("$ref").and_then(Value::as_str) {
43        Some(r) => &schema["$defs"][r.trim_start_matches("#/$defs/")],
44        None => spec,
45    }
46}
47
48/// A short human type for a schema node.
49fn type_name(schema: &Value, spec: &Value) -> String {
50    let spec = resolve(schema, spec);
51    if let Some(values) = spec.get("enum").and_then(Value::as_array) {
52        return values
53            .iter()
54            .map(|v| format!("`{}`", v.as_str().unwrap_or_default()))
55            .collect::<Vec<_>>()
56            .join(", ");
57    }
58    if let Some(options) = spec
59        .get("anyOf")
60        .or_else(|| spec.get("oneOf"))
61        .and_then(Value::as_array)
62    {
63        let names: Vec<String> = options
64            .iter()
65            .filter(|o| o.get("type") != Some(&json!("null")))
66            .map(|o| type_name(schema, o))
67            .collect();
68        return names.join(" or ");
69    }
70    let kind = match spec.get("type") {
71        Some(Value::Array(kinds)) => kinds
72            .iter()
73            .filter_map(Value::as_str)
74            .find(|k| *k != "null")
75            .unwrap_or("value"),
76        Some(Value::String(kind)) => kind.as_str(),
77        _ => "value",
78    };
79    match kind {
80        "array" => format!(
81            "list of {}",
82            spec.get("items")
83                .map_or("values".into(), |i| type_name(schema, i))
84        ),
85        "object" if spec.get("properties").is_some() => {
86            // Sorted, so the page does not depend on serde_json's map order.
87            let mut keys: Vec<&String> = spec["properties"]
88                .as_object()
89                .map(|p| p.keys().collect())
90                .unwrap_or_default();
91            keys.sort();
92            format!(
93                "table ({})",
94                keys.iter()
95                    .map(|k| format!("`{k}`"))
96                    .collect::<Vec<_>>()
97                    .join(", ")
98            )
99        }
100        "object" => "table".into(),
101        "number" => "number".into(),
102        other => other.into(),
103    }
104}
105
106fn cell(text: &str) -> String {
107    text.replace('|', "\\|").replace('\n', " ")
108}
109
110fn port_line(ports: &Value) -> String {
111    ports
112        .as_array()
113        .map(|ps| {
114            ps.iter()
115                .map(|p| {
116                    let kinds: Vec<&str> = p["kinds"]
117                        .as_array()
118                        .map(|k| k.iter().filter_map(Value::as_str).collect())
119                        .unwrap_or_default();
120                    format!(
121                        "`{}` ({}{})",
122                        p["name"].as_str().unwrap_or_default(),
123                        kinds.join(" or "),
124                        if p["optional"] == true {
125                            ", optional"
126                        } else {
127                            ""
128                        }
129                    )
130                })
131                .collect::<Vec<_>>()
132                .join(", ")
133        })
134        .unwrap_or_default()
135}
136
137/// The reference page for every built-in operation, generated from `catalogue()`.
138pub fn reference_markdown() -> String {
139    let mut out = String::from(
140        "# Operation reference\n\n\
141         <!-- Generated from the operations' own schemas by `modewise ops --markdown`; do not edit.\n\
142         Regenerate with `MODEWISE_UPDATE_DOCS=1 cargo test -p modewise_operations --test reference`. -->\n\n\
143         Every step in a pipeline names one of these operations. Parameters go in the step's `params` table; \
144         anything not listed is rejected, and missing parameters take the defaults shown. \
145         `modewise ops --json` gives the same information as JSON Schema, for tools and agents.\n",
146    );
147    for op in catalogue()["operations"].as_array().into_iter().flatten() {
148        let name = op["name"].as_str().unwrap_or_default();
149        out.push_str(&format!(
150            "\n## `{name}`\n\n{}\n\n",
151            op["summary"].as_str().unwrap_or_default()
152        ));
153        out.push_str(&format!(
154            "- **Inputs:** {}\n- **Outputs:** {}\n",
155            port_line(&op["inputs"]),
156            port_line(&op["outputs"])
157        ));
158        let schema = &op["params"];
159        let required: Vec<&str> = schema["required"]
160            .as_array()
161            .map(|r| r.iter().filter_map(Value::as_str).collect())
162            .unwrap_or_default();
163        let Some(properties) = schema["properties"].as_object().filter(|p| !p.is_empty()) else {
164            out.push_str("\nNo parameters.\n");
165            continue;
166        };
167        let mut fields: Vec<(&String, &Value)> = properties.iter().collect();
168        fields.sort_by_key(|(k, _)| (!required.contains(&k.as_str()), k.as_str()));
169        out.push_str("\n| Parameter | Type | Default | Meaning |\n|---|---|---|---|\n");
170        for (field, spec) in fields {
171            let default = match spec.get("default") {
172                _ if required.contains(&field.as_str()) => "required".to_string(),
173                Some(Value::Null) | None => "—".to_string(),
174                Some(v) => format!("`{v}`"),
175            };
176            let meaning = spec
177                .get("description")
178                .and_then(Value::as_str)
179                .unwrap_or_default();
180            out.push_str(&format!(
181                "| `{field}` | {} | {default} | {} |\n",
182                cell(&type_name(schema, spec)),
183                cell(meaning)
184            ));
185        }
186    }
187    out
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    #[test]
195    fn types_read_from_schema_nodes() {
196        let schema = json!({"$defs": {"Side": {"enum": ["left", "right"], "type": "string"}}});
197        let name = |spec: Value| type_name(&schema, &spec);
198        assert_eq!(name(json!({"$ref": "#/$defs/Side"})), "`left`, `right`");
199        assert_eq!(name(json!({"type": ["integer", "null"]})), "integer");
200        assert_eq!(
201            name(json!({"type": "array", "items": {"type": "string"}})),
202            "list of string"
203        );
204        assert_eq!(
205            name(json!({"type": "object", "additionalProperties": {"type": "string"}})),
206            "table"
207        );
208        assert_eq!(
209            name(json!({"type": "object", "properties": {"b": {}, "a": {}}})),
210            "table (`a`, `b`)"
211        );
212        assert_eq!(
213            name(json!({"anyOf": [{"$ref": "#/$defs/Side"}, {"type": "null"}]})),
214            "`left`, `right`"
215        );
216        assert_eq!(name(json!({})), "value");
217        assert_eq!(cell("a | b\nc"), "a \\| b c");
218    }
219}