salvor-graph 0.5.1

Pure, IO-free graph document model, strict versioned validation, and JSON Schema emission for the Salvor v0.4 graph API
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
//! A fluent, typed builder for a graph [`Graph`] document.
//!
//! The document model in [`crate::document`] is the wire format: strict,
//! adjacently tagged, and easy to get wrong by hand (a stray key, a payload
//! nested under the wrong tag, an edge that names a field instead of a node).
//! This builder is the author-facing front door. It never invents a new format;
//! it constructs the same [`Graph`] the model already defines, so whatever this
//! builder emits parses and validates exactly as a hand-written document would.
//!
//! # What the types buy you
//!
//! Each node kind has its own spec type ([`AgentSpec`], [`ToolSpec`],
//! [`GateSpec`], [`BranchSpec`], [`MapSpec`], [`FoldSpec`]) whose constructor demands the
//! fields that kind cannot do without: an agent needs its hash, a tool needs its
//! name, a gate needs its approval schema. A field that belongs to one kind is
//! not reachable on another, so "a gate with an agent_hash" is not a runtime
//! error, it is a shape you cannot write. The optional fields are chained
//! methods, present only where the model allows them. The result is that a
//! STRUCTURALLY malformed document is hard to express.
//!
//! # Where the builder stops
//!
//! Typed construction stops at structure. It does NOT check that an agent hash
//! is 64 hex digits, that a map's concurrency is positive, that edges name real
//! nodes, or that the graph is acyclic. Those are SEMANTIC rules, and they stay
//! with [`crate::validate`], which runs over the built `Graph` the same way it
//! runs over a parsed one. Build to get a well-shaped document; validate to
//! learn whether it is a legal one.
//!
//! # Authoring the canonical flow
//!
//! ```
//! use salvor_graph::{AgentSpec, GateSpec, GraphBuilder, ToolSpec};
//! use serde_json::json;
//!
//! let draft = json!({
//!     "type": "object",
//!     "properties": { "draft": { "type": "string" } },
//!     "required": ["draft"]
//! });
//!
//! let graph = GraphBuilder::new()
//!     .agent(
//!         AgentSpec::new("research", format!("sha256:{}", "1".repeat(64)))
//!             .output_schema(draft.clone()),
//!     )
//!     .agent(
//!         AgentSpec::new("review", format!("sha256:{}", "2".repeat(64)))
//!             .input_schema(draft.clone())
//!             .output_schema(draft),
//!     )
//!     .gate(
//!         GateSpec::new(
//!             "approve",
//!             json!({
//!                 "type": "object",
//!                 "properties": { "approved": { "type": "boolean" } },
//!                 "required": ["approved"]
//!             }),
//!         )
//!         .prompt("Approve this draft for publication?"),
//!     )
//!     .tool(
//!         ToolSpec::new("publish", "http_post")
//!             .input("body", "approve.draft")
//!             .input("url", "config.publish_url"),
//!     )
//!     .edge("research", "review")
//!     .edge("review", "approve")
//!     .edge("approve", "publish")
//!     .build();
//!
//! // Structure is done; semantics are a separate pass.
//! let summary = salvor_graph::validate(&graph).expect("the canonical flow is valid");
//! assert_eq!(summary.entry_nodes, ["research"]);
//! assert_eq!(summary.terminal_nodes, ["publish"]);
//! ```

use serde_json::Value;

use crate::document::{
    AgentNode, BranchCase, BranchCondition, BranchNode, Edge, FoldBody, FoldJoin, FoldNode,
    GateNode, Graph, MapBody, MapNode, Node, SCHEMA_VERSION, ToolNode,
};

/// Accumulates nodes and edges, then freezes them into a [`Graph`].
///
/// Every `node`-adding method takes a per-kind spec and returns `self`, so a
/// whole document reads as one chain ending in [`build`](GraphBuilder::build).
/// The builder stamps [`SCHEMA_VERSION`] onto the document, so an author never
/// writes the version by hand.
#[derive(Clone, Debug, Default)]
pub struct GraphBuilder {
    nodes: Vec<Node>,
    edges: Vec<Edge>,
}

impl GraphBuilder {
    /// Starts an empty builder.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds an `agent` node from its [`AgentSpec`].
    #[must_use]
    pub fn agent(mut self, spec: AgentSpec) -> Self {
        self.nodes.push(spec.into_node());
        self
    }

    /// Adds a `tool` node from its [`ToolSpec`].
    #[must_use]
    pub fn tool(mut self, spec: ToolSpec) -> Self {
        self.nodes.push(spec.into_node());
        self
    }

    /// Adds a `gate` node from its [`GateSpec`].
    #[must_use]
    pub fn gate(mut self, spec: GateSpec) -> Self {
        self.nodes.push(spec.into_node());
        self
    }

    /// Adds a `branch` node from its [`BranchSpec`].
    #[must_use]
    pub fn branch(mut self, spec: BranchSpec) -> Self {
        self.nodes.push(spec.into_node());
        self
    }

    /// Adds a `map` node from its [`MapSpec`].
    #[must_use]
    pub fn map(mut self, spec: MapSpec) -> Self {
        self.nodes.push(spec.into_node());
        self
    }

    /// Adds a `fold` node from its [`FoldSpec`].
    #[must_use]
    pub fn fold(mut self, spec: FoldSpec) -> Self {
        self.nodes.push(spec.into_node());
        self
    }

    /// Adds a plain edge from one node id to another.
    #[must_use]
    pub fn edge(mut self, from: impl Into<String>, to: impl Into<String>) -> Self {
        self.edges.push(Edge {
            from: from.into(),
            to: to.into(),
            label: None,
        });
        self
    }

    /// Adds a labeled edge. The label names the [`BranchCase`] this edge
    /// realizes when the source is a `branch`.
    #[must_use]
    pub fn labeled_edge(
        mut self,
        from: impl Into<String>,
        to: impl Into<String>,
        label: impl Into<String>,
    ) -> Self {
        self.edges.push(Edge {
            from: from.into(),
            to: to.into(),
            label: Some(label.into()),
        });
        self
    }

    /// Freezes the accumulated nodes and edges into a [`Graph`], stamping the
    /// current [`SCHEMA_VERSION`].
    ///
    /// Structure only: run [`crate::validate`] on the result to check the
    /// semantic rules (hash shape, referential integrity, acyclicity, and the
    /// rest).
    #[must_use]
    pub fn build(self) -> Graph {
        Graph {
            schema_version: SCHEMA_VERSION,
            nodes: self.nodes,
            edges: self.edges,
        }
    }
}

/// The spec for an `agent` node: a full agent loop referenced by content hash.
#[derive(Clone, Debug)]
pub struct AgentSpec {
    id: String,
    agent_hash: String,
    name: Option<String>,
    input_schema: Option<Value>,
    output_schema: Option<Value>,
}

impl AgentSpec {
    /// Starts an agent spec with its two required fields: the node id and the
    /// `sha256:<64 hex>` agent hash. The hash form is checked by
    /// [`crate::validate`], not here.
    pub fn new(id: impl Into<String>, agent_hash: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            agent_hash: agent_hash.into(),
            name: None,
            input_schema: None,
            output_schema: None,
        }
    }

    /// Sets a short display label for this node. Bounds (a 64-character cap,
    /// not empty or all whitespace) are checked by [`crate::validate`], not
    /// here; see [`crate::document`]'s "The optional node display name"
    /// section for why this field, unlike an agent's own `name`, is part of
    /// the graph's content hash.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Declares the JSON Schema for the payload this agent consumes.
    #[must_use]
    pub fn input_schema(mut self, schema: Value) -> Self {
        self.input_schema = Some(schema);
        self
    }

    /// Declares the JSON Schema for the payload this agent produces.
    #[must_use]
    pub fn output_schema(mut self, schema: Value) -> Self {
        self.output_schema = Some(schema);
        self
    }

    fn into_node(self) -> Node {
        Node::Agent(AgentNode {
            id: self.id,
            agent_hash: self.agent_hash,
            name: self.name,
            input_schema: self.input_schema,
            output_schema: self.output_schema,
        })
    }
}

/// The spec for a `tool` node: one direct tool invocation.
#[derive(Clone, Debug)]
pub struct ToolSpec {
    id: String,
    tool: String,
    name: Option<String>,
    input: std::collections::BTreeMap<String, String>,
    input_schema: Option<Value>,
    output_schema: Option<Value>,
}

impl ToolSpec {
    /// Starts a tool spec with its required fields: the node id and the
    /// registered tool name.
    pub fn new(id: impl Into<String>, tool: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            tool: tool.into(),
            name: None,
            input: std::collections::BTreeMap::new(),
            input_schema: None,
            output_schema: None,
        }
    }

    /// Sets a short display label for this node. Bounds (a 64-character cap,
    /// not empty or all whitespace) are checked by [`crate::validate`], not
    /// here; see [`crate::document`]'s "The optional node display name"
    /// section for why this field, unlike an agent's own `name`, is part of
    /// the graph's content hash.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Adds one input mapping: a tool input field name to an opaque source
    /// reference. Recorded as data; not resolved by this crate.
    #[must_use]
    pub fn input(mut self, field: impl Into<String>, source: impl Into<String>) -> Self {
        self.input.insert(field.into(), source.into());
        self
    }

    /// Declares the JSON Schema for the payload this tool consumes.
    #[must_use]
    pub fn input_schema(mut self, schema: Value) -> Self {
        self.input_schema = Some(schema);
        self
    }

    /// Declares the JSON Schema for the payload this tool produces.
    #[must_use]
    pub fn output_schema(mut self, schema: Value) -> Self {
        self.output_schema = Some(schema);
        self
    }

    fn into_node(self) -> Node {
        Node::Tool(ToolNode {
            id: self.id,
            tool: self.tool,
            name: self.name,
            input: self.input,
            input_schema: self.input_schema,
            output_schema: self.output_schema,
        })
    }
}

/// The spec for a `gate` node: human approval that suspends the run.
#[derive(Clone, Debug)]
pub struct GateSpec {
    id: String,
    name: Option<String>,
    prompt: Option<String>,
    approval_schema: Value,
}

impl GateSpec {
    /// Starts a gate spec with its required fields: the node id and the JSON
    /// Schema the approval input must satisfy. A gate with no declared approval
    /// shape is meaningless, so the schema is not optional.
    pub fn new(id: impl Into<String>, approval_schema: Value) -> Self {
        Self {
            id: id.into(),
            name: None,
            prompt: None,
            approval_schema,
        }
    }

    /// Sets a short display label for this node. Bounds (a 64-character cap,
    /// not empty or all whitespace) are checked by [`crate::validate`], not
    /// here; see [`crate::document`]'s "The optional node display name"
    /// section for why this field, unlike an agent's own `name`, is part of
    /// the graph's content hash.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Sets the human-readable prompt shown in the approval inbox.
    #[must_use]
    pub fn prompt(mut self, prompt: impl Into<String>) -> Self {
        self.prompt = Some(prompt.into());
        self
    }

    fn into_node(self) -> Node {
        Node::Gate(GateNode {
            id: self.id,
            name: self.name,
            prompt: self.prompt,
            approval_schema: self.approval_schema,
        })
    }
}

/// The spec for a `branch` node: routes on a typed output.
#[derive(Clone, Debug)]
pub struct BranchSpec {
    id: String,
    name: Option<String>,
    on: Option<String>,
    agent_hash: Option<String>,
    cases: Vec<BranchCase>,
}

impl BranchSpec {
    /// Starts a branch spec with its required node id. Cases are added with
    /// [`case`](BranchSpec::case).
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            name: None,
            on: None,
            agent_hash: None,
            cases: Vec::new(),
        }
    }

    /// Sets a short display label for this node. Bounds (a 64-character cap,
    /// not empty or all whitespace) are checked by [`crate::validate`], not
    /// here; see [`crate::document`]'s "The optional node display name"
    /// section for why this field, unlike an agent's own `name`, is part of
    /// the graph's content hash.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Sets the opaque reference to the typed value the branch routes on.
    #[must_use]
    pub fn on(mut self, on: impl Into<String>) -> Self {
        self.on = Some(on.into());
        self
    }

    /// Sets the `sha256:<64 hex>` hash of the agent that decides a
    /// [`BranchCondition::ModelDecision`] case. Required by [`crate::validate`]
    /// on any branch that carries a model-decision case; the hash form is
    /// checked there, not here.
    #[must_use]
    pub fn agent_hash(mut self, agent_hash: impl Into<String>) -> Self {
        self.agent_hash = Some(agent_hash.into());
        self
    }

    /// Adds a named case selected by the given condition. The route it realizes
    /// is a [`labeled_edge`](GraphBuilder::labeled_edge) whose label matches the
    /// case name.
    #[must_use]
    pub fn case(mut self, name: impl Into<String>, when: BranchCondition) -> Self {
        self.cases.push(BranchCase {
            name: name.into(),
            when,
        });
        self
    }

    fn into_node(self) -> Node {
        Node::Branch(BranchNode {
            id: self.id,
            name: self.name,
            on: self.on,
            agent_hash: self.agent_hash,
            cases: self.cases,
        })
    }
}

/// The spec for a `map` node: fan-out a sub-run per element of a typed list,
/// with a concurrency cap.
#[derive(Clone, Debug)]
pub struct MapSpec {
    id: String,
    name: Option<String>,
    over: String,
    concurrency: u32,
    body: MapBody,
    output_schema: Option<Value>,
}

impl MapSpec {
    /// Starts a map spec with its required fields: the node id, the opaque
    /// reference to the list it fans out over, the concurrency cap, and the
    /// [`MapBody`] each element is mapped through.
    pub fn new(
        id: impl Into<String>,
        over: impl Into<String>,
        concurrency: u32,
        body: MapBody,
    ) -> Self {
        Self {
            id: id.into(),
            name: None,
            over: over.into(),
            concurrency,
            body,
            output_schema: None,
        }
    }

    /// Sets a short display label for this node. Bounds (a 64-character cap,
    /// not empty or all whitespace) are checked by [`crate::validate`], not
    /// here; see [`crate::document`]'s "The optional node display name"
    /// section for why this field, unlike an agent's own `name`, is part of
    /// the graph's content hash.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Declares the JSON Schema for the joined list this node produces.
    #[must_use]
    pub fn output_schema(mut self, schema: Value) -> Self {
        self.output_schema = Some(schema);
        self
    }

    fn into_node(self) -> Node {
        Node::Map(MapNode {
            id: self.id,
            name: self.name,
            over: self.over,
            concurrency: self.concurrency,
            body: self.body,
            output_schema: self.output_schema,
        })
    }
}

/// The spec for a `fold` node: bounded iteration that accumulates across passes.
#[derive(Clone, Debug)]
pub struct FoldSpec {
    id: String,
    name: Option<String>,
    body: FoldBody,
    max_iterations: u32,
    stop_when: String,
    join: FoldJoin,
    accumulator_schema: Option<Value>,
}

impl FoldSpec {
    /// Starts a fold spec with its required fields: the node id, the
    /// [`FoldBody`] each pass runs, the iteration bound, the `stop_when`
    /// predicate, and the [`FoldJoin`] rule. The bound's positivity, the
    /// predicate's parse, and a `best_by` reference's shape are checked by
    /// [`crate::validate`], not here.
    pub fn new(
        id: impl Into<String>,
        body: FoldBody,
        max_iterations: u32,
        stop_when: impl Into<String>,
        join: FoldJoin,
    ) -> Self {
        Self {
            id: id.into(),
            name: None,
            body,
            max_iterations,
            stop_when: stop_when.into(),
            join,
            accumulator_schema: None,
        }
    }

    /// Sets a short display label for this node. Bounds (a 64-character cap,
    /// not empty or all whitespace) are checked by [`crate::validate`], not
    /// here; see [`crate::document`]'s "The optional node display name"
    /// section for why this field, unlike an agent's own `name`, is part of
    /// the graph's content hash.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Declares the JSON Schema for the accumulated value the loop carries and
    /// produces. Data only, like an agent's `output_schema`.
    #[must_use]
    pub fn accumulator_schema(mut self, schema: Value) -> Self {
        self.accumulator_schema = Some(schema);
        self
    }

    fn into_node(self) -> Node {
        Node::Fold(FoldNode {
            id: self.id,
            name: self.name,
            body: self.body,
            max_iterations: self.max_iterations,
            stop_when: self.stop_when,
            join: self.join,
            accumulator_schema: self.accumulator_schema,
        })
    }
}

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

    /// A schema shape reused by several nodes in the canonical flow.
    fn draft_schema() -> Value {
        json!({
            "type": "object",
            "properties": { "draft": { "type": "string" } },
            "required": ["draft"]
        })
    }

    /// Builds the exact research -> review -> approve -> publish flow the
    /// canonical fixture records.
    fn canonical_flow() -> Graph {
        GraphBuilder::new()
            .agent(
                AgentSpec::new("research", format!("sha256:{}", "1".repeat(64)))
                    .output_schema(draft_schema()),
            )
            .agent(
                AgentSpec::new("review", format!("sha256:{}", "2".repeat(64)))
                    .input_schema(draft_schema())
                    .output_schema(draft_schema()),
            )
            .gate(
                GateSpec::new(
                    "approve",
                    json!({
                        "type": "object",
                        "properties": { "approved": { "type": "boolean" } },
                        "required": ["approved"]
                    }),
                )
                .prompt("Approve this draft for publication?"),
            )
            .tool(
                ToolSpec::new("publish", "http_post")
                    .input("body", "approve.draft")
                    .input("url", "config.publish_url"),
            )
            .edge("research", "review")
            .edge("review", "approve")
            .edge("approve", "publish")
            .build()
    }

    /// The builder emits a document structurally equal to the canonical fixture
    /// that keeps all three language builders honest.
    #[test]
    fn builds_the_canonical_document() {
        let built = serde_json::to_value(canonical_flow()).expect("serialize built graph");
        let canonical: Value = serde_json::from_str(include_str!(
            "../../../examples/graphs/research-review-publish.json"
        ))
        .expect("parse canonical fixture");
        assert_eq!(
            built, canonical,
            "builder output must match the canonical fixture exactly"
        );
    }

    /// Builds the exact fold-refine flow the cross-language `fold-refine`
    /// fixture records, so the Rust, TypeScript, and Python fold builders all
    /// reduce to one canonical document.
    fn fold_flow() -> Graph {
        use crate::document::{FoldBody, FoldJoin};

        let score_schema = json!({
            "type": "object",
            "properties": { "score": { "type": "number" } },
            "required": ["score"]
        });
        GraphBuilder::new()
            .agent(
                AgentSpec::new("tailor", format!("sha256:{}", "3".repeat(64)))
                    .output_schema(score_schema.clone()),
            )
            .fold(
                FoldSpec::new(
                    "refine",
                    FoldBody::Node("tailor".into()),
                    3,
                    "score >= 0.85",
                    FoldJoin::BestBy("score".into()),
                )
                .name("Refine to threshold")
                .accumulator_schema(score_schema),
            )
            .build()
    }

    /// The builder emits a fold document structurally equal to the shared
    /// fold-refine fixture that keeps all three language builders honest.
    #[test]
    fn builds_the_fold_document() {
        let built = serde_json::to_value(fold_flow()).expect("serialize built graph");
        let canonical: Value =
            serde_json::from_str(include_str!("../../../examples/graphs/fold-refine.json"))
                .expect("parse fold fixture");
        assert_eq!(
            built, canonical,
            "builder output must match the fold fixture exactly"
        );
    }

    /// The built fold flow passes semantic validation.
    #[test]
    fn fold_document_validates() {
        let summary = crate::validate(&fold_flow()).expect("fold flow is valid");
        assert_eq!(summary.node_count, 2);
        assert_eq!(summary.edge_count, 0);
    }

    /// The built canonical flow passes semantic validation.
    #[test]
    fn canonical_document_validates() {
        let summary = crate::validate(&canonical_flow()).expect("canonical flow is valid");
        assert_eq!(summary.node_count, 4);
        assert_eq!(summary.edge_count, 3);
        assert_eq!(summary.entry_nodes, vec!["research"]);
        assert_eq!(summary.terminal_nodes, vec!["publish"]);
    }

    /// The branch and map specs build the shapes the model expects: an unset
    /// optional field stays off the wire, and a labeled edge realizes a case.
    #[test]
    fn branch_and_map_specs_build_expected_shapes() {
        let graph = GraphBuilder::new()
            .agent(AgentSpec::new(
                "score",
                format!("sha256:{}", "a".repeat(64)),
            ))
            .branch(
                BranchSpec::new("route")
                    .on("score.value")
                    .case("high", BranchCondition::Expression("score > 0.8".into()))
                    .case("ask", BranchCondition::ModelDecision),
            )
            .agent(AgentSpec::new(
                "worker",
                format!("sha256:{}", "b".repeat(64)),
            ))
            .map(MapSpec::new(
                "fanout",
                "route.items",
                4,
                MapBody::Node("worker".into()),
            ))
            .edge("score", "route")
            .labeled_edge("route", "fanout", "high")
            .build();

        // The map node serializes with no output_schema key, because the spec
        // never set one.
        let value = serde_json::to_value(&graph).expect("serialize");
        let map_payload = value["nodes"][3]["payload"].clone();
        assert!(
            map_payload.get("output_schema").is_none(),
            "unset optional field must stay off the wire: {map_payload}"
        );
        assert_eq!(value["edges"][1]["label"], json!("high"));
    }

    /// The fold spec builds the shape the model expects: the body, bound, stop
    /// predicate, and join land in the payload, an unset `accumulator_schema`
    /// stays off the wire, and the document validates.
    #[test]
    fn fold_spec_builds_expected_shape() {
        use crate::document::{FoldBody, FoldJoin};

        let graph = GraphBuilder::new()
            .agent(AgentSpec::new(
                "tailor",
                format!("sha256:{}", "a".repeat(64)),
            ))
            .fold(
                FoldSpec::new(
                    "refine",
                    FoldBody::Node("tailor".into()),
                    3,
                    "score >= 0.85",
                    FoldJoin::BestBy("score".into()),
                )
                .name("Refine to threshold"),
            )
            .build();

        let summary = crate::validate(&graph).expect("the fold flow is valid");
        assert_eq!(summary.node_count, 2);

        let value = serde_json::to_value(&graph).expect("serialize");
        let payload = &value["nodes"][1]["payload"];
        assert_eq!(value["nodes"][1]["kind"], json!("fold"));
        assert_eq!(payload["max_iterations"], json!(3));
        assert_eq!(payload["stop_when"], json!("score >= 0.85"));
        assert_eq!(
            payload["join"],
            json!({"kind": "best_by", "value": "score"})
        );
        assert_eq!(payload["body"], json!({"kind": "node", "value": "tailor"}));
        assert_eq!(payload["name"], json!("Refine to threshold"));
        assert!(
            payload.get("accumulator_schema").is_none(),
            "unset optional field must stay off the wire: {payload}"
        );
    }

    /// `.name(...)` is available on every node kind's spec, puts the name on
    /// the wire when set, and validates clean; a sibling node with no `.name`
    /// call carries none, proving the two coexist in one document.
    #[test]
    fn every_spec_kind_accepts_a_display_name() {
        let graph = GraphBuilder::new()
            .agent(
                AgentSpec::new("research", format!("sha256:{}", "1".repeat(64)))
                    .name("Research the topic"),
            )
            .tool(ToolSpec::new("publish", "http_post").name("Publish the draft"))
            .gate(GateSpec::new("approve", json!({"type": "object"})).name("Approve the draft"))
            .branch(
                BranchSpec::new("route")
                    .name("Route on confidence")
                    .case("high", BranchCondition::Expression("score > 0.8".into())),
            )
            .map(
                MapSpec::new("fanout", "route.items", 2, MapBody::Node("research".into()))
                    .name("Notify each watcher"),
            )
            .edge("research", "publish")
            .build();

        let summary = crate::validate(&graph).expect("named nodes still validate");
        assert_eq!(summary.node_count, 5);

        let value = serde_json::to_value(&graph).expect("serialize");
        for (index, expected) in [
            (0, "Research the topic"),
            (1, "Publish the draft"),
            (2, "Approve the draft"),
            (3, "Route on confidence"),
            (4, "Notify each watcher"),
        ] {
            assert_eq!(
                value["nodes"][index]["payload"]["name"],
                json!(expected),
                "node {index} carries its display name on the wire"
            );
        }
    }
}