engenho-substrate 0.53.140

engenho-substrate — the substrate leaf: every module a shipped engenho crate references (derivations and caches, receipts, quorum, ledgers, verifiers, rollout gates, freshness, owned tasks), with engenho-substrate-core re-exported whole so every engenho_substrate:: path keeps resolving.
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
//! roça — typed materialization-DAG primitive.
//!
//! `Plantio` (Portuguese: *planting*; the cleared field becomes a
//! planted field) is the substrate's typed DAG-value of stages.
//! Each `Stage` names a shape, its prerequisites, its verifiers,
//! its confirmation policy, and where to materialize it.
//!
//! ## Pure-data layer
//!
//! This module ships ONLY the typed values + topology helpers.
//! No controller, no scheduler, no runtime. The DAG compiles to
//! a list of `(StageId, NodeId)` materialization jobs the next
//! layer (`PlantioController`) dispatches.
//!
//! ## Composition with prior primitives
//!
//! - `Stage.shape: WorkloadShape` — from `crate::shape`
//! - `Stage.verify: Vec<Verificacao>` — from `crate::verifier`
//! - `Stage.confirm: ConfirmacaoPolicy` — references `QuorumTracker`
//!   (the next-round controller composes them)
//! - `Stage.depends_on: BTreeSet<StageId>` — typed topology
//! - `Stage.placement: Placement` — typed scheduler hint
//!
//! ## Topology validation
//!
//! `Plantio::validate()` returns `Ok(())` only when:
//!   * Every `depends_on` reference points to a known stage.
//!   * The DAG is acyclic (deterministic Kahn-style sort succeeds).
//!   * No two stages share a `StageId`.

use std::collections::{BTreeMap, BTreeSet, VecDeque};

use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::receipt::NodeId;
use crate::shape::WorkloadShape;
use crate::verifier::Verificacao;

/// Stable stage identifier within a Plantio. Operator-chosen
/// (typically human-readable like "build-image" or "deploy-pod").
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct StageId(pub String);

impl StageId {
    /// Construct from a string.
    #[must_use]
    pub fn new(s: impl Into<String>) -> Self {
        Self(s.into())
    }

    /// Borrow as `&str`.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for StageId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

/// Parse-boundary refusal for a stage threshold `k`.
///
/// `k` counts nodes or receipts, so zero is not a weaker quorum — it is
/// a policy no fold can honour. Every consumer downstream of here had
/// independently rounded it up to one (`Placement::min_nodes`,
/// `Plantio::compile_jobs`, the controller's `threshold_for`), which
/// means an operator who wrote `"k": 0` got a one-node quorum and no
/// word about it. This refuses the value where the CR is *read*,
/// instead of repairing it at each place it is used. Wire format is
/// unchanged: every `k` a valid CR already carries still parses.
fn de_threshold_k<'de, D>(de: D) -> Result<usize, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let k = usize::deserialize(de)?;
    if k == 0 {
        return Err(serde::de::Error::invalid_value(
            serde::de::Unexpected::Unsigned(0),
            &"k: a threshold of at least 1",
        ));
    }
    Ok(k)
}

/// Where a stage should be materialized.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Placement {
    /// Exactly one specific node.
    Pinned {
        /// Target node identity.
        node: NodeId,
    },
    /// Any one node — first available wins.
    AnyOne,
    /// Any K nodes — load-spreading without agreement requirement.
    AnyK {
        /// How many nodes. `0` is refused at parse; see
        /// [`de_threshold_k`].
        #[serde(deserialize_with = "de_threshold_k")]
        k: usize,
    },
    /// Quorum — K nodes, BLAKE3-agreement required (typed Dissent
    /// from `QuorumTracker` if disagreement detected).
    Quorum {
        /// Quorum threshold. `0` is refused at parse; see
        /// [`de_threshold_k`].
        #[serde(deserialize_with = "de_threshold_k")]
        k: usize,
    },
    /// Every node in the cluster.
    AllNodes,
}

impl Placement {
    /// Minimum nodes required for this placement to be satisfied.
    /// `AllNodes` returns `None` (depends on dynamic cluster size).
    ///
    /// The `.max(1)` is the residue of the old repair-at-use design.
    /// A parsed `Placement` can no longer carry a zero (see
    /// [`de_threshold_k`]), so it only covers a value built in Rust;
    /// it disappears when `k` becomes a `NonZeroUsize`.
    #[must_use]
    pub fn min_nodes(&self) -> Option<usize> {
        match self {
            Self::Pinned { .. } | Self::AnyOne => Some(1),
            Self::AnyK { k } | Self::Quorum { k } => Some((*k).max(1)),
            Self::AllNodes => None,
        }
    }

    /// True if the placement requires agreement across nodes (i.e.
    /// `Quorum` or `AllNodes`).
    #[must_use]
    pub fn requires_agreement(&self) -> bool {
        matches!(self, Self::Quorum { .. } | Self::AllNodes)
    }
}

/// How the DAG decides a stage is confirmed.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ConfirmacaoPolicy {
    /// Local-only — this node's own receipt suffices.
    Local,
    /// K receipts gossiped via chitchat must reach this node.
    Quorum {
        /// Receipt threshold. `0` is refused at parse; see
        /// [`de_threshold_k`].
        #[serde(deserialize_with = "de_threshold_k")]
        k: usize,
    },
    /// Every placement target must produce a receipt.
    All,
    /// Strong consistency — Raft commit required.
    RaftCommitted,
}

impl Default for ConfirmacaoPolicy {
    fn default() -> Self {
        Self::Local
    }
}

/// One stage of the materialization DAG.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Stage {
    /// Stable identity within the Plantio.
    pub id: StageId,
    /// What shape this stage produces.
    pub shape: WorkloadShape,
    /// Stages that must reach `Confirmed` before this one starts.
    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
    pub depends_on: BTreeSet<StageId>,
    /// Verification predicates — ALL must pass before Confirmed.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub verify: Vec<Verificacao>,
    /// How the DAG knows the stage is confirmed.
    #[serde(default)]
    pub confirm: ConfirmacaoPolicy,
    /// Where to materialize.
    pub placement: Placement,
}

impl Stage {
    /// Minimal constructor — single-node Pinned placement.
    #[must_use]
    pub fn pinned(id: impl Into<String>, shape: WorkloadShape, node: NodeId) -> Self {
        Self {
            id: StageId::new(id),
            shape,
            depends_on: BTreeSet::new(),
            verify: Vec::new(),
            confirm: ConfirmacaoPolicy::Local,
            placement: Placement::Pinned { node },
        }
    }
}

/// Validation errors for a Plantio.
#[derive(Debug, Clone, Error)]
pub enum PlantioError {
    /// A `depends_on` reference points at an unknown StageId.
    #[error("unknown dependency: stage {stage} depends on {dependency}")]
    UnknownDependency {
        /// Stage that has the dangling reference.
        stage: StageId,
        /// The reference that doesn't resolve.
        dependency: StageId,
    },
    /// The DAG contains a cycle.
    #[error("cycle detected (remaining stages: {remaining:?})")]
    Cycle {
        /// Stages that couldn't be topologically sorted.
        remaining: Vec<StageId>,
    },
    /// A stage was added twice under the same ID.
    #[error("duplicate stage id: {0}")]
    DuplicateId(StageId),
}

crate::impl_error_kind! {
    PlantioError {
        { UnknownDependency { .. } } => "unknown_dependency",
        { Cycle { .. } } => "cycle",
        (DuplicateId(_)) => "duplicate_id",
    }
}

crate::impl_fingerprint!(Plantio);

/// Typed materialization DAG. Pure value — no runtime state.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Plantio {
    /// Stages keyed by ID. BTreeMap preserves deterministic ordering.
    pub stages: BTreeMap<StageId, Stage>,
}

impl Plantio {
    /// Empty Plantio.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Insert a stage. Errors on duplicate ID.
    ///
    /// # Errors
    /// [`PlantioError::DuplicateId`] if a stage with the same ID
    /// is already present.
    pub fn add_stage(&mut self, stage: Stage) -> Result<&mut Self, PlantioError> {
        if self.stages.contains_key(&stage.id) {
            return Err(PlantioError::DuplicateId(stage.id));
        }
        self.stages.insert(stage.id.clone(), stage);
        Ok(self)
    }

    /// Count of stages.
    #[must_use]
    pub fn len(&self) -> usize {
        self.stages.len()
    }

    /// True if empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.stages.is_empty()
    }

    /// BLAKE3 fingerprint over canonical JSON. Operators commit
    /// this to attest a particular Plantio was deployed.
    /// Same Plantio (down to stage insertion order via BTreeMap)
    /// always produces the same fingerprint.
    ///
    /// Generated via [`crate::Fingerprint`].
    #[must_use]
    pub fn fingerprint(&self) -> [u8; 32] {
        <Self as crate::Fingerprint>::fingerprint(self)
    }

    /// Observable snapshot — name + stage count. Pattern #2 SSC v0.96:
    /// `Plantio` joins TieredCache + CompositeShapeRenderer +
    /// ChainedVerifier as a 4th `ChildCountSnapshot` consumer.
    /// Dashboards can show "this Plantio has N stages."
    #[must_use]
    pub fn snapshot(&self) -> crate::mirante::ChildCountSnapshot {
        crate::mirante::ChildCountSnapshot {
            name: "plantio",
            child_count: self.len(),
        }
    }

    /// Validate topology: every depends_on resolves + the DAG is
    /// acyclic. Empty Plantio is trivially valid.
    ///
    /// # Errors
    /// [`PlantioError::UnknownDependency`] or [`PlantioError::Cycle`].
    pub fn validate(&self) -> Result<(), PlantioError> {
        // Check every dependency resolves.
        for stage in self.stages.values() {
            for dep in &stage.depends_on {
                if !self.stages.contains_key(dep) {
                    return Err(PlantioError::UnknownDependency {
                        stage: stage.id.clone(),
                        dependency: dep.clone(),
                    });
                }
            }
        }
        // Kahn's algorithm — surfaces cycles by leaving them in `remaining`.
        let _ = self.topo_sort()?;
        Ok(())
    }

    /// Topological sort. Returns stages in dependency order;
    /// each stage appears AFTER everything it depends_on.
    ///
    /// # Errors
    /// [`PlantioError::Cycle`] if the DAG is cyclic;
    /// [`PlantioError::UnknownDependency`] for dangling refs.
    pub fn topo_sort(&self) -> Result<Vec<StageId>, PlantioError> {
        // Validate dependencies first.
        for stage in self.stages.values() {
            for dep in &stage.depends_on {
                if !self.stages.contains_key(dep) {
                    return Err(PlantioError::UnknownDependency {
                        stage: stage.id.clone(),
                        dependency: dep.clone(),
                    });
                }
            }
        }
        // Compute in-degree per stage.
        let mut in_degree: BTreeMap<StageId, usize> =
            self.stages.keys().map(|k| (k.clone(), 0usize)).collect();
        for stage in self.stages.values() {
            for dep in &stage.depends_on {
                // depends_on means dep → stage. Stage's in-degree
                // increments by the count of its deps.
                *in_degree.entry(stage.id.clone()).or_insert(0) += 1;
                // Touch dep so we don't accidentally drop it.
                let _ = dep;
            }
        }
        // Seed queue with zero-in-degree nodes (BTree iteration =
        // deterministic order).
        let mut queue: VecDeque<StageId> = in_degree
            .iter()
            .filter(|(_, d)| **d == 0)
            .map(|(k, _)| k.clone())
            .collect();
        let mut sorted = Vec::with_capacity(self.stages.len());
        while let Some(next) = queue.pop_front() {
            sorted.push(next.clone());
            // Decrement in-degree of stages that depend on `next`.
            for stage in self.stages.values() {
                if stage.depends_on.contains(&next) {
                    if let Some(d) = in_degree.get_mut(&stage.id) {
                        *d = d.saturating_sub(1);
                        if *d == 0 {
                            queue.push_back(stage.id.clone());
                        }
                    }
                }
            }
        }
        if sorted.len() != self.stages.len() {
            let remaining: Vec<StageId> = in_degree
                .into_iter()
                .filter(|(_, d)| *d > 0)
                .map(|(k, _)| k)
                .collect();
            return Err(PlantioError::Cycle { remaining });
        }
        Ok(sorted)
    }

    /// "Compile" the Plantio into a flat list of materialization
    /// jobs ready for a downstream scheduler. Each job is a
    /// (stage_id, target_node) pair; placement fan-out happens
    /// here — `AllNodes` requires the caller to supply the live
    /// cluster size.
    ///
    /// Returns an empty Vec on an empty Plantio. Caller is
    /// responsible for the actual fan-out across `AllNodes` (the
    /// substrate doesn't have a live cluster directory here —
    /// that's `PlantioController`'s job next round).
    ///
    /// # Errors
    /// Propagates [`PlantioError`] from validation.
    pub fn compile_jobs(&self) -> Result<Vec<MaterializationJob>, PlantioError> {
        let sorted = self.topo_sort()?;
        let mut jobs = Vec::new();
        for id in &sorted {
            let stage = &self.stages[id];
            match &stage.placement {
                Placement::Pinned { node } => jobs.push(MaterializationJob {
                    stage_id: id.clone(),
                    target: JobTarget::Node(*node),
                }),
                Placement::AnyOne => jobs.push(MaterializationJob {
                    stage_id: id.clone(),
                    target: JobTarget::AnyOne,
                }),
                Placement::AnyK { k } => jobs.push(MaterializationJob {
                    stage_id: id.clone(),
                    target: JobTarget::AnyK { k: (*k).max(1) },
                }),
                Placement::Quorum { k } => jobs.push(MaterializationJob {
                    stage_id: id.clone(),
                    target: JobTarget::Quorum { k: (*k).max(1) },
                }),
                Placement::AllNodes => jobs.push(MaterializationJob {
                    stage_id: id.clone(),
                    target: JobTarget::AllNodes,
                }),
            }
        }
        Ok(jobs)
    }
}

crate::define_named!(Plantio, "plantio");
crate::impl_observable!(Plantio, crate::mirante::ChildCountSnapshot);

/// One unit of work emitted by `Plantio::compile_jobs`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MaterializationJob {
    /// Stage this job materializes.
    pub stage_id: StageId,
    /// Where the job targets.
    pub target: JobTarget,
}

/// Job-side projection of `Placement`. Distinguishes "I need a
/// specific node" from "the scheduler picks". Single-node concrete;
/// multi-node abstract until the scheduler resolves them.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum JobTarget {
    /// Concrete node — runs there.
    Node(NodeId),
    /// Scheduler picks any one node.
    AnyOne,
    /// Scheduler picks K nodes.
    AnyK {
        /// Count of nodes.
        k: usize,
    },
    /// Scheduler picks K nodes with agreement.
    Quorum {
        /// Quorum threshold.
        k: usize,
    },
    /// Scheduler fans out to every cluster node.
    AllNodes,
}

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

    fn n(b: u8) -> NodeId {
        NodeId::new([b; 32])
    }

    fn s(id: &str) -> StageId {
        StageId::new(id)
    }

    fn simple_stage(id: &str, deps: &[&str]) -> Stage {
        let mut st = Stage::pinned(id, WorkloadShape::OciImage, n(1));
        st.depends_on = deps.iter().map(|d| s(d)).collect();
        st
    }

    // ── StageId ────────────────────────────────────────────────

    #[test]
    fn stage_id_display_matches_str() {
        assert_eq!(format!("{}", s("build")), "build");
    }

    #[test]
    fn stage_id_round_trips_via_serde() {
        let id = s("x");
        let bytes = serde_json::to_vec(&id).unwrap();
        let back: StageId = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(back, id);
    }

    // ── Placement / Confirmacao ────────────────────────────────

    #[test]
    fn placement_min_nodes_matrix() {
        assert_eq!(Placement::Pinned { node: n(1) }.min_nodes(), Some(1));
        assert_eq!(Placement::AnyOne.min_nodes(), Some(1));
        assert_eq!(Placement::AnyK { k: 5 }.min_nodes(), Some(5));
        assert_eq!(Placement::Quorum { k: 3 }.min_nodes(), Some(3));
        assert_eq!(Placement::AllNodes.min_nodes(), None);
    }

    #[test]
    fn placement_requires_agreement_only_for_quorum_and_all() {
        assert!(Placement::Quorum { k: 1 }.requires_agreement());
        assert!(Placement::AllNodes.requires_agreement());
        assert!(!Placement::Pinned { node: n(1) }.requires_agreement());
        assert!(!Placement::AnyOne.requires_agreement());
        assert!(!Placement::AnyK { k: 5 }.requires_agreement());
    }

    /// A zero built in Rust still folds to one. This is the residual
    /// hole, pinned so it is visible: the wire can no longer reach it
    /// (see the parse tests below), and it closes for good when `k`
    /// becomes a `NonZeroUsize` end to end.
    #[test]
    fn placement_zero_k_clamps_to_one_via_min_nodes() {
        assert_eq!(Placement::AnyK { k: 0 }.min_nodes(), Some(1));
        assert_eq!(Placement::Quorum { k: 0 }.min_nodes(), Some(1));
    }

    // ── k = 0 is refused where the CR is read ──────────────────

    #[test]
    fn placement_any_k_refuses_zero_at_the_parse_boundary() {
        let err = serde_json::from_str::<Placement>(r#"{"kind":"any_k","k":0}"#)
            .expect_err("a placement with k = 0 must not parse");
        assert!(
            err.to_string().contains("at least 1"),
            "the refusal must say what was expected, got: {err}"
        );
    }

    #[test]
    fn placement_quorum_refuses_zero_at_the_parse_boundary() {
        let err = serde_json::from_str::<Placement>(r#"{"kind":"quorum","k":0}"#)
            .expect_err("a quorum placement with k = 0 must not parse");
        assert!(
            err.to_string().contains("at least 1"),
            "the refusal must say what was expected, got: {err}"
        );
    }

    #[test]
    fn confirmacao_quorum_refuses_zero_at_the_parse_boundary() {
        let err = serde_json::from_str::<ConfirmacaoPolicy>(r#"{"kind":"quorum","k":0}"#)
            .expect_err("a confirmation policy with k = 0 must not parse");
        assert!(
            err.to_string().contains("at least 1"),
            "the refusal must say what was expected, got: {err}"
        );
    }

    /// The wire number an operator actually writes is untouched — only
    /// zero moved from "silently means one" to "refused".
    #[test]
    fn every_non_zero_k_still_parses_to_the_same_number() {
        assert_eq!(
            serde_json::from_str::<Placement>(r#"{"kind":"any_k","k":1}"#).unwrap(),
            Placement::AnyK { k: 1 }
        );
        assert_eq!(
            serde_json::from_str::<Placement>(r#"{"kind":"quorum","k":3}"#).unwrap(),
            Placement::Quorum { k: 3 }
        );
        assert_eq!(
            serde_json::from_str::<ConfirmacaoPolicy>(r#"{"kind":"quorum","k":3}"#).unwrap(),
            ConfirmacaoPolicy::Quorum { k: 3 }
        );
        let p = Placement::Quorum { k: 3 };
        let back: Placement = serde_json::from_str(&serde_json::to_string(&p).unwrap()).unwrap();
        assert_eq!(back, p);
    }

    /// The realistic path: a whole Plantio read out of a CR. A zero
    /// anywhere in it takes the Plantio down with it rather than
    /// quietly becoming a one-node quorum.
    #[test]
    fn a_plantio_carrying_a_zero_k_does_not_parse() {
        let mut st = simple_stage("q", &[]);
        st.placement = Placement::Quorum { k: 3 };
        st.confirm = ConfirmacaoPolicy::Quorum { k: 3 };
        let mut p = Plantio::new();
        p.add_stage(st).unwrap();

        let good = serde_json::to_string(&p).unwrap();
        assert!(serde_json::from_str::<Plantio>(&good).is_ok());

        let zeroed = good.replace("\"k\":3", "\"k\":0");
        assert_ne!(
            zeroed, good,
            "fixture must contain the k it is about to zero"
        );
        let err = serde_json::from_str::<Plantio>(&zeroed)
            .expect_err("a plantio carrying k = 0 must not parse");
        assert!(
            err.to_string().contains("at least 1"),
            "the refusal must say what was expected, got: {err}"
        );
    }

    #[test]
    fn confirmacao_default_is_local() {
        assert_eq!(ConfirmacaoPolicy::default(), ConfirmacaoPolicy::Local);
    }

    #[test]
    fn confirmacao_serializes_with_tag() {
        let json = serde_json::to_string(&ConfirmacaoPolicy::Quorum { k: 3 }).unwrap();
        assert!(json.contains("\"kind\":\"quorum\""));
    }

    // ── Stage ──────────────────────────────────────────────────

    #[test]
    fn pinned_constructor_sets_defaults() {
        let st = Stage::pinned("x", WorkloadShape::OciImage, n(1));
        assert_eq!(st.id, s("x"));
        assert_eq!(st.confirm, ConfirmacaoPolicy::Local);
        assert!(st.depends_on.is_empty());
        assert!(st.verify.is_empty());
        assert!(matches!(st.placement, Placement::Pinned { .. }));
    }

    #[test]
    fn stage_round_trips_via_serde() {
        let st = simple_stage("x", &["a", "b"]);
        let bytes = serde_json::to_vec(&st).unwrap();
        let back: Stage = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(back, st);
    }

    // ── Plantio basic ──────────────────────────────────────────

    #[test]
    fn empty_plantio_is_valid() {
        let p = Plantio::new();
        assert!(p.is_empty());
        assert_eq!(p.len(), 0);
        p.validate().unwrap();
        assert!(p.compile_jobs().unwrap().is_empty());
    }

    #[test]
    fn add_stage_rejects_duplicate_id() {
        let mut p = Plantio::new();
        p.add_stage(simple_stage("x", &[])).unwrap();
        let err = p.add_stage(simple_stage("x", &[])).unwrap_err();
        assert_eq!(err.kind(), "duplicate_id");
    }

    #[test]
    fn validate_rejects_unknown_dependency() {
        let mut p = Plantio::new();
        p.add_stage(simple_stage("x", &["nope"])).unwrap();
        let err = p.validate().unwrap_err();
        assert_eq!(err.kind(), "unknown_dependency");
    }

    // ── Plantio topo_sort ──────────────────────────────────────

    #[test]
    fn topo_sort_orders_a_then_b_when_b_depends_on_a() {
        let mut p = Plantio::new();
        p.add_stage(simple_stage("a", &[])).unwrap();
        p.add_stage(simple_stage("b", &["a"])).unwrap();
        let order = p.topo_sort().unwrap();
        assert_eq!(order, vec![s("a"), s("b")]);
    }

    #[test]
    fn topo_sort_chain_of_three() {
        let mut p = Plantio::new();
        p.add_stage(simple_stage("c", &["b"])).unwrap();
        p.add_stage(simple_stage("b", &["a"])).unwrap();
        p.add_stage(simple_stage("a", &[])).unwrap();
        let order = p.topo_sort().unwrap();
        assert_eq!(order, vec![s("a"), s("b"), s("c")]);
    }

    #[test]
    fn topo_sort_diamond_works() {
        // a → {b, c} → d
        let mut p = Plantio::new();
        p.add_stage(simple_stage("a", &[])).unwrap();
        p.add_stage(simple_stage("b", &["a"])).unwrap();
        p.add_stage(simple_stage("c", &["a"])).unwrap();
        p.add_stage(simple_stage("d", &["b", "c"])).unwrap();
        let order = p.topo_sort().unwrap();
        // a first, d last; b/c in either order.
        assert_eq!(order[0], s("a"));
        assert_eq!(order[3], s("d"));
        let middle: BTreeSet<_> = order[1..3].iter().collect();
        assert!(middle.contains(&s("b")));
        assert!(middle.contains(&s("c")));
    }

    #[test]
    fn topo_sort_detects_cycle() {
        // a → b → a (cycle)
        let mut p = Plantio::new();
        p.add_stage(simple_stage("a", &["b"])).unwrap();
        p.add_stage(simple_stage("b", &["a"])).unwrap();
        let err = p.topo_sort().unwrap_err();
        assert_eq!(err.kind(), "cycle");
        if let PlantioError::Cycle { remaining } = err {
            // Both stages remain unprocessed.
            assert_eq!(remaining.len(), 2);
        }
    }

    // ── Plantio compile_jobs ───────────────────────────────────

    #[test]
    fn compile_jobs_emits_one_job_per_stage_in_topo_order() {
        let mut p = Plantio::new();
        p.add_stage(simple_stage("a", &[])).unwrap();
        p.add_stage(simple_stage("b", &["a"])).unwrap();
        let jobs = p.compile_jobs().unwrap();
        assert_eq!(jobs.len(), 2);
        assert_eq!(jobs[0].stage_id, s("a"));
        assert_eq!(jobs[1].stage_id, s("b"));
    }

    #[test]
    fn compile_jobs_projects_placement_to_job_target() {
        let mut p = Plantio::new();
        let mut st_pinned = Stage::pinned("p", WorkloadShape::OciImage, n(1));
        st_pinned.placement = Placement::Pinned { node: n(7) };
        p.add_stage(st_pinned).unwrap();
        let mut st_any = Stage::pinned("any", WorkloadShape::OciImage, n(1));
        st_any.placement = Placement::AnyOne;
        p.add_stage(st_any).unwrap();
        let mut st_quorum = Stage::pinned("q", WorkloadShape::OciImage, n(1));
        st_quorum.placement = Placement::Quorum { k: 3 };
        p.add_stage(st_quorum).unwrap();
        let mut st_all = Stage::pinned("all", WorkloadShape::OciImage, n(1));
        st_all.placement = Placement::AllNodes;
        p.add_stage(st_all).unwrap();
        let jobs = p.compile_jobs().unwrap();
        let targets: BTreeMap<StageId, JobTarget> =
            jobs.into_iter().map(|j| (j.stage_id, j.target)).collect();
        assert_eq!(targets[&s("p")], JobTarget::Node(n(7)));
        assert_eq!(targets[&s("any")], JobTarget::AnyOne);
        assert_eq!(targets[&s("q")], JobTarget::Quorum { k: 3 });
        assert_eq!(targets[&s("all")], JobTarget::AllNodes);
    }

    #[test]
    fn compile_jobs_propagates_cycle_error() {
        let mut p = Plantio::new();
        p.add_stage(simple_stage("a", &["b"])).unwrap();
        p.add_stage(simple_stage("b", &["a"])).unwrap();
        let err = p.compile_jobs().unwrap_err();
        assert_eq!(err.kind(), "cycle");
    }

    // ── Plantio serde ──────────────────────────────────────────

    #[test]
    fn plantio_round_trips_via_serde() {
        let mut p = Plantio::new();
        p.add_stage(simple_stage("a", &[])).unwrap();
        p.add_stage(simple_stage("b", &["a"])).unwrap();
        let bytes = serde_json::to_vec(&p).unwrap();
        let back: Plantio = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(back, p);
    }

    // ── PlantioError ───────────────────────────────────────────

    #[test]
    fn error_kinds_are_stable() {
        let dup = PlantioError::DuplicateId(s("x"));
        assert_eq!(dup.kind(), "duplicate_id");
        let unk = PlantioError::UnknownDependency {
            stage: s("a"),
            dependency: s("b"),
        };
        assert_eq!(unk.kind(), "unknown_dependency");
        let cyc = PlantioError::Cycle { remaining: vec![] };
        assert_eq!(cyc.kind(), "cycle");
    }
}