phoxal 0.32.5

Phoxal - production-oriented autonomous robot framework: the runtime engine and model (the api contract tree lives in phoxal-api, the typed bus in phoxal-bus).
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
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
//! Graph validation for Phoxal participant graphs (D59/D63/D1), plus the
//! deployment coherence pass (coherence-gate design doc, `organization`
//! `tmp/coherence-gate/readme.md`).
//!
//! This is the pure core: given the `emit-apis` report of every participant in a
//! robot graph, it is fully unit-testable without Docker or a registry,
//! independent of how the reports are obtained (resolved images, local
//! binaries).
//!
//! **There is no interop gate on contract identity (D1).** Contract identity is
//! the generation-qualified `family` name alone (e.g. `"y2026_1::drive::Target"`);
//! there is no `schema_id` hash to agree on, because two participants naming the
//! same generation-qualified contract are compatible by construction (same name
//! ⇒ same frozen shape, enforced by the type system and made physically real by
//! the generation-qualified wire key). Two participants naming *different*
//! contracts are simply different topics, never a collision. `check_plan`/
//! `check_graph` below therefore carry only [`Problem::InvalidConfig`], the one
//! thing that *is* still a real runtime hazard on that axis: a user runtime's
//! manifest config not matching its emitted JSON Schema.
//!
//! Nothing about pub/sub topology or query responder counts is checked by
//! `check_plan`/`check_graph`. A robot legitimately consumes commands whose
//! sender is external to the checked participant set (an operator UI, a
//! joystick, a sim controller), and legitimately offers query endpoints that
//! nothing on-robot currently calls (the callers are external tools). The bus
//! already makes these non-issues at runtime: a publisher checks for
//! subscribers before sending, and a query server starts regardless of current
//! clients. So a consumed contract with no producer and a produced contract
//! with no consumer are both legal states on their own - **that open-world
//! stance stays.**
//!
//! What the open-world stance does not cover is a contract that is
//! demonstrably produced/served in-set at one generation while a participant
//! consumes/asks a *different, disjoint* generation of that same logical
//! contract - clear evidence of a botched migration, not an external
//! counterpart. [`check_coherence`] is that one contract-axis check: a pure,
//! mismatch-only pass over each participant's `#[derive(phoxal::Api)]`
//! contract surface (the `generation`/`contract`/`role`/`external` entries of
//! [`crate::participant::metadata::ParticipantMetaContract`]). It blocks only
//! on generation disjointness where a counterpart is provably in-set, never on
//! absence alone - see its own docs and the coherence-gate design doc §3 for
//! the exact rule and worked examples.
//!
//! Simulation plans differ from deploy/run plans only in *which participants the
//! caller passes*: in sim, a component driver is simply not launched and the
//! Webots simulator participant is passed in its place (D16). Because the
//! simulator is built from the same framework, it speaks the same contracts by
//! construction. There is no separate substitution concept, no completeness
//! gate, and no missing-producer diagnostic here - whether a contract has a
//! producer is a caller/deployment choice, not something this checker judges.

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

use crate::participant::metadata::ParticipantMetaContract;

/// One participant's `emit-apis` report, reduced to what graph validation needs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParticipantApis {
    /// The concrete participant/instance id used for graph membership and
    /// diagnostics. For most participants this equals `artifact_id`, but a
    /// component driver is launched once per component instance, so several
    /// instances of the same driver share one `artifact_id` yet must remain
    /// distinct nodes in the graph (e.g. `left_drive`, `right_drive`).
    pub participant_id: String,
    /// The artifact id (`emit-apis` `artifact.id`), e.g. `"drive"`. Kept for
    /// artifact-identity validation; not used to key the topology graph.
    pub artifact_id: String,
    /// The artifact kind (`emit-apis` `artifact.kind`), e.g. `"service"`,
    /// `"driver"`, or `"simulator"`. Not consulted by the checker itself;
    /// preserved for callers (e.g. board display of which driver a sim plan's
    /// simulator participant stands in for).
    pub participant_kind: ParticipantKind,
    /// The `emit-apis` `participant_class` the artifact reports. Not consulted
    /// by the checker itself - name identity applies to every participant
    /// uniformly; preserved for diagnostics.
    pub participant_class: ParticipantClass,
    /// The API version the artifact reports (`emit-apis` `api_version`).
    pub api_version: String,
    /// The artifact's emitted config schema, preserved for later validation.
    pub config_schema: Option<serde_json::Value>,
    /// The manifest scope this participant is launched under. Normal runtimes
    /// see the whole graph; component drivers are launched once per component
    /// instance.
    pub scope: ParticipantScope,
    /// The contracts the artifact participates in.
    pub contracts: Vec<Contract>,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum ParticipantKind {
    Service,
    Driver,
    Tool,
    Simulator,
    Other(String),
}

impl ParticipantKind {
    /// Parse the `emit-apis` `artifact.kind` string. Unknown kinds are preserved
    /// for diagnostics.
    #[must_use]
    pub fn parse(s: &str) -> Self {
        match s {
            "service" => Self::Service,
            "driver" => Self::Driver,
            "tool" => Self::Tool,
            "simulator" => Self::Simulator,
            other => Self::Other(other.to_string()),
        }
    }

    #[must_use]
    pub fn as_str(&self) -> &str {
        match self {
            Self::Service => "service",
            Self::Driver => "driver",
            Self::Tool => "tool",
            Self::Simulator => "simulator",
            Self::Other(kind) => kind,
        }
    }

    #[must_use]
    pub const fn is_simulator(&self) -> bool {
        matches!(self, Self::Simulator)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ParticipantClass {
    #[default]
    Checked,
    Privileged,
}

impl ParticipantClass {
    /// Parse the `emit-apis` `participant_class` string.
    #[must_use]
    pub fn parse(s: &str) -> Option<Self> {
        Some(match s {
            "checked" => Self::Checked,
            "privileged" => Self::Privileged,
            _ => return None,
        })
    }

    #[must_use]
    pub const fn is_checked(self) -> bool {
        matches!(self, Self::Checked)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum ParticipantScope {
    #[default]
    Graph,
    ComponentInstance(String),
}

/// One contract use from an `emit-apis` report: its generation-qualified name
/// (e.g. `"y2026_1::drive::Target"`, D1). There is no `schema_id` - the name
/// itself is the whole identity.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Contract {
    pub family: String,
}

/// Borrowed input to the pure graph checker.
#[derive(Debug, Clone, Copy)]
pub struct CheckInput<'a> {
    pub participants: &'a [ParticipantApis],
}

/// A problem found while validating a robot graph.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Problem {
    /// A user runtime's manifest config does not match its emitted JSON Schema.
    InvalidConfig {
        runtime_id: String,
        errors: Vec<String>,
    },
}

/// The outcome of validating a graph: the problems found (empty == healthy).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Report {
    pub problems: Vec<Problem>,
}

impl Report {
    #[must_use]
    pub fn is_ok(&self) -> bool {
        self.problems.is_empty()
    }
}

/// Validate a robot graph.
///
/// `participants` is every normal participant's `emit-apis` report. There is no
/// contract-agreement axis left to check (D1: name identity alone guarantees
/// compatibility) - this is a thin, stable entry point for callers, kept for
/// config validation to grow into.
#[must_use]
pub fn check_graph(participants: &[ParticipantApis]) -> Report {
    check_plan(CheckInput { participants })
}

#[must_use]
pub fn check_plan(input: CheckInput<'_>) -> Report {
    let _ = input.participants;
    Report::default()
}

// ---------------------------------------------------------------------------
// Coherence pass (coherence-gate design doc §3)
// ---------------------------------------------------------------------------

/// One participant's contract surface for [`check_coherence`]: its identity
/// plus every `{role, generation, contract, external}` entry recorded by its
/// `#[derive(phoxal::Api)]` metadata section (design doc §2).
///
/// Deliberately separate from [`ParticipantApis`] above: that type identifies
/// a contract by a single generation-qualified `family` string with no role
/// axis (it feeds the topology/config checker, `check_plan`), while the
/// coherence pass needs `generation` and `contract` as separate fields plus
/// the `role`/`external` facts to group by logical contract and apply the
/// role-asymmetric rule (design doc §2 "the check never parses a name").
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParticipantContractSurface {
    /// The participant identity named in diagnostics.
    pub participant_id: String,
    /// This participant's contract surface entries, in any order.
    pub contracts: Vec<ParticipantMetaContract>,
}

/// One coherence mismatch found by [`check_coherence`] (design doc §3).
///
/// Both variants block only on **positive disjointness evidence** - a
/// counterpart that is demonstrably present in-set at generations that share
/// nothing with this participant's own. Absence alone (an empty `Pub(L)` or
/// `Serve(L)`) is never a mismatch; that is exactly the open-world stance the
/// module docs describe, which this pass narrows only where evidence exists.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CoherenceMismatch {
    /// A participant's non-`external` `subscribe` generations for a logical
    /// contract share no generation with any in-set publisher of that
    /// contract, even though the contract *is* published in-set (design doc
    /// §3, "pub/sub - per-participant overlap"). Checked per subscribing
    /// participant, never pooled: one up-to-date subscriber elsewhere does
    /// not excuse another participant's stranded hard cutover.
    PubSubDisjoint {
        participant_id: String,
        /// The logical contract (the `contract` field alone; generation-independent).
        contract: String,
        /// This participant's non-`external` `subscribe` generations for `contract`.
        subscribed: BTreeSet<String>,
        /// Every generation published in-set for `contract`.
        published: BTreeSet<String>,
    },
    /// A participant's non-`external` `ask` generation for a logical contract
    /// has no same-generation `serve` in-set: a permanently dead query
    /// (design doc §3, "serve/ask - every ask matched"; `QueryError::Timeout`,
    /// D31). The one closed-world rule in the design - checked per ask
    /// generation, since a server superset elsewhere in the same contract
    /// does not answer a different, unserved generation.
    UnservedAsk {
        participant_id: String,
        /// The logical contract (the `contract` field alone; generation-independent).
        contract: String,
        /// The ask generation with no matching in-set server.
        generation: String,
        /// Every generation served in-set for `contract` (may be empty).
        served: BTreeSet<String>,
    },
}

/// The outcome of the coherence pass: the mismatches found (empty == coherent).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CoherenceReport {
    pub mismatches: Vec<CoherenceMismatch>,
}

impl CoherenceReport {
    #[must_use]
    pub fn is_ok(&self) -> bool {
        self.mismatches.is_empty()
    }
}

/// Run the deployment coherence pass over a whole participant set (design doc
/// §3).
///
/// Pure and total: no I/O, no building, no binary parsing - callers hand it
/// already-parsed contract surfaces. Groups every entry by its **logical
/// contract** (the `contract` field alone, generation-independent) and
/// applies the role-asymmetric rule:
///
/// - **Pub/sub** blocks a subscribing participant only when the contract *is*
///   published in-set (`Pub(L)` non-empty) and this participant's own
///   non-`external` subscribe generations share nothing with it. Checked
///   per-participant, not pooled, so one dual-subscribing participant never
///   masks another's stranded hard cutover.
/// - **Serve/ask** blocks every non-`external` ask generation that has no
///   same-generation server in-set, regardless of whether the contract is
///   served at *other* generations - the one closed-world rule in the design,
///   because an unmatched ask never resolves to a useful intermediate state
///   (it times out on every call, D31), unlike an unmatched subscribe.
///
/// An `external` entry (`#[phoxal(external)]`, design doc §1) skips its own
/// edge's requirement entirely: it is excluded from `SubP(L)`/`AskP(L)` before
/// either check runs, so a participant whose only edge for a contract is
/// marked `external` is never flagged for it.
#[must_use]
pub fn check_coherence(participants: &[ParticipantContractSurface]) -> CoherenceReport {
    // Pub(L)/Serve(L), pooled across the whole set (never filtered by
    // `external`: the marker only ever applies to consumer roles, design doc
    // §1, so every publish/serve entry counts toward these pools).
    let mut published: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
    let mut served: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
    for p in participants {
        for c in &p.contracts {
            match c.role.as_str() {
                "publish" => {
                    published
                        .entry(c.contract.as_str())
                        .or_default()
                        .insert(c.generation.as_str());
                }
                "serve" => {
                    served
                        .entry(c.contract.as_str())
                        .or_default()
                        .insert(c.generation.as_str());
                }
                _ => {}
            }
        }
    }

    let mut mismatches = Vec::new();

    for p in participants {
        // Pub/sub: per-participant SubP(L), non-external edges only.
        let mut sub_by_contract: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
        for c in &p.contracts {
            if c.role == "subscribe" && !c.external {
                sub_by_contract
                    .entry(c.contract.as_str())
                    .or_default()
                    .insert(c.generation.as_str());
            }
        }
        for (contract, subscribed) in sub_by_contract {
            let Some(published) = published.get(contract) else {
                continue; // Pub(L) empty -> open world, OK.
            };
            if subscribed.is_disjoint(published) {
                mismatches.push(CoherenceMismatch::PubSubDisjoint {
                    participant_id: p.participant_id.clone(),
                    contract: contract.to_string(),
                    subscribed: subscribed.iter().map(|s| (*s).to_string()).collect(),
                    published: published.iter().map(|s| (*s).to_string()).collect(),
                });
            }
        }

        // Serve/ask: every non-external ask generation needs a same-generation server.
        for c in &p.contracts {
            if c.role != "ask" || c.external {
                continue;
            }
            let contract_served = served.get(c.contract.as_str());
            let has_server =
                contract_served.is_some_and(|gens| gens.contains(c.generation.as_str()));
            if !has_server {
                mismatches.push(CoherenceMismatch::UnservedAsk {
                    participant_id: p.participant_id.clone(),
                    contract: c.contract.clone(),
                    generation: c.generation.clone(),
                    served: contract_served
                        .map(|gens| gens.iter().map(|s| (*s).to_string()).collect())
                        .unwrap_or_default(),
                });
            }
        }
    }

    CoherenceReport { mismatches }
}

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

    fn contract(family: &str) -> Contract {
        Contract {
            family: family.to_string(),
        }
    }

    fn participant(id: &str, api: &str, contracts: Vec<Contract>) -> ParticipantApis {
        ParticipantApis {
            participant_id: id.to_string(),
            artifact_id: id.to_string(),
            participant_kind: ParticipantKind::Service,
            participant_class: ParticipantClass::Checked,
            api_version: api.to_string(),
            config_schema: None,
            scope: ParticipantScope::Graph,
            contracts,
        }
    }

    fn privileged_participant(id: &str, api: &str, contracts: Vec<Contract>) -> ParticipantApis {
        ParticipantApis {
            participant_id: id.to_string(),
            artifact_id: id.to_string(),
            participant_kind: ParticipantKind::Tool,
            participant_class: ParticipantClass::Privileged,
            api_version: api.to_string(),
            config_schema: None,
            scope: ParticipantScope::Graph,
            contracts,
        }
    }

    #[test]
    fn participant_kind_parse_preserves_unknown_kinds() {
        assert_eq!(ParticipantKind::parse("service"), ParticipantKind::Service);
        assert_eq!(ParticipantKind::parse("driver"), ParticipantKind::Driver);
        assert_eq!(
            ParticipantKind::parse("simulator"),
            ParticipantKind::Simulator
        );
        assert_eq!(
            ParticipantKind::parse("custom-kind"),
            ParticipantKind::Other("custom-kind".to_string())
        );
    }

    #[test]
    fn participant_class_parse_round_trips_and_rejects_unknown() {
        assert_eq!(
            ParticipantClass::parse("checked"),
            Some(ParticipantClass::Checked)
        );
        assert_eq!(
            ParticipantClass::parse("privileged"),
            Some(ParticipantClass::Privileged)
        );
        assert_eq!(ParticipantClass::parse("service"), None);
    }

    #[test]
    fn healthy_pubsub_graph_has_no_problems() {
        // producer publishes drive/target; consumer subscribes it.
        let graph = vec![
            participant(
                "mission",
                "y2026_1",
                vec![contract("y2026_1::drive::Target")],
            ),
            participant("drive", "y2026_1", vec![contract("y2026_1::drive::Target")]),
        ];
        assert!(check_graph(&graph).is_ok());
    }

    #[test]
    fn healthy_query_graph_has_no_problems() {
        // a server serves asset/get; a client queries it.
        let graph = vec![
            participant(
                "asset",
                "y2026_1",
                vec![contract("y2026_1::asset::GetRequest")],
            ),
            participant(
                "client",
                "y2026_1",
                vec![contract("y2026_1::asset::GetRequest")],
            ),
        ];
        assert!(check_graph(&graph).is_ok());
    }

    #[test]
    fn mixed_generations_on_the_same_contract_family_are_simply_different_contracts() {
        // D1: with no schema_id, a `y2026_1::drive::Target` user and a
        // `y2026_2::drive::Target` user are unrelated contracts, not a
        // mismatch - there is nothing to report.
        let graph = vec![
            participant(
                "mission",
                "y2026_1",
                vec![contract("y2026_1::drive::Target")],
            ),
            participant("drive", "y2026_2", vec![contract("y2026_2::drive::Target")]),
        ];
        assert!(check_graph(&graph).is_ok());
    }

    #[test]
    fn tool_kind_participant_contracts_do_not_gate_the_graph() {
        let graph = vec![
            participant(
                "mission",
                "y2026_1",
                vec![contract("y2026_1::drive::Target")],
            ),
            participant("drive", "y2026_1", vec![contract("y2026_1::drive::Target")]),
            privileged_participant(
                "inspector",
                "y2026_1",
                vec![contract("y2026_1::drive::Target")],
            ),
        ];

        assert!(check_graph(&graph).is_ok());
    }

    #[test]
    fn a_publisher_anywhere_satisfies_all_subscribers() {
        let graph = vec![
            participant(
                "odometry",
                "y2026_1",
                vec![contract("y2026_1::odometry::State")],
            ),
            participant(
                "localize",
                "y2026_1",
                vec![contract("y2026_1::odometry::State")],
            ),
            participant("map", "y2026_1", vec![contract("y2026_1::odometry::State")]),
        ];
        assert!(check_graph(&graph).is_ok());
    }

    #[test]
    fn dangling_consumers_and_dangling_servers_are_legal() {
        // A real robot: a consumed command with no producer in the checked set
        // (an external operator/joystick/sim-controller sends it), and a query
        // server with no current client (the caller is an external tool). Neither
        // is a problem or warning; the bus tolerates both at runtime.
        let participants = vec![
            // Consumes a command nobody in the graph produces.
            participant(
                "mission",
                "y2026_1",
                vec![contract("y2026_1::mission::Command")],
            ),
            // Offers a query endpoint with no client in the graph.
            participant(
                "asset",
                "y2026_1",
                vec![contract("y2026_1::asset::GetRequest")],
            ),
        ];

        let report = check_graph(&participants);

        assert_eq!(report, Report::default());
    }

    #[test]
    fn empty_graph_is_ok() {
        assert!(check_graph(&[]).is_ok());
    }

    // -----------------------------------------------------------------
    // check_coherence (coherence-gate design doc §3 worked examples)
    // -----------------------------------------------------------------

    fn meta_contract(
        role: &str,
        generation: &str,
        contract: &str,
        external: bool,
    ) -> ParticipantMetaContract {
        ParticipantMetaContract {
            role: role.to_string(),
            generation: generation.to_string(),
            contract: contract.to_string(),
            external,
        }
    }

    fn surface(id: &str, contracts: Vec<ParticipantMetaContract>) -> ParticipantContractSurface {
        ParticipantContractSurface {
            participant_id: id.to_string(),
            contracts,
        }
    }

    fn gens(vals: &[&str]) -> BTreeSet<String> {
        vals.iter().map(|s| (*s).to_string()).collect()
    }

    #[test]
    fn coherence_empty_participant_set_is_ok() {
        assert!(check_coherence(&[]).is_ok());
    }

    /// §3 worked example 1: "pub `y2026_1`, sub `y2026_7`, nothing else ->
    /// disjoint -> block".
    #[test]
    fn coherence_pub_sub_disjoint_generations_block() {
        let participants = vec![
            surface(
                "drive",
                vec![meta_contract("publish", "y2026_1", "drive::Target", false)],
            ),
            surface(
                "mission",
                vec![meta_contract(
                    "subscribe",
                    "y2026_7",
                    "drive::Target",
                    false,
                )],
            ),
        ];

        let report = check_coherence(&participants);

        assert_eq!(
            report.mismatches,
            vec![CoherenceMismatch::PubSubDisjoint {
                participant_id: "mission".to_string(),
                contract: "drive::Target".to_string(),
                subscribed: gens(&["y2026_7"]),
                published: gens(&["y2026_1"]),
            }]
        );
    }

    /// §3 worked example 2: "pub `y2026_1`; one service subscribes both
    /// `y2026_1` and `y2026_7` -> valid" (the dual-subscribe spans a
    /// migration).
    #[test]
    fn coherence_dual_subscribe_spans_migration_is_valid() {
        let participants = vec![
            surface(
                "drive",
                vec![meta_contract("publish", "y2026_1", "drive::Target", false)],
            ),
            surface(
                "mission",
                vec![
                    meta_contract("subscribe", "y2026_1", "drive::Target", false),
                    meta_contract("subscribe", "y2026_7", "drive::Target", false),
                ],
            ),
        ];

        assert!(check_coherence(&participants).is_ok());
    }

    /// §3 worked example 3: the same service then drops its `y2026_1` sub ->
    /// `SubP={7}` vs `Pub={1}` -> disjoint -> block.
    #[test]
    fn coherence_dropping_old_sub_after_dual_subscribe_blocks() {
        let participants = vec![
            surface(
                "drive",
                vec![meta_contract("publish", "y2026_1", "drive::Target", false)],
            ),
            surface(
                "mission",
                vec![meta_contract(
                    "subscribe",
                    "y2026_7",
                    "drive::Target",
                    false,
                )],
            ),
        ];

        let report = check_coherence(&participants);

        assert_eq!(
            report.mismatches,
            vec![CoherenceMismatch::PubSubDisjoint {
                participant_id: "mission".to_string(),
                contract: "drive::Target".to_string(),
                subscribed: gens(&["y2026_7"]),
                published: gens(&["y2026_1"]),
            }]
        );
    }

    /// §3 worked example 4 (the pooled-rule trap): "pub `y2026_1`; service A
    /// subs `{1}`; service B subs `{7}` only -> A passes, B blocks". A pooled
    /// `Pub(L) ∩ Sub(L)` over the union would wrongly pass this via A's
    /// overlap; the per-participant rule must flag B specifically.
    #[test]
    fn coherence_pooled_overlap_does_not_excuse_a_stranded_subscriber() {
        let participants = vec![
            surface(
                "drive",
                vec![meta_contract("publish", "y2026_1", "drive::Target", false)],
            ),
            surface(
                "service_a",
                vec![meta_contract(
                    "subscribe",
                    "y2026_1",
                    "drive::Target",
                    false,
                )],
            ),
            surface(
                "service_b",
                vec![meta_contract(
                    "subscribe",
                    "y2026_7",
                    "drive::Target",
                    false,
                )],
            ),
        ];

        let report = check_coherence(&participants);

        assert_eq!(
            report.mismatches,
            vec![CoherenceMismatch::PubSubDisjoint {
                participant_id: "service_b".to_string(),
                contract: "drive::Target".to_string(),
                subscribed: gens(&["y2026_7"]),
                published: gens(&["y2026_1"]),
            }]
        );
    }

    /// §3 ask worked example 1: "servers `{L, L+1}`, ask `{L+1}` -> valid"
    /// (the extra server@L is a harmless unused server).
    #[test]
    fn coherence_ask_matched_by_a_superset_server_is_valid() {
        let participants = vec![
            surface(
                "asset",
                vec![
                    meta_contract("serve", "y2026_1", "asset::Get", false),
                    meta_contract("serve", "y2026_7", "asset::Get", false),
                ],
            ),
            surface(
                "client",
                vec![meta_contract("ask", "y2026_7", "asset::Get", false)],
            ),
        ];

        assert!(check_coherence(&participants).is_ok());
    }

    /// §3 ask worked example 2: "server `{L}`, ask `{L+1}` -> block".
    #[test]
    fn coherence_ask_with_no_matching_server_generation_blocks() {
        let participants = vec![
            surface(
                "asset",
                vec![meta_contract("serve", "y2026_1", "asset::Get", false)],
            ),
            surface(
                "client",
                vec![meta_contract("ask", "y2026_7", "asset::Get", false)],
            ),
        ];

        let report = check_coherence(&participants);

        assert_eq!(
            report.mismatches,
            vec![CoherenceMismatch::UnservedAsk {
                participant_id: "client".to_string(),
                contract: "asset::Get".to_string(),
                generation: "y2026_7".to_string(),
                served: gens(&["y2026_1"]),
            }]
        );
    }

    /// §3 ask worked example 3: "server `{L}`, ask `{L, L+1}` -> ask@L is
    /// answered, but ask@L+1 has no server -> block" - only the L+1 ask.
    #[test]
    fn coherence_partial_ask_coverage_blocks_only_the_unserved_generation() {
        let participants = vec![
            surface(
                "asset",
                vec![meta_contract("serve", "y2026_1", "asset::Get", false)],
            ),
            surface(
                "client",
                vec![
                    meta_contract("ask", "y2026_1", "asset::Get", false),
                    meta_contract("ask", "y2026_7", "asset::Get", false),
                ],
            ),
        ];

        let report = check_coherence(&participants);

        assert_eq!(
            report.mismatches,
            vec![CoherenceMismatch::UnservedAsk {
                participant_id: "client".to_string(),
                contract: "asset::Get".to_string(),
                generation: "y2026_7".to_string(),
                served: gens(&["y2026_1"]),
            }]
        );
    }

    /// §1: `#[phoxal(external)]` on a subscribe edge skips that edge's
    /// pub/sub requirement entirely, even though the generations are
    /// otherwise disjoint from the in-set publisher.
    #[test]
    fn coherence_external_marker_excuses_a_subscribe_mismatch() {
        let participants = vec![
            surface(
                "drive",
                vec![meta_contract("publish", "y2026_1", "drive::Target", false)],
            ),
            surface(
                "teleop",
                vec![meta_contract("subscribe", "y2026_7", "drive::Target", true)],
            ),
        ];

        assert!(check_coherence(&participants).is_ok());
    }

    /// §1: `#[phoxal(external)]` on an ask edge skips that edge's
    /// serve/ask requirement entirely, even though no in-set server answers
    /// that generation.
    #[test]
    fn coherence_external_marker_excuses_an_ask_mismatch() {
        let participants = vec![
            surface(
                "asset",
                vec![meta_contract("serve", "y2026_1", "asset::Get", false)],
            ),
            surface(
                "client",
                vec![meta_contract("ask", "y2026_7", "asset::Get", true)],
            ),
        ];

        assert!(check_coherence(&participants).is_ok());
    }

    /// §3: "if `Pub(L)` is empty -> OK (open world: the producer may be
    /// external to the set... or intentionally absent)".
    #[test]
    fn coherence_open_world_ok_when_nothing_publishes_in_set() {
        let participants = vec![surface(
            "mission",
            vec![meta_contract(
                "subscribe",
                "y2026_1",
                "mission::Command",
                false,
            )],
        )];

        assert!(check_coherence(&participants).is_ok());
    }

    /// §3: "a server with no matching ask is harmless (unused server,
    /// callers may be external tools)".
    #[test]
    fn coherence_server_with_no_asker_is_harmless() {
        let participants = vec![surface(
            "asset",
            vec![meta_contract("serve", "y2026_1", "asset::Get", false)],
        )];

        assert!(check_coherence(&participants).is_ok());
    }
}