Skip to main content

graphrt_core/
dsl.rs

1//! Workflow documents: the portable, serializable description of a workflow.
2//!
3//! A document is plain data (JSON or YAML). It is turned into an executable
4//! [`crate::graph::Graph`] by [`crate::graph::Graph::build`] using a
5//! [`crate::node::Registry`].
6//!
7//! ```yaml
8//! version: "1"
9//! name: hello
10//! env:
11//!   - { name: API_KEY, type: secret }
12//! graph:
13//!   nodes:
14//!     - id: start
15//!       type: start
16//!       variables: [{ variable: name, type: string, required: true }]
17//!     - id: greet
18//!       type: template-transform
19//!       template: "Hello {{ name }}"
20//!       variables: [{ variable: name, value_selector: [start, name] }]
21//!     - id: end
22//!       type: end
23//!       outputs: [{ variable: greeting, value_selector: [greet, output] }]
24//!   edges:
25//!     - { source: start, target: greet }
26//!     - { source: greet, target: end }
27//! ```
28//!
29//! For interoperability the loader also accepts the common "node with a `data`
30//! object" layout (`{id, parentId, data: {type, title, ...}}`), camelCase edge
31//! handles (`sourceHandle`) and documents wrapped in a top-level `workflow` key.
32
33use indexmap::IndexMap;
34use serde::{Deserialize, Serialize};
35
36use crate::value::{Value, ValueType};
37
38/// Error raised while decoding a workflow document.
39#[derive(Debug, thiserror::Error)]
40#[non_exhaustive]
41pub enum DocumentError {
42    #[error("invalid JSON workflow document: {0}")]
43    Json(#[from] serde_json::Error),
44    /// Only produced when the `yaml` feature is enabled (the variant always exists
45    /// so enabling the feature never breaks downstream matches).
46    #[error("invalid YAML workflow document: {0}")]
47    Yaml(String),
48    #[error("invalid node `{id}`: {message}")]
49    Node { id: String, message: String },
50}
51
52/// A complete workflow document.
53#[derive(Clone, Debug, Default, Serialize)]
54pub struct Workflow {
55    /// Document format version.
56    pub version: String,
57    pub name: Option<String>,
58    pub description: Option<String>,
59    /// Environment variables (`env.*`). Values may be omitted and supplied by the host at run time.
60    pub env: Vec<VariableDecl>,
61    /// Conversation variables (`conversation.*`), persisted by the host between runs.
62    pub conversation: Vec<VariableDecl>,
63    pub graph: GraphDoc,
64}
65
66/// Declaration of an env or conversation variable.
67#[derive(Clone, Debug, Serialize, Deserialize)]
68pub struct VariableDecl {
69    pub name: String,
70    #[serde(rename = "type", alias = "value_type", default = "any_type")]
71    pub ty: ValueType,
72    #[serde(default)]
73    pub value: Option<Value>,
74    #[serde(default)]
75    pub description: Option<String>,
76}
77
78fn any_type() -> ValueType {
79    ValueType::Any
80}
81
82/// Nodes and edges.
83#[derive(Clone, Debug, Default, Serialize)]
84pub struct GraphDoc {
85    pub nodes: Vec<NodeDoc>,
86    pub edges: Vec<EdgeDoc>,
87}
88
89/// One node. Node-specific settings live in `config`.
90///
91/// Serializes to the flat layout the loader accepts (`id`, `type`, `title`,
92/// `parent`, `on_error`, `retry`, `timeout_ms`, then the config keys), so a
93/// document survives a serialize / parse round trip unchanged.
94#[derive(Clone, Debug)]
95pub struct NodeDoc {
96    pub id: String,
97    /// Node kind, e.g. `llm`, `if-else`, `http-request`.
98    pub kind: String,
99    pub title: Option<String>,
100    /// Owning container (iteration / loop) for nodes inside a container body.
101    pub parent: Option<String>,
102    pub policy: NodePolicy,
103    /// Remaining node-specific configuration.
104    pub config: serde_json::Map<String, serde_json::Value>,
105}
106
107impl NodeDoc {
108    /// Minimal constructor, mainly for programmatic graph building and tests.
109    pub fn new(id: impl Into<String>, kind: impl Into<String>, config: serde_json::Value) -> Self {
110        let config = match config {
111            serde_json::Value::Object(map) => map,
112            _ => serde_json::Map::new(),
113        };
114        Self { id: id.into(), kind: kind.into(), title: None, parent: None, policy: NodePolicy::default(), config }
115    }
116
117    /// Set the owning container.
118    pub fn with_parent(mut self, parent: impl Into<String>) -> Self {
119        self.parent = Some(parent.into());
120        self
121    }
122
123    /// Set the failure policy.
124    pub fn with_policy(mut self, policy: NodePolicy) -> Self {
125        self.policy = policy;
126        self
127    }
128
129    /// Deserialize `config` into a node-specific config struct.
130    pub fn parse_config<T: serde::de::DeserializeOwned>(&self) -> Result<T, DocumentError> {
131        serde_json::from_value(serde_json::Value::Object(self.config.clone()))
132            .map_err(|e| DocumentError::Node { id: self.id.clone(), message: e.to_string() })
133    }
134
135    /// Human-readable label.
136    pub fn label(&self) -> &str {
137        self.title.as_deref().unwrap_or(&self.id)
138    }
139}
140
141/// Failure handling, retries and timeouts for one node.
142#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
143pub struct NodePolicy {
144    #[serde(default)]
145    pub on_error: ErrorStrategy,
146    #[serde(default)]
147    pub retry: RetryPolicy,
148    /// Per-attempt timeout in milliseconds. `None` uses the engine default.
149    #[serde(default)]
150    pub timeout_ms: Option<u64>,
151}
152
153/// What happens when a node fails after exhausting retries.
154#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
155#[serde(tag = "strategy", rename_all = "kebab-case")]
156#[non_exhaustive]
157pub enum ErrorStrategy {
158    /// Fail the frame (and the run, unless a container handles it).
159    #[default]
160    Fail,
161    /// Route through outgoing edges whose handle is [`crate::graph::FAIL_BRANCH`];
162    /// outputs are `error_message` and `error_type`.
163    FailBranch,
164    /// Continue normally with these outputs, plus `error_message` and `error_type`.
165    DefaultValue {
166        #[serde(default)]
167        values: IndexMap<String, Value>,
168    },
169}
170
171/// Retry policy. Applies to every node kind.
172#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
173pub struct RetryPolicy {
174    #[serde(default)]
175    pub max_retries: u32,
176    /// Delay before the first retry, in milliseconds.
177    #[serde(default)]
178    pub interval_ms: u64,
179    /// Multiplier applied to the delay after each retry (1.0 = constant).
180    #[serde(default = "one")]
181    pub backoff: f64,
182}
183
184fn one() -> f64 {
185    1.0
186}
187
188impl Default for RetryPolicy {
189    fn default() -> Self {
190        Self { max_retries: 0, interval_ms: 0, backoff: 1.0 }
191    }
192}
193
194impl RetryPolicy {
195    /// Delay before retry number `attempt` (1-based).
196    pub fn delay_ms(&self, attempt: u32) -> u64 {
197        let factor = self.backoff.max(1.0).powi(i32::try_from(attempt.saturating_sub(1)).unwrap_or(i32::MAX));
198        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss, clippy::cast_precision_loss)]
199        let ms = (self.interval_ms as f64 * factor).min(3_600_000.0) as u64;
200        ms
201    }
202}
203
204/// A directed edge. `handle` selects the branch of the source node (default `source`).
205#[derive(Clone, Debug, Serialize, Deserialize)]
206pub struct EdgeDoc {
207    #[serde(default)]
208    pub id: Option<String>,
209    pub source: String,
210    pub target: String,
211    #[serde(default, alias = "sourceHandle", alias = "source_handle", skip_serializing_if = "Option::is_none")]
212    pub handle: Option<String>,
213}
214
215impl EdgeDoc {
216    pub fn new(source: impl Into<String>, target: impl Into<String>) -> Self {
217        Self { id: None, source: source.into(), target: target.into(), handle: None }
218    }
219
220    pub fn with_handle(mut self, handle: impl Into<String>) -> Self {
221        self.handle = Some(handle.into());
222        self
223    }
224}
225
226impl Workflow {
227    /// Parse a JSON document.
228    pub fn from_json(text: &str) -> Result<Self, DocumentError> {
229        let raw: serde_json::Value = serde_json::from_str(text)?;
230        Self::from_value(raw)
231    }
232
233    /// Parse a YAML document.
234    #[cfg(feature = "yaml")]
235    pub fn from_yaml(text: &str) -> Result<Self, DocumentError> {
236        // YAML 1.2 booleans only: `yes`, `no`, `y`, `n`, `on`, `off` stay strings.
237        let options = serde_saphyr::options! { strict_booleans: true };
238        let raw: serde_json::Value =
239            serde_saphyr::from_str_with_options(text, options).map_err(|e| DocumentError::Yaml(e.to_string()))?;
240        Self::from_value(raw)
241    }
242
243    /// Parse JSON or YAML, detecting the format from the first non-blank character.
244    pub fn parse(text: &str) -> Result<Self, DocumentError> {
245        let first = text.trim_start().chars().next();
246        if matches!(first, Some('{')) {
247            return Self::from_json(text);
248        }
249        #[cfg(feature = "yaml")]
250        {
251            Self::from_yaml(text)
252        }
253        #[cfg(not(feature = "yaml"))]
254        {
255            Self::from_json(text)
256        }
257    }
258
259    /// Build from an already-decoded JSON value.
260    pub fn from_value(raw: serde_json::Value) -> Result<Self, DocumentError> {
261        let mut root = match raw {
262            serde_json::Value::Object(m) => m,
263            _ => return Err(node_err("<document>", "document must be an object")),
264        };
265        // Documents may nest everything under `workflow`.
266        if let Some(serde_json::Value::Object(inner)) = root.remove("workflow") {
267            for (k, v) in inner {
268                root.entry(k).or_insert(v);
269            }
270        }
271        let app = root.get("app").and_then(|a| a.as_object());
272        let name = str_field(&root, "name").or_else(|| app.and_then(|a| str_field(a, "name")));
273        let description = str_field(&root, "description").or_else(|| app.and_then(|a| str_field(a, "description")));
274        let version = str_field(&root, "version").unwrap_or_else(|| "1".to_owned());
275
276        let env = decls(root.remove("env").or_else(|| root.remove("environment_variables")))?;
277        let conversation = decls(root.remove("conversation").or_else(|| root.remove("conversation_variables")))?;
278
279        let graph = match root.remove("graph") {
280            Some(serde_json::Value::Object(g)) => g,
281            _ => return Err(node_err("<document>", "missing `graph` object")),
282        };
283        let nodes = match graph.get("nodes") {
284            Some(serde_json::Value::Array(items)) => items.clone(),
285            _ => Vec::new(),
286        };
287        let edges = match graph.get("edges") {
288            Some(e) => serde_json::from_value::<Vec<EdgeDoc>>(e.clone())?,
289            None => Vec::new(),
290        };
291        let mut docs = Vec::with_capacity(nodes.len());
292        for raw in nodes {
293            if let Some(doc) = NodeDoc::from_raw(raw)? {
294                docs.push(doc);
295            }
296        }
297        Ok(Self { version, name, description, env, conversation, graph: GraphDoc { nodes: docs, edges } })
298    }
299}
300
301fn str_field(map: &serde_json::Map<String, serde_json::Value>, key: &str) -> Option<String> {
302    map.get(key).and_then(|v| v.as_str()).map(str::to_owned)
303}
304
305fn node_err(id: &str, message: &str) -> DocumentError {
306    DocumentError::Node { id: id.to_owned(), message: message.to_owned() }
307}
308
309fn decls(raw: Option<serde_json::Value>) -> Result<Vec<VariableDecl>, DocumentError> {
310    match raw {
311        None | Some(serde_json::Value::Null) => Ok(Vec::new()),
312        Some(v) => Ok(serde_json::from_value(v)?),
313    }
314}
315
316/// Keys handled by [`NodeDoc`] itself and therefore removed from `config`.
317const POLICY_KEYS: &[&str] =
318    &["on_error", "error_strategy", "default_value", "retry", "retry_config", "timeout_ms", "timeout"];
319
320impl NodeDoc {
321    /// Normalize a raw node object. Returns `Ok(None)` for annotation-only nodes (notes).
322    pub fn from_raw(raw: serde_json::Value) -> Result<Option<Self>, DocumentError> {
323        let serde_json::Value::Object(mut obj) = raw else {
324            return Err(node_err("<node>", "node must be an object"));
325        };
326        let id = match obj.remove("id") {
327            Some(serde_json::Value::String(s)) if !s.is_empty() => s,
328            _ => return Err(node_err("<node>", "node `id` must be a non-empty string")),
329        };
330        let mut parent = obj.remove("parentId").or_else(|| obj.remove("parent")).and_then(as_string);
331        // Flatten the `data` wrapper layout.
332        if let Some(serde_json::Value::Object(data)) = obj.remove("data") {
333            for (k, v) in data {
334                obj.insert(k, v);
335            }
336        }
337        for key in ["container_id", "iteration_id", "loop_id"] {
338            let v = obj.remove(key).and_then(as_string);
339            if parent.is_none() {
340                parent = v;
341            }
342        }
343        let kind = match obj.remove("type") {
344            Some(serde_json::Value::String(s)) if !s.is_empty() => s,
345            _ => return Err(node_err(&id, "node `type` must be a non-empty string")),
346        };
347        if kind == "custom-note" || kind == "note" {
348            return Ok(None);
349        }
350        let title = obj.remove("title").and_then(as_string);
351        let policy = extract_policy(&id, &mut obj)?;
352        for k in [
353            "desc",
354            "selected",
355            "position",
356            "positionAbsolute",
357            "width",
358            "height",
359            "sourcePosition",
360            "targetPosition",
361            "zIndex",
362            "isInIteration",
363            "isInLoop",
364        ] {
365            obj.remove(k);
366        }
367        Ok(Some(Self { id, kind, title, parent, policy, config: obj }))
368    }
369}
370
371fn as_string(v: serde_json::Value) -> Option<String> {
372    match v {
373        serde_json::Value::String(s) if !s.is_empty() => Some(s),
374        _ => None,
375    }
376}
377
378fn extract_policy(id: &str, obj: &mut serde_json::Map<String, serde_json::Value>) -> Result<NodePolicy, DocumentError> {
379    let mut policy = NodePolicy::default();
380    let bad =
381        |what: &str, e: serde_json::Error| DocumentError::Node { id: id.to_owned(), message: format!("{what}: {e}") };
382
383    if let Some(v) = obj.remove("on_error") {
384        policy.on_error = serde_json::from_value(v).map_err(|e| bad("on_error", e))?;
385    } else if let Some(serde_json::Value::String(strategy)) = obj.remove("error_strategy") {
386        policy.on_error = match strategy.as_str() {
387            "fail-branch" => ErrorStrategy::FailBranch,
388            "" | "none" | "fail" => ErrorStrategy::Fail,
389            "default-value" => {
390                // Accept `[{key, type, value}]` lists or plain maps.
391                let values = match obj.remove("default_value") {
392                    Some(serde_json::Value::Array(items)) => items
393                        .into_iter()
394                        .filter_map(|item| {
395                            let key = item.get("key")?.as_str()?.to_owned();
396                            let declared = item.get("type").and_then(|t| t.as_str()).unwrap_or("any").to_owned();
397                            let value = item.get("value").cloned().unwrap_or(serde_json::Value::Null);
398                            Some((key, default_value(&declared, value)))
399                        })
400                        .collect(),
401                    Some(serde_json::Value::Object(map)) => {
402                        map.into_iter().map(|(k, v)| (k, Value::from_json(v))).collect()
403                    }
404                    _ => IndexMap::new(),
405                };
406                ErrorStrategy::DefaultValue { values }
407            }
408            other => {
409                return Err(DocumentError::Node {
410                    id: id.to_owned(),
411                    message: format!(
412                        "unknown error_strategy `{other}` (expected `fail`, `fail-branch` or `default-value`)"
413                    ),
414                });
415            }
416        };
417    }
418    obj.remove("default_value");
419
420    if let Some(v) = obj.remove("retry") {
421        policy.retry = serde_json::from_value(v).map_err(|e| bad("retry", e))?;
422    } else if let Some(serde_json::Value::Object(cfg)) = obj.remove("retry_config") {
423        let enabled = cfg.get("retry_enabled").and_then(serde_json::Value::as_bool).unwrap_or(false);
424        if enabled {
425            policy.retry.max_retries = cfg
426                .get("max_retries")
427                .and_then(serde_json::Value::as_u64)
428                .and_then(|n| u32::try_from(n).ok())
429                .unwrap_or(0);
430            policy.retry.interval_ms = cfg.get("retry_interval").and_then(serde_json::Value::as_u64).unwrap_or(0);
431        }
432    }
433    match obj.remove("timeout_ms") {
434        None | Some(serde_json::Value::Null) => {}
435        Some(v) => match v.as_u64() {
436            Some(ms) => policy.timeout_ms = Some(ms),
437            None => {
438                return Err(DocumentError::Node {
439                    id: id.to_owned(),
440                    message: format!("timeout_ms must be a non-negative integer number of milliseconds, got {v}"),
441                });
442            }
443        },
444    }
445    for k in POLICY_KEYS {
446        obj.remove(*k);
447    }
448    Ok(policy)
449}
450
451/// Default values may arrive as JSON-encoded strings for non-string types.
452fn default_value(declared: &str, value: serde_json::Value) -> Value {
453    match (declared, value) {
454        ("string", v) => Value::from_json(v),
455        (_, serde_json::Value::String(s)) => match serde_json::from_str::<serde_json::Value>(&s) {
456            Ok(parsed) => Value::from_json(parsed),
457            Err(_) => Value::from(s),
458        },
459        (_, v) => Value::from_json(v),
460    }
461}
462
463#[cfg(test)]
464mod tests {
465    use super::*;
466
467    #[test]
468    fn parses_flat_layout() {
469        let doc = Workflow::from_json(
470            r#"{"graph":{"nodes":[{"id":"s","type":"start","variables":[]},
471                {"id":"h","type":"http-request","retry":{"max_retries":2,"interval_ms":10},"timeout_ms":500}],
472                "edges":[{"source":"s","target":"h"}]}}"#,
473        );
474        let doc = doc.unwrap();
475        assert_eq!(doc.graph.nodes.len(), 2);
476        let h = &doc.graph.nodes[1];
477        assert_eq!(h.policy.retry.max_retries, 2);
478        assert_eq!(h.policy.timeout_ms, Some(500));
479        assert!(!h.config.contains_key("retry"));
480    }
481
482    #[test]
483    fn parses_data_wrapper_layout() {
484        let doc = Workflow::from_json(
485            r#"{"workflow":{"environment_variables":[{"name":"K","value_type":"secret","value":"x"}],
486              "graph":{"nodes":[
487                {"id":"a","type":"custom","data":{"type":"llm","title":"LLM","error_strategy":"default-value",
488                  "default_value":[{"key":"n","type":"number","value":"42"}],
489                  "retry_config":{"retry_enabled":true,"max_retries":3,"retry_interval":100}}},
490                {"id":"b","type":"custom","parentId":"it","data":{"type":"code"}},
491                {"id":"note","type":"custom-note","data":{"type":"custom-note"}}],
492              "edges":[{"source":"a","target":"b","sourceHandle":"source"}]}}}"#,
493        );
494        let doc = doc.unwrap();
495        assert_eq!(doc.env.len(), 1);
496        assert_eq!(doc.env[0].ty, ValueType::Secret);
497        assert_eq!(doc.graph.nodes.len(), 2);
498        let a = &doc.graph.nodes[0];
499        assert_eq!(a.kind, "llm");
500        assert_eq!(a.title.as_deref(), Some("LLM"));
501        assert_eq!(a.policy.retry.max_retries, 3);
502        match &a.policy.on_error {
503            ErrorStrategy::DefaultValue { values } => assert_eq!(values.get("n"), Some(&Value::Int(42))),
504            other => panic!("unexpected {other:?}"),
505        }
506        assert_eq!(doc.graph.nodes[1].parent.as_deref(), Some("it"));
507        assert_eq!(doc.graph.edges[0].handle.as_deref(), Some("source"));
508    }
509
510    #[test]
511    fn backoff_delay() {
512        let p = RetryPolicy { max_retries: 3, interval_ms: 100, backoff: 2.0 };
513        assert_eq!(p.delay_ms(1), 100);
514        assert_eq!(p.delay_ms(3), 400);
515    }
516
517    #[cfg(feature = "yaml")]
518    #[test]
519    fn parses_yaml() {
520        let doc = Workflow::parse("graph:\n  nodes:\n    - {id: s, type: start}\n  edges: []\n");
521        assert!(matches!(doc, Ok(d) if d.graph.nodes.len() == 1));
522    }
523
524    #[cfg(feature = "yaml")]
525    #[test]
526    fn yaml_uses_strict_booleans() {
527        let doc = Workflow::parse("graph:\n  nodes:\n    - {id: s, type: start, label: n, flag: true}\n").unwrap();
528        let cfg = &doc.graph.nodes[0].config;
529        assert_eq!(cfg.get("label"), Some(&serde_json::json!("n")));
530        assert_eq!(cfg.get("flag"), Some(&serde_json::json!(true)));
531    }
532}
533
534impl Serialize for NodeDoc {
535    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
536        use serde::ser::{Error as _, SerializeMap};
537        let mut map = serializer.serialize_map(None)?;
538        map.serialize_entry("id", &self.id)?;
539        map.serialize_entry("type", &self.kind)?;
540        if let Some(title) = &self.title {
541            map.serialize_entry("title", title)?;
542        }
543        if let Some(parent) = &self.parent {
544            map.serialize_entry("parent", parent)?;
545        }
546        if self.policy.on_error != ErrorStrategy::Fail {
547            map.serialize_entry("on_error", &self.policy.on_error)?;
548        }
549        if self.policy.retry != RetryPolicy::default() {
550            map.serialize_entry("retry", &self.policy.retry)?;
551        }
552        if let Some(ms) = self.policy.timeout_ms {
553            map.serialize_entry("timeout_ms", &ms)?;
554        }
555        for (key, value) in &self.config {
556            if matches!(key.as_str(), "id" | "type" | "title" | "parent") || POLICY_KEYS.contains(&key.as_str()) {
557                return Err(S::Error::custom(format!("node `{}`: config key `{key}` is reserved", self.id)));
558            }
559            map.serialize_entry(key, value)?;
560        }
561        map.end()
562    }
563}
564
565impl Workflow {
566    /// Serialize to JSON in the same layout [`Workflow::from_json`] accepts.
567    pub fn to_json(&self) -> Result<String, DocumentError> {
568        Ok(serde_json::to_string(self)?)
569    }
570
571    /// Canonical JSON of the graph section (object keys sorted recursively).
572    /// Used for fingerprints, so key order in the source document does not matter.
573    pub fn canonical_graph_json(&self) -> Result<String, DocumentError> {
574        let value = serde_json::to_value(&self.graph)?;
575        Ok(serde_json::to_string(&canonicalize(value))?)
576    }
577}
578
579/// Recursively sort object keys.
580fn canonicalize(value: serde_json::Value) -> serde_json::Value {
581    match value {
582        serde_json::Value::Object(map) => {
583            let mut entries: Vec<(String, serde_json::Value)> = map.into_iter().collect();
584            entries.sort_by(|a, b| a.0.cmp(&b.0));
585            serde_json::Value::Object(entries.into_iter().map(|(k, v)| (k, canonicalize(v))).collect())
586        }
587        serde_json::Value::Array(items) => serde_json::Value::Array(items.into_iter().map(canonicalize).collect()),
588        other => other,
589    }
590}
591
592#[cfg(test)]
593mod roundtrip_tests {
594    use super::*;
595
596    const DOC: &str = r#"{"name":"demo","env":[{"name":"K","type":"secret"}],"graph":{"nodes":[
597        {"id":"s","type":"start","variables":[]},
598        {"id":"h","type":"custom","data":{"type":"http-request","title":"Call","url":"https://x",
599          "error_strategy":"default-value","default_value":{"body":"none"},
600          "retry_config":{"retry_enabled":true,"max_retries":2,"retry_interval":10},"timeout_ms":500}},
601        {"id":"b","type":"code","parentId":"it"}],
602        "edges":[{"source":"s","target":"h","sourceHandle":"source"}]}}"#;
603
604    #[test]
605    fn workflow_round_trips() {
606        let a = Workflow::from_json(DOC).unwrap();
607        let text = a.to_json().unwrap();
608        let b = Workflow::from_json(&text).unwrap();
609        assert_eq!(text, b.to_json().unwrap());
610        let h = &b.graph.nodes[1];
611        assert_eq!(h.kind, "http-request");
612        assert_eq!(h.title.as_deref(), Some("Call"));
613        assert_eq!(h.policy, a.graph.nodes[1].policy);
614        assert_eq!(h.policy.timeout_ms, Some(500));
615        assert_eq!(h.config.get("url"), Some(&serde_json::json!("https://x")));
616        assert!(!h.config.contains_key("config"));
617        assert_eq!(b.graph.nodes[2].parent.as_deref(), Some("it"));
618        assert_eq!(a.canonical_graph_json().unwrap(), b.canonical_graph_json().unwrap());
619    }
620
621    #[test]
622    fn canonical_json_ignores_key_order() {
623        let a = Workflow::from_json(r#"{"graph":{"nodes":[{"id":"s","type":"start","x":1,"y":2}],"edges":[]}}"#);
624        let b = Workflow::from_json(r#"{"graph":{"nodes":[{"y":2,"x":1,"type":"start","id":"s"}],"edges":[]}}"#);
625        assert_eq!(a.unwrap().canonical_graph_json().unwrap(), b.unwrap().canonical_graph_json().unwrap());
626    }
627
628    #[test]
629    fn typos_are_errors() {
630        let bad_strategy = r#"{"graph":{"nodes":[{"id":"s","type":"start","error_strategy":"fail-brnch"}]}}"#;
631        assert!(matches!(Workflow::from_json(bad_strategy), Err(DocumentError::Node { .. })));
632        let bad_timeout = r#"{"graph":{"nodes":[{"id":"s","type":"start","timeout_ms":"5s"}]}}"#;
633        assert!(matches!(Workflow::from_json(bad_timeout), Err(DocumentError::Node { .. })));
634        let none = r#"{"graph":{"nodes":[{"id":"s","type":"start","error_strategy":"none"}]}}"#;
635        assert!(Workflow::from_json(none).is_ok());
636    }
637}