tinyflows 0.2.0

A Rust-based workflow management solution.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! The tinyflows workflow definition model: a directed graph of typed nodes.
//!
//! A [`WorkflowGraph`] is the serializable source of truth for an automation.
//! Both authoring surfaces — the visual canvas and agent-first chat — produce
//! and edit the *same* `WorkflowGraph`.
//!
//! ## Versioning
//!
//! The JSON wire format is a stable contract. Two version axes make it durable
//! as the model evolves:
//!
//! - [`WorkflowGraph::schema_version`] — the overall model shape. The current
//!   value is [`CURRENT_SCHEMA_VERSION`].
//! - [`Node::type_version`] — the per-kind `config` shape for a node.
//!
//! Both fields are `#[serde(default)]`, so definitions persisted before they
//! existed still load. Load-time upgrades are performed by [`crate::migrate`].

mod node_kind;

pub use node_kind::{NodeKind, TriggerKind};

use serde::{Deserialize, Serialize};

/// The current [`WorkflowGraph`] schema version understood by this crate.
///
/// Graphs persisted with a lower `schema_version` are upgraded on load by
/// [`crate::migrate`]. Bumping this constant is a breaking JSON-format change
/// and must ship with a migration.
///
/// ```
/// assert_eq!(tinyflows::model::CURRENT_SCHEMA_VERSION, 1);
/// ```
pub const CURRENT_SCHEMA_VERSION: u32 = 1;

/// Stable identifier for a node within a [`WorkflowGraph`].
pub type NodeId = String;

/// Serde default for [`WorkflowGraph::schema_version`]: the current schema
/// version, so JSON authored before the field existed loads as up to date.
fn default_schema_version() -> u32 {
    CURRENT_SCHEMA_VERSION
}

/// Serde default for [`Node::type_version`]: the initial version (`1`) for
/// every node kind, so JSON authored before the field existed loads correctly.
fn default_type_version() -> u32 {
    1
}

/// A named input or output connection point on a [`Node`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Port {
    /// The port's stable name (e.g. `"main"`, `"true"`, `"false"`, `"tool"`).
    pub name: String,
    /// Optional human-readable label for the editor.
    #[serde(default)]
    pub label: Option<String>,
}

/// Optional canvas coordinates for a node (ignored by the engine).
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
pub struct Position {
    /// Horizontal position on the canvas.
    pub x: f64,
    /// Vertical position on the canvas.
    pub y: f64,
}

/// A single unit of work in a workflow.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Node {
    /// Unique id within the graph.
    pub id: NodeId,
    /// The kind of work this node performs.
    pub kind: NodeKind,
    /// Version of this node kind's `config` shape. Defaults to `1`; bumped by a
    /// kind when its configuration evolves, with a per-kind load-time migration.
    #[serde(default = "default_type_version")]
    pub type_version: u32,
    /// Human-readable name shown in the editor.
    pub name: String,
    /// Kind-specific configuration as free-form JSON.
    #[serde(default)]
    pub config: serde_json::Value,
    /// Declared output ports (for branching / multi-output nodes).
    #[serde(default)]
    pub ports: Vec<Port>,
    /// Optional canvas position.
    #[serde(default)]
    pub position: Option<Position>,
}

/// A directed connection from one node's output port to another's input port.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Edge {
    /// Source node id.
    pub from_node: NodeId,
    /// Source port name (defaults to `"main"`).
    #[serde(default = "default_port")]
    pub from_port: String,
    /// Target node id.
    pub to_node: NodeId,
    /// Target port name (defaults to `"main"`).
    #[serde(default = "default_port")]
    pub to_port: String,
}

fn default_port() -> String {
    "main".to_string()
}

/// A complete, serializable workflow definition.
///
/// A freshly [`Default`](WorkflowGraph::default)-constructed graph is stamped
/// with the [`CURRENT_SCHEMA_VERSION`], and JSON that omits the version fields
/// deserializes with the same defaults, so persisted and in-memory graphs agree:
///
/// ```
/// use tinyflows::model::{WorkflowGraph, CURRENT_SCHEMA_VERSION};
///
/// let fresh = WorkflowGraph::default();
/// assert_eq!(fresh.schema_version, CURRENT_SCHEMA_VERSION);
///
/// // JSON that predates the `schema_version` field still loads as current.
/// let loaded: WorkflowGraph =
///     serde_json::from_str(r#"{"name":"demo","nodes":[],"edges":[]}"#).unwrap();
/// assert_eq!(loaded.schema_version, CURRENT_SCHEMA_VERSION);
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WorkflowGraph {
    /// Overall model-shape version. Defaults to [`CURRENT_SCHEMA_VERSION`] so
    /// JSON authored before the field existed loads as the current shape;
    /// older persisted values are upgraded by [`crate::migrate`].
    #[serde(default = "default_schema_version")]
    pub schema_version: u32,
    /// Optional stable id of the workflow.
    #[serde(default)]
    pub id: Option<String>,
    /// Human-readable workflow name.
    #[serde(default)]
    pub name: String,
    /// The nodes in the graph.
    #[serde(default)]
    pub nodes: Vec<Node>,
    /// The directed edges connecting node ports.
    #[serde(default)]
    pub edges: Vec<Edge>,
}

impl Default for WorkflowGraph {
    /// A new, empty graph stamped with the [`CURRENT_SCHEMA_VERSION`] (rather
    /// than `0`), so freshly constructed graphs match freshly deserialized ones.
    fn default() -> Self {
        Self {
            schema_version: CURRENT_SCHEMA_VERSION,
            id: None,
            name: String::new(),
            nodes: Vec::new(),
            edges: Vec::new(),
        }
    }
}

impl WorkflowGraph {
    /// Returns the graph's trigger node, if it has exactly one.
    ///
    /// Returns `None` for a graph with zero triggers *or* more than one, so
    /// callers can treat "not exactly one trigger" uniformly.
    ///
    /// ```
    /// use tinyflows::model::WorkflowGraph;
    ///
    /// // An empty graph has no trigger.
    /// assert!(WorkflowGraph::default().trigger().is_none());
    ///
    /// // A graph deserialized with a single trigger returns it.
    /// let graph: WorkflowGraph = serde_json::from_str(
    ///     r#"{"nodes":[{"id":"t","kind":"trigger","name":"start"}],"edges":[]}"#,
    /// )
    /// .unwrap();
    /// assert_eq!(graph.trigger().map(|n| n.id.as_str()), Some("t"));
    /// ```
    #[must_use]
    pub fn trigger(&self) -> Option<&Node> {
        let mut triggers = self.nodes.iter().filter(|n| n.kind == NodeKind::Trigger);
        let first = triggers.next()?;
        match triggers.next() {
            Some(_) => None,
            None => Some(first),
        }
    }

    /// Looks up a node by id.
    #[must_use]
    pub fn node(&self, id: &str) -> Option<&Node> {
        self.nodes.iter().find(|n| n.id == id)
    }

    /// Returns the ids of the **direct** successors of `start` — the target node
    /// of each edge leaving it (immediate neighbors only, not the transitive
    /// closure; ids may repeat if multiple edges connect the same pair).
    ///
    /// ```
    /// use tinyflows::model::WorkflowGraph;
    ///
    /// let graph: WorkflowGraph = serde_json::from_str(
    ///     r#"{
    ///       "nodes":[
    ///         {"id":"t","kind":"trigger","name":"start"},
    ///         {"id":"a","kind":"agent","name":"a"}
    ///       ],
    ///       "edges":[{"from_node":"t","to_node":"a"}]
    ///     }"#,
    /// )
    /// .unwrap();
    /// assert_eq!(graph.successors("t"), vec!["a"]);
    /// assert!(graph.successors("a").is_empty());
    /// ```
    #[must_use]
    pub fn successors(&self, start: &str) -> Vec<&str> {
        self.edges
            .iter()
            .filter(|e| e.from_node == start)
            .map(|e| e.to_node.as_str())
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn node(id: &str, kind: NodeKind) -> Node {
        Node {
            id: id.to_string(),
            kind,
            type_version: 1,
            name: id.to_string(),
            config: serde_json::Value::Null,
            ports: Vec::new(),
            position: None,
        }
    }

    #[test]
    fn json_round_trips() {
        let graph = WorkflowGraph {
            schema_version: CURRENT_SCHEMA_VERSION,
            id: Some("wf_1".to_string()),
            name: "demo".to_string(),
            nodes: vec![node("t", NodeKind::Trigger), node("a", NodeKind::Agent)],
            edges: vec![Edge {
                from_node: "t".to_string(),
                from_port: "main".to_string(),
                to_node: "a".to_string(),
                to_port: "main".to_string(),
            }],
        };
        let json = serde_json::to_string(&graph).expect("serialize");
        let back: WorkflowGraph = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(graph, back);
    }

    #[test]
    fn edge_ports_default_to_main() {
        let json = r#"{"from_node":"t","to_node":"a"}"#;
        let edge: Edge = serde_json::from_str(json).expect("deserialize");
        assert_eq!(edge.from_port, "main");
        assert_eq!(edge.to_port, "main");
    }

    #[test]
    fn trigger_and_lookup() {
        let graph = WorkflowGraph {
            nodes: vec![node("t", NodeKind::Trigger), node("a", NodeKind::Agent)],
            ..Default::default()
        };
        assert_eq!(graph.trigger().map(|n| n.id.as_str()), Some("t"));
        assert_eq!(graph.node("a").map(|n| n.id.as_str()), Some("a"));
        assert!(graph.node("missing").is_none());
    }

    #[test]
    fn default_stamps_current_schema_version() {
        let graph = WorkflowGraph::default();
        assert_eq!(graph.schema_version, CURRENT_SCHEMA_VERSION);
        assert_eq!(graph.schema_version, 1);
        assert!(graph.id.is_none());
        assert_eq!(graph.name, "");
        assert!(graph.nodes.is_empty());
        assert!(graph.edges.is_empty());
    }

    #[test]
    fn trigger_returns_none_with_zero_triggers() {
        let graph = WorkflowGraph {
            nodes: vec![node("a", NodeKind::Agent)],
            ..Default::default()
        };
        assert!(graph.trigger().is_none());
    }

    #[test]
    fn trigger_returns_none_with_multiple_triggers() {
        let graph = WorkflowGraph {
            nodes: vec![node("t1", NodeKind::Trigger), node("t2", NodeKind::Trigger)],
            ..Default::default()
        };
        assert!(graph.trigger().is_none());
    }

    #[test]
    fn trigger_returns_the_single_trigger() {
        let graph = WorkflowGraph {
            nodes: vec![node("a", NodeKind::Agent), node("t", NodeKind::Trigger)],
            ..Default::default()
        };
        assert_eq!(graph.trigger().map(|n| n.id.as_str()), Some("t"));
    }

    #[test]
    fn successors_lists_direct_edge_targets() {
        let graph = WorkflowGraph {
            nodes: vec![
                node("t", NodeKind::Trigger),
                node("a", NodeKind::Agent),
                node("b", NodeKind::Agent),
            ],
            edges: vec![
                Edge {
                    from_node: "t".to_string(),
                    from_port: "main".to_string(),
                    to_node: "a".to_string(),
                    to_port: "main".to_string(),
                },
                Edge {
                    from_node: "t".to_string(),
                    from_port: "main".to_string(),
                    to_node: "b".to_string(),
                    to_port: "main".to_string(),
                },
            ],
            ..Default::default()
        };
        assert_eq!(graph.successors("t"), vec!["a", "b"]);
        assert!(graph.successors("a").is_empty());
        assert!(graph.successors("missing").is_empty());
    }

    #[test]
    fn successors_may_repeat_for_parallel_edges() {
        let graph = WorkflowGraph {
            nodes: vec![node("t", NodeKind::Trigger), node("a", NodeKind::Agent)],
            edges: vec![
                Edge {
                    from_node: "t".to_string(),
                    from_port: "main".to_string(),
                    to_node: "a".to_string(),
                    to_port: "main".to_string(),
                },
                Edge {
                    from_node: "t".to_string(),
                    from_port: "other".to_string(),
                    to_node: "a".to_string(),
                    to_port: "main".to_string(),
                },
            ],
            ..Default::default()
        };
        assert_eq!(graph.successors("t"), vec!["a", "a"]);
    }

    #[test]
    fn round_trip_preserves_version_fields() {
        let graph = WorkflowGraph {
            schema_version: CURRENT_SCHEMA_VERSION,
            id: Some("wf_1".to_string()),
            name: "demo".to_string(),
            nodes: vec![Node {
                id: "t".to_string(),
                kind: NodeKind::Trigger,
                type_version: 3,
                name: "t".to_string(),
                config: serde_json::json!({"mode": "manual"}),
                ports: Vec::new(),
                position: None,
            }],
            edges: Vec::new(),
        };
        let json = serde_json::to_string(&graph).expect("serialize");
        assert!(json.contains("\"schema_version\":1"));
        assert!(json.contains("\"type_version\":3"));
        let back: WorkflowGraph = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(graph, back);
        assert_eq!(back.nodes[0].type_version, 3);
    }

    #[test]
    fn omitted_version_fields_use_serde_defaults() {
        // A graph and node authored before the version fields existed.
        let json = r#"{
            "name": "legacy",
            "nodes": [{"id": "t", "kind": "trigger", "name": "start"}],
            "edges": []
        }"#;
        let graph: WorkflowGraph = serde_json::from_str(json).expect("deserialize");
        assert_eq!(graph.schema_version, CURRENT_SCHEMA_VERSION);
        assert_eq!(graph.nodes[0].type_version, default_type_version());
        assert_eq!(graph.nodes[0].type_version, 1);
        // Other `#[serde(default)]` fields fill in too.
        assert!(graph.id.is_none());
        assert!(graph.nodes[0].config.is_null());
        assert!(graph.nodes[0].ports.is_empty());
        assert!(graph.nodes[0].position.is_none());
    }

    #[test]
    fn edge_from_port_defaults_to_main() {
        let json = r#"{"from_node":"t","to_node":"a","to_port":"custom"}"#;
        let edge: Edge = serde_json::from_str(json).expect("deserialize");
        assert_eq!(edge.from_port, "main");
        assert_eq!(edge.to_port, "custom");
    }
}