wyrd-spec 0.1.1

Wyrd foundation types: Card envelope, SpecKinds, and pure data contracts.
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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
//! Card references authored inside specs.

use std::fmt;
use std::path::PathBuf;
use std::str::FromStr;

use serde::{Deserialize, Serialize};

use crate::envelope::{CardKind, Spec};
use crate::ids::{CardName, CardUid, SpaceName};
use crate::refs::ReferenceSlotVisitor;
use wyrd_semver::VersionBlock;

/// Reference to a registered Card by kind, name, version, optional space, and optional UID.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
pub struct CardRef {
    /// Referenced Card kind.
    pub kind: CardKind,
    /// Referenced Card name.
    pub name: CardName,
    /// Exact referenced Card version.
    pub version: VersionBlock,
    /// Space pinning identity together with `name` and `version`.
    ///
    /// Authors may omit it; the loader inherits the enclosing card's resolved
    /// metadata space before the reference crosses a wire boundary.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub space: Option<SpaceName>,
    /// Optional server-resolved durable UID.
    ///
    /// Authors identify a dependency with `(kind, space, name, version)` and
    /// may omit this field. The server resolves that reference to a [`CardUid`]
    /// before registration; the UID is then used for durable authorization and
    /// lineage without changing the authored reference identity.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub uid: Option<CardUid>,
}

/// Exact named identity for a [`CardRef`], excluding its server-resolved UID.
///
/// This is an in-memory key for matching authored, graph, and registry
/// references. It is not a wire shape. The version is kept as its canonical
/// string because identity equality is exact rather than semver-ordered.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CardRefIdentity {
    /// Card kind.
    pub kind: CardKind,
    /// Optional authored space; resolved references must carry one.
    pub space: Option<SpaceName>,
    /// Card name.
    pub name: CardName,
    /// Exact version string.
    pub version: String,
}

/// A reference position that requires durable identity.
///
/// Loaders rewrite `Path` values to `Sibling` values before submitting a request;
/// the server rejects unresolved paths at the wire boundary. Authored `Ref`
/// values remain external references even when they identify a submitted card.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case", untagged)]
pub enum Ref {
    /// A direct reference to a registered Card.
    Ref(CardRef),
    /// A loader-projected reference to another submission in the same request.
    Sibling {
        /// Exact identity of the sibling submission.
        sibling: CardRef,
    },
    /// A local authored path awaiting loader resolution.
    #[cfg_attr(feature = "server", schema(value_type = String))]
    Path(PathBuf),
}

impl Ref {
    /// Return the resolved [`CardRef`] when this ref carries durable identity.
    ///
    /// Returns `None` for [`Ref::Path`] values that a loader has not yet
    /// rewritten. Both [`Ref::Ref`] and [`Ref::Sibling`] carry durable identity.
    #[must_use]
    pub fn as_card_ref(&self) -> Option<&CardRef> {
        match self {
            Self::Ref(card_ref) | Self::Sibling { sibling: card_ref } => Some(card_ref),
            Self::Path(_) => None,
        }
    }

    /// Mutable variant of [`Ref::as_card_ref`].
    #[must_use]
    pub fn as_card_ref_mut(&mut self) -> Option<&mut CardRef> {
        match self {
            Self::Ref(card_ref) | Self::Sibling { sibling: card_ref } => Some(card_ref),
            Self::Path(_) => None,
        }
    }

    /// Return the exact identity when this is a loader-projected sibling.
    #[must_use]
    pub fn as_sibling(&self) -> Option<&CardRef> {
        match self {
            Self::Sibling { sibling } => Some(sibling),
            Self::Ref(_) | Self::Path(_) => None,
        }
    }
}

impl From<CardRef> for Ref {
    fn from(card_ref: CardRef) -> Self {
        Self::Ref(card_ref)
    }
}

/// A reference position that may carry an embedded child spec.
///
/// Loaders rewrite `Path` values to `Sibling` values before submitting a request;
/// the server rejects unresolved paths at the wire boundary. `Inline`
/// bodies are authored, not synthesized by the loader.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case", untagged)]
pub enum InlineableRef<T> {
    /// A direct reference to a registered Card.
    Ref(CardRef),
    /// A loader-projected reference to another submission in the same request.
    Sibling {
        /// Exact identity of the sibling submission.
        sibling: CardRef,
    },
    /// An embedded child spec.
    Inline(Box<T>),
    /// A local authored path awaiting loader resolution.
    #[cfg_attr(feature = "server", schema(value_type = String))]
    Path(PathBuf),
}

impl<T> InlineableRef<T> {
    /// Return the resolved [`CardRef`] when this ref carries durable identity.
    ///
    /// Returns `None` for [`InlineableRef::Path`] (loader has not resolved
    /// it yet) and [`InlineableRef::Inline`] (the body is embedded, not
    /// referenced). Both card-reference variants carry durable identity.
    #[must_use]
    pub fn as_card_ref(&self) -> Option<&CardRef> {
        match self {
            Self::Ref(card_ref) | Self::Sibling { sibling: card_ref } => Some(card_ref),
            Self::Inline(_) | Self::Path(_) => None,
        }
    }

    /// Mutable variant of [`InlineableRef::as_card_ref`].
    #[must_use]
    pub fn as_card_ref_mut(&mut self) -> Option<&mut CardRef> {
        match self {
            Self::Ref(card_ref) | Self::Sibling { sibling: card_ref } => Some(card_ref),
            Self::Inline(_) | Self::Path(_) => None,
        }
    }

    /// Return the embedded child body when authored inline.
    #[must_use]
    pub fn as_inline(&self) -> Option<&T> {
        match self {
            Self::Inline(body) => Some(body),
            Self::Ref(_) | Self::Sibling { .. } | Self::Path(_) => None,
        }
    }

    /// Return the embedded child body mutably when authored inline.
    #[must_use]
    pub fn as_inline_mut(&mut self) -> Option<&mut T> {
        match self {
            Self::Inline(body) => Some(body),
            Self::Ref(_) | Self::Sibling { .. } | Self::Path(_) => None,
        }
    }

    /// Return the exact identity when this is a loader-projected sibling.
    #[must_use]
    pub fn as_sibling(&self) -> Option<&CardRef> {
        match self {
            Self::Sibling { sibling } => Some(sibling),
            Self::Ref(_) | Self::Inline(_) | Self::Path(_) => None,
        }
    }

    /// Project an identity-bearing slot onto the durable [`Ref`] shape,
    /// keeping its authored provenance: an external `Ref` stays `Ref` and a
    /// loader `Sibling` stays `Sibling`, so consumers never infer the body's
    /// source from identity alone.
    ///
    /// Returns `None` for an inline body or an unresolved path.
    #[must_use]
    pub fn to_durable(&self) -> Option<Ref> {
        match self {
            Self::Ref(card_ref) => Some(Ref::Ref(card_ref.clone())),
            Self::Sibling { sibling } => Some(Ref::Sibling {
                sibling: sibling.clone(),
            }),
            Self::Inline(_) | Self::Path(_) => None,
        }
    }
}

impl<T> From<CardRef> for InlineableRef<T> {
    fn from(card_ref: CardRef) -> Self {
        Self::Ref(card_ref)
    }
}

impl From<skald_spec::Prompt> for InlineableRef<skald_spec::Prompt> {
    fn from(prompt: skald_spec::Prompt) -> Self {
        Self::Inline(Box::new(prompt))
    }
}

impl From<crate::card::agent::AgentSpec> for InlineableRef<crate::card::agent::AgentSpec> {
    fn from(spec: crate::card::agent::AgentSpec) -> Self {
        Self::Inline(Box::new(spec))
    }
}

impl CardRef {
    /// Return the exact named identity key for this reference.
    #[must_use]
    pub fn identity_key(&self) -> CardRefIdentity {
        CardRefIdentity {
            kind: self.kind.clone(),
            space: self.space.clone(),
            name: self.name.clone(),
            version: self.version.as_str().to_owned(),
        }
    }

    /// True when two card refs share the exact named identity tuple.
    ///
    /// The optional `uid` is ignored — authorization is identity-based on
    /// `(kind, space, name, version)` only.
    #[must_use]
    pub fn same_identity(&self, other: &CardRef) -> bool {
        self.kind == other.kind
            && self.space == other.space
            && self.name == other.name
            && self.version == other.version
    }
}

/// A principal's card authorization set.
///
/// Authorization is identity-based on `(kind, name, version, space)`. The
/// optional resolved `uid` is ignored.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CardRefScope(Vec<CardRef>);

impl CardRefScope {
    /// Borrow scope members.
    #[must_use]
    pub fn as_slice(&self) -> &[CardRef] {
        &self.0
    }

    /// Whether the scope has no members.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Number of scope members.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Build a scope and guarantee that `root` is the first member.
    ///
    /// Duplicate identity (same `(kind, name, version, space)`, ignoring `uid`)
    /// is removed. Root is always retained as the first element.
    ///
    /// A duplicate that carries a resolved `uid` donates it to the retained
    /// entry. Mint resolves each scope member against the tenant-local
    /// registry while its callers still hold the authored, UID-less root, so
    /// without this the resolved root identity would be dropped and ingest
    /// could not stamp `card_uid` from signed claims alone.
    #[must_use]
    pub fn from_root_and_members(
        root: &CardRef,
        members: impl IntoIterator<Item = CardRef>,
    ) -> Self {
        let mut scope = vec![root.clone()];
        for member in members {
            match scope
                .iter_mut()
                .find(|existing| existing.same_identity(&member))
            {
                Some(existing) => {
                    if existing.uid.is_none() {
                        existing.uid = member.uid;
                    }
                }
                None => scope.push(member),
            }
        }
        Self(scope)
    }

    /// Build an own-card-only scope.
    ///
    /// Passing this as `card_ref_scope` on issuance is the canonical way to
    /// express "this token is scoped only to its own card." An empty
    /// `card_ref_scope` on a received wire token carries the same meaning and
    /// is upgraded to `own` by the verifier's `seed_scope` call.
    #[must_use]
    pub fn own(root: &CardRef) -> Self {
        Self::from_root_and_members(root, std::iter::empty())
    }

    /// True when the scope is empty (vacuously) or contains the root card.
    ///
    /// An empty scope is permitted because the wire format omits the scope
    /// field for own-scoped tokens and the verifier upgrades it to `own(root)`
    /// via `seed_scope`. If you need a stricter guarantee that the root was
    /// explicitly present at construction time, use `authorizes` on a
    /// non-empty scope.
    #[must_use]
    pub fn permits_root(&self, root: &CardRef) -> bool {
        self.is_empty() || self.authorizes(root)
    }

    /// Return true when `card` is authorized by identity.
    #[must_use]
    pub fn authorizes(&self, card: &CardRef) -> bool {
        self.0.iter().any(|member| member.same_identity(card))
    }

    /// The resolved UIDs of this scope's members, in member order.
    ///
    /// This is the set a row's `card_uid` correlation is authorized against:
    /// the UIDs the mint signed onto the scope. A member without a resolved
    /// UID contributes none, so no row can correlate to it.
    #[must_use]
    pub fn uids(&self) -> Vec<CardUid> {
        self.0
            .iter()
            .filter_map(|member| member.uid.clone())
            .collect()
    }
}

/// Serializes as a JSON array of `Display` strings (`"space/Kind/name@version"`).
///
/// This is the canonical wire encoding for `card_ref_scope` members in JWT claims
/// and HTTP payloads. Individual `card_ref` fields use an object shape instead —
/// this asymmetry exists because scope members are positional (root-first) and
/// compact by design. An empty array means "own-card scope"; the verifier upgrades
/// it to `own(root)` via `seed_scope`.
impl Serialize for CardRefScope {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_seq(self.0.iter().map(ToString::to_string))
    }
}

impl<'de> Deserialize<'de> for CardRefScope {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let members: Vec<CardRef> = Vec::<String>::deserialize(deserializer)?
            .into_iter()
            .map(|s| s.parse::<CardRef>().map_err(serde::de::Error::custom))
            .collect::<Result<Vec<_>, _>>()?;
        Ok(match members.as_slice() {
            [] => Self::default(),
            [root, rest @ ..] => Self::from_root_and_members(root, rest.iter().cloned()),
        })
    }
}

/// Every card ref a spec declares, for auth-scope traversal.
#[must_use]
pub fn scope_child_card_refs(spec: &Spec) -> Vec<CardRef> {
    let mut spec = spec.clone();
    let mut references = Vec::new();
    ReferenceSlotVisitor::visit(&mut spec, |slot| {
        references.extend(slot.value.as_card_ref().cloned());
    });
    references
}

/// Return every unresolved local Card reference path in a spec.
///
/// Traversal follows the typed reference visitor, including nested inline
/// Prompt and Agent bodies, and preserves declaration order.
#[must_use]
pub fn unresolved_card_ref_paths(spec: &Spec) -> Vec<PathBuf> {
    let mut spec = spec.clone();
    let mut paths = Vec::new();
    ReferenceSlotVisitor::visit(&mut spec, |slot| {
        paths.extend(slot.value.as_path().map(std::path::Path::to_path_buf));
    });
    paths
}

/// Return every registration-only sibling Card reference in declaration order.
///
/// Siblings express request-time registration intent rather than durable Card
/// identity. The typed visitor includes nested inline Agent and Prompt bodies,
/// so this helper lets persistence and read projections reject that intent
/// without traversing serialized JSON.
#[must_use]
pub fn registration_only_sibling_refs(spec: &Spec) -> Vec<CardRef> {
    let mut spec = spec.clone();
    let mut siblings = Vec::new();
    ReferenceSlotVisitor::visit(&mut spec, |slot| {
        siblings.extend(slot.value.as_sibling().cloned());
    });
    siblings
}

/// Bind server-resolved UIDs to the card references discovered by
/// [`scope_child_card_refs`]. The input pairs are authoritative; JSON values
/// are used only as the serialization boundary for the already typed spec and
/// are matched against the complete serialized `CardRef` identity shape. Any
/// existing `uid` is ignored because the server must replace authored values
/// with the UID it resolved.
///
/// # Panics
///
/// Panics if `CardRef` serialization fails, which it cannot.
pub fn bind_scoped_card_ref_uids(
    kind: &CardKind,
    spec: Spec,
    resolved: &[(CardRef, CardUid)],
) -> Result<Spec, crate::envelope::SpecDecodeError> {
    if resolved.is_empty() {
        return Ok(spec);
    }
    let mut value =
        serde_json::to_value(spec).map_err(|error| crate::envelope::SpecDecodeError {
            kind: kind.wire_name().to_owned(),
            message: error.to_string(),
        })?;
    for (card_ref, uid) in resolved {
        let mut target =
            serde_json::to_value(card_ref).expect("CardRef serialization is infallible");
        if let serde_json::Value::Object(object) = &mut target {
            object.remove("uid");
        }
        let uid_value = serde_json::to_value(uid).expect("CardUid serialization is infallible");
        bind_serialized_ref(&mut value, &target, &uid_value);
    }
    Spec::from_kind_and_value(kind, value)
}

/// Walk a serialized spec and add one resolved UID to exact `CardRef` objects.
///
/// Matching the complete serialized reference identity prevents a short generic
/// object with the same four identity fields from being rewritten accidentally.
/// The optional UID is excluded from the comparison so stale authored UIDs are
/// replaced. The traversal visits nested arrays and objects because references
/// can appear in several kind-specific spec shapes.
fn bind_serialized_ref(
    value: &mut serde_json::Value,
    target: &serde_json::Value,
    uid: &serde_json::Value,
) {
    match value {
        serde_json::Value::Array(values) => {
            for value in values {
                bind_serialized_ref(value, target, uid);
            }
        }
        serde_json::Value::Object(object) => {
            let mut identity = object.clone();
            identity.remove("uid");
            if serde_json::Value::Object(identity) == *target {
                object.insert("uid".to_owned(), uid.clone());
            }
            for value in object.values_mut() {
                bind_serialized_ref(value, target, uid);
            }
        }
        serde_json::Value::Null
        | serde_json::Value::Bool(_)
        | serde_json::Value::Number(_)
        | serde_json::Value::String(_) => {}
    }
}

impl fmt::Display for CardRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}/{}/{}@{}",
            self.space
                .as_ref()
                .map_or("<missing-space>", SpaceName::as_str),
            self.kind.wire_name(),
            self.name,
            self.version
        )?;
        if let Some(uid) = &self.uid {
            write!(f, "#{uid}")?;
        }
        Ok(())
    }
}

impl FromStr for CardRef {
    type Err = CardRefParseError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let (head, uid) = match value.split_once('#') {
            Some((head, uid)) => (head, Some(uid.parse().map_err(CardRefParseError::Uid)?)),
            None => (value, None),
        };
        let (before_version, version) = head
            .rsplit_once('@')
            .ok_or(CardRefParseError::MissingVersion)?;
        let mut parts = before_version.split('/');
        let space = parts
            .next()
            .ok_or(CardRefParseError::MissingSpace)?
            .parse()
            .map_err(CardRefParseError::Space)?;
        let kind = parts
            .next()
            .ok_or(CardRefParseError::MissingKind)
            .and_then(parse_card_kind)?;
        let name = parts
            .next()
            .ok_or(CardRefParseError::MissingName)?
            .parse()
            .map_err(CardRefParseError::Name)?;
        if parts.next().is_some() {
            return Err(CardRefParseError::TooManySegments);
        }

        Ok(Self {
            kind,
            name,
            version: version.parse().map_err(CardRefParseError::Version)?,
            space: Some(space),
            uid,
        })
    }
}

fn parse_card_kind(value: &str) -> Result<CardKind, CardRefParseError> {
    CardKind::native()
        .into_iter()
        .find(|kind| kind.wire_name() == value)
        .ok_or_else(|| CardRefParseError::Kind(value.to_owned()))
}

/// Card reference text parse error.
#[derive(Debug, thiserror::Error)]
pub enum CardRefParseError {
    /// Missing space segment.
    #[error("card ref is missing space")]
    MissingSpace,
    /// Missing kind segment.
    #[error("card ref is missing kind")]
    MissingKind,
    /// Missing name segment.
    #[error("card ref is missing name")]
    MissingName,
    /// Missing version suffix.
    #[error("card ref is missing @version")]
    MissingVersion,
    /// Too many slash-delimited segments.
    #[error("card ref must be space/kind/name@version[#uid]")]
    TooManySegments,
    /// Unknown card kind.
    #[error("unknown card kind: {0}")]
    Kind(String),
    /// Space failed validation.
    #[error("invalid space: {0}")]
    Space(crate::ids::IdError),
    /// Name failed validation.
    #[error("invalid name: {0}")]
    Name(crate::ids::IdError),
    /// Version failed validation.
    #[error("invalid version: {0}")]
    Version(wyrd_semver::VersionError),
    /// UID failed validation.
    #[error("invalid uid: {0}")]
    Uid(crate::ids::IdError),
}
#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use super::*;
    use crate::card::agent::{AgentRunConfigSpec, AgentSpec};
    use crate::card::mcp::McpSpec;
    use crate::card::service::{ServiceComponent, ServiceSpec};

    fn sample_ref() -> CardRef {
        CardRef {
            kind: CardKind::Artifact,
            name: CardName::new("weights").expect("static name is valid"),
            version: VersionBlock::parse("1.0.0").expect("static version is valid"),
            space: Some(SpaceName::new("prod").expect("static space is valid")),
            uid: None,
        }
    }

    #[test]
    fn card_ref_display_and_from_str_roundtrip() {
        let card_ref = CardRef {
            kind: CardKind::Service,
            name: CardName::new("billing").expect("static name is valid"),
            version: VersionBlock::parse("1.0.0").expect("static version is valid"),
            space: Some(SpaceName::new("prod").expect("static space is valid")),
            uid: None,
        };

        let text = card_ref.to_string();
        let parsed: CardRef = text.parse().expect("card ref parses");

        assert_eq!(text, "prod/Service/billing@1.0.0");
        assert_eq!(parsed, card_ref);
    }

    #[test]
    fn card_ref_canonical_round_trip() {
        let card_ref = sample_ref();

        let parsed: CardRef = card_ref.to_string().parse().expect("card ref parses");

        assert_eq!(parsed, card_ref);
    }

    #[test]
    fn card_ref_with_uid_round_trip() {
        let card_ref = CardRef {
            uid: Some(
                CardUid::new("01890f28-7c4a-7cc3-98e7-4f4a3c2d1b11").expect("static uid is valid"),
            ),
            ..sample_ref()
        };

        let text = card_ref.to_string();
        let parsed: CardRef = text.parse().expect("card ref parses");

        assert_eq!(
            text,
            "prod/Artifact/weights@1.0.0#01890f28-7c4a-7cc3-98e7-4f4a3c2d1b11"
        );
        assert_eq!(parsed, card_ref);
    }

    #[test]
    fn card_ref_display_fromstr_inverse() {
        let card_ref = sample_ref();

        let parsed: CardRef = card_ref.to_string().parse().expect("card ref parses");

        assert_eq!(parsed.to_string(), card_ref.to_string());
    }

    #[test]
    fn card_ref_canonical_bytes_pinned() {
        let card_ref = CardRef {
            uid: Some(
                CardUid::new("01890f28-7c4a-7cc3-98e7-4f4a3c2d1b11").expect("static uid is valid"),
            ),
            ..sample_ref()
        };

        let bytes = serde_json::to_vec(&card_ref).expect("card ref serializes");

        assert_eq!(
            std::str::from_utf8(&bytes).expect("json is utf8"),
            r#"{"kind":"Artifact","name":"weights","version":"1.0.0","space":"prod","uid":"01890f28-7c4a-7cc3-98e7-4f4a3c2d1b11"}"#
        );
    }

    #[test]
    fn card_ref_serde_roundtrips() {
        let card_ref = sample_ref();
        let json = serde_json::to_string(&card_ref).expect("serialize");
        let parsed: CardRef = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(card_ref, parsed);
    }

    #[test]
    fn sibling_ref_uses_explicit_wire_wrapper() {
        let reference = Ref::Sibling {
            sibling: sample_ref(),
        };
        let json = serde_json::to_value(&reference).expect("sibling ref serializes");
        assert_eq!(json, serde_json::json!({"sibling": sample_ref()}));
        let parsed: Ref = serde_json::from_value(json).expect("sibling ref deserializes");
        assert_eq!(parsed, reference);
    }

    #[test]
    fn card_ref_skips_none_uid() {
        let card_ref = CardRef {
            kind: CardKind::Model,
            name: CardName::new("churn").expect("static name is valid"),
            version: VersionBlock::parse("1.0.0").expect("static version is valid"),
            space: Some(SpaceName::new("default").expect("static space is valid")),
            uid: None,
        };
        let json = serde_json::to_string(&card_ref).expect("serialize");
        assert!(
            json.contains(r#""space":"default""#),
            "space must serialize"
        );
        assert!(!json.contains("uid"), "uid=None must skip");
    }

    /// The compact claim encoding is the only Card-scope contract on the wire,
    /// so it must carry each member's resolved registry UID through mint,
    /// signing, and verification without a parallel identity-to-UID map.
    #[test]
    fn card_ref_scope_serde_preserves_resolved_uids() {
        let root = CardRef {
            uid: Some(
                CardUid::new("01890f28-7c4a-7cc3-98e7-4f4a3c2d1b11").expect("static uid is valid"),
            ),
            ..sample_ref()
        };
        let secondary = CardRef {
            kind: CardKind::Model,
            name: CardName::new("scorer").expect("static name is valid"),
            uid: Some(
                CardUid::new("01890f28-7c4a-7cc3-98e7-4f4a3c2d1b22").expect("static uid is valid"),
            ),
            ..sample_ref()
        };
        let scope = CardRefScope::from_root_and_members(&root, [secondary.clone()]);

        let json = serde_json::to_string(&scope).expect("scope serializes");
        let parsed: CardRefScope = serde_json::from_str(&json).expect("scope deserializes");

        assert_eq!(
            json,
            r#"["prod/Artifact/weights@1.0.0#01890f28-7c4a-7cc3-98e7-4f4a3c2d1b11","prod/Model/scorer@1.0.0#01890f28-7c4a-7cc3-98e7-4f4a3c2d1b22"]"#,
            "compact claim encoding carries every resolved uid"
        );
        assert_eq!(parsed, scope, "round trip preserves the whole scope");
        assert_eq!(
            parsed.as_slice()[0].uid,
            root.uid,
            "root uid survives the claim round trip"
        );
        assert_eq!(
            parsed.as_slice()[1].uid,
            secondary.uid,
            "secondary uid survives the claim round trip"
        );
    }

    /// Mint holds the authored, UID-less root while the registry walk resolves
    /// the same identity, so the resolved UID must survive deduplication.
    #[test]
    fn from_root_and_members_adopts_resolved_root_uid() {
        let authored = sample_ref();
        let resolved = CardRef {
            uid: Some(
                CardUid::new("01890f28-7c4a-7cc3-98e7-4f4a3c2d1b11").expect("static uid is valid"),
            ),
            ..sample_ref()
        };

        let scope = CardRefScope::from_root_and_members(&authored, [resolved.clone()]);

        assert_eq!(
            scope.len(),
            1,
            "the resolved duplicate is still deduplicated"
        );
        assert_eq!(
            scope.as_slice()[0].uid,
            resolved.uid,
            "the resolved uid is adopted onto the retained root"
        );
    }

    #[test]
    fn binding_replaces_an_authored_uid_with_the_server_uid() {
        let authored_uid =
            CardUid::new("01890f28-7c4a-7cc3-98e7-4f4a3c2d1b11").expect("static uid is valid");
        let resolved_uid =
            CardUid::new("01890f28-7c4a-7cc3-98e7-4f4a3c2d1b12").expect("static uid is valid");
        let authored_ref = CardRef {
            kind: CardKind::Prompt,
            name: CardName::new("system-prompt").expect("static name is valid"),
            version: VersionBlock::parse("1.0.0").expect("static version is valid"),
            space: Some(SpaceName::new("default").expect("static space is valid")),
            uid: Some(authored_uid),
        };
        let lookup_ref = CardRef {
            uid: None,
            ..authored_ref.clone()
        };
        let spec = Spec::Mcp(McpSpec {
            server_name: "tools".to_owned(),
            tool_refs: vec![authored_ref.into()],
            ..McpSpec::default()
        });

        let bound =
            bind_scoped_card_ref_uids(&CardKind::Mcp, spec, &[(lookup_ref, resolved_uid.clone())])
                .expect("MCP spec remains valid after UID binding");

        let Spec::Mcp(bound) = bound else {
            panic!("expected an MCP spec");
        };
        assert_eq!(
            bound.tool_refs[0]
                .as_card_ref()
                .and_then(|card_ref| card_ref.uid.clone()),
            Some(resolved_uid)
        );
    }

    #[test]
    fn card_ref_accepts_missing_authored_space() {
        let json = r#"{"kind":"Model","name":"churn","version":"1.0.0"}"#;
        let card_ref =
            serde_json::from_str::<CardRef>(json).expect("space is optional while authored");
        assert!(card_ref.space.is_none());
    }

    #[test]
    fn card_ref_identity_ignores_uid_but_includes_version_and_space() {
        let first = sample_ref();
        let with_uid = CardRef {
            uid: Some(
                CardUid::new("01890f28-7c4a-7cc3-98e7-4f4a3c2d1b11").expect("static uid is valid"),
            ),
            ..first.clone()
        };
        assert!(first.same_identity(&with_uid));

        let different_version = CardRef {
            version: VersionBlock::parse("2.0.0").expect("static version is valid"),
            ..first.clone()
        };
        assert!(!first.same_identity(&different_version));

        let different_space = CardRef {
            space: Some(SpaceName::new("staging").expect("static space is valid")),
            ..first
        };
        assert!(!with_uid.same_identity(&different_space));
    }

    /// Build a verification binding whose Verifier, Trigger, and Operator
    /// slots are all unresolved authored paths under `dir`.
    fn path_binding(dir: &str) -> crate::card::verifier::VerificationBinding {
        crate::card::verifier::VerificationBinding {
            verifier: Ref::Path(PathBuf::from(format!("{dir}/verifier.yaml"))),
            runs_on: Some(InlineableRef::Path(PathBuf::from(format!(
                "{dir}/trigger.yaml"
            )))),
            on_failure: vec![InlineableRef::Path(PathBuf::from(format!(
                "{dir}/operator.yaml"
            )))],
        }
    }

    /// Confirm unresolved Service paths include component-local and
    /// Service-level verification binding slots in visit order.
    #[test]
    fn unresolved_card_ref_paths_include_top_level_slots() {
        let mut spec = ServiceSpec::default();
        spec.components.push(ServiceComponent {
            alias: "model".to_owned(),
            card_ref: Ref::Path(PathBuf::from("components/model.yaml")),
            verified_by: vec![path_binding("component")],
            source: None,
            config: BTreeMap::new(),
            credential_refs: Vec::new(),
        });
        spec.verified_by.push(path_binding("service"));

        assert_eq!(
            unresolved_card_ref_paths(&Spec::Service(spec)),
            vec![
                PathBuf::from("components/model.yaml"),
                PathBuf::from("component/verifier.yaml"),
                PathBuf::from("component/trigger.yaml"),
                PathBuf::from("component/operator.yaml"),
                PathBuf::from("service/verifier.yaml"),
                PathBuf::from("service/trigger.yaml"),
                PathBuf::from("service/operator.yaml"),
            ]
        );
    }

    /// A path reference nested in an inline Agent of a judge task is reported
    /// as unresolved.
    ///
    /// # Panics
    /// Panics when another set of paths is reported.
    #[test]
    fn unresolved_card_ref_paths_include_nested_slots() {
        let spec = nested_judge(InlineableRef::Path(PathBuf::from("nested/agent.yaml")));

        assert_eq!(
            unresolved_card_ref_paths(&spec),
            vec![PathBuf::from("nested/agent.yaml")]
        );
    }

    #[test]
    fn unresolved_card_ref_paths_are_empty_for_a_resolved_spec() {
        assert!(unresolved_card_ref_paths(&Spec::Service(ServiceSpec::default())).is_empty());
    }

    /// Build a prompt fixture that can be embedded in an inline Agent.
    fn nested_prompt() -> skald_spec::Prompt {
        skald_spec::Prompt::new(
            skald_spec::ProviderRequest::OpenAiChatCompletion(skald_spec::OpenAiChatRequest {
                model: "gpt-test".to_owned(),
                messages: vec![skald_spec::OpenAiChatMessage {
                    role: "user".to_owned(),
                    content: Some(skald_spec::wire::openai_chat::OpenAiMessageContent::Text(
                        "hello".to_owned(),
                    )),
                    ..Default::default()
                }],
                response_format: None,
                stream: None,
                stream_options: None,
                tools: None,
                tool_choice: None,
                parallel_tool_calls: None,
                settings: skald_spec::OpenAiChatSettings::default(),
            }),
            "gpt-test",
        )
        .expect("fixture prompt is valid")
    }

    /// Build an inline Agent whose prompt reference is supplied by the test.
    fn nested_agent(prompt: InlineableRef<skald_spec::Prompt>) -> AgentSpec {
        AgentSpec {
            prompt,
            execution_route: crate::card::agent::ExecutionRoute::Native {},
            tool_names: Vec::new(),
            run_config: AgentRunConfigSpec::default(),
            verified_by: Vec::new(),
        }
    }

    /// Return an Eval Verifier spec whose one LLM judge holds `judge_ref`.
    ///
    /// # Panics
    /// Panics when the fixed task id, judge, or Eval stops validating.
    fn nested_judge(judge_ref: InlineableRef<AgentSpec>) -> Spec {
        use crate::card::verifier::{VerifierImplementation, VerifierSpec};
        use crate::vala::eval::{ComparisonOperator, EvalSpec, EvalTask, LlmJudgeTask, TaskId};

        let task_id = TaskId::new("judge").expect("fixture task id is valid");
        let judge = LlmJudgeTask::new(
            task_id.clone(),
            judge_ref,
            ComparisonOperator::Equals,
            serde_json::json!(true),
        )
        .expect("fixture judge is valid");
        Spec::Verifier(VerifierSpec {
            description: None,
            implementation: VerifierImplementation::Eval(
                EvalSpec::new(BTreeMap::from([(task_id, EvalTask::LlmJudge(judge))]))
                    .expect("fixture eval is valid"),
            ),
        })
    }

    /// Confirm sibling collection covers top-level and nested slots in visitor order.
    ///
    /// # Panics
    /// Panics when a static name is invalid or another set of siblings is
    /// collected.
    #[test]
    fn registration_only_sibling_refs_include_top_level_and_nested_slots() {
        let top_level = sample_ref();
        let nested = CardRef {
            name: CardName::new("nested-prompt").expect("static name is valid"),
            ..sample_ref()
        };
        let mut service = ServiceSpec::default();
        service.components.push(ServiceComponent {
            alias: "top-level".to_owned(),
            card_ref: Ref::Sibling {
                sibling: top_level.clone(),
            },
            verified_by: Vec::new(),
            source: None,
            config: BTreeMap::new(),
            credential_refs: Vec::new(),
        });
        let spec = nested_judge(InlineableRef::Inline(Box::new(nested_agent(
            InlineableRef::Sibling {
                sibling: nested.clone(),
            },
        ))));

        assert_eq!(
            registration_only_sibling_refs(&Spec::Service(service)),
            vec![top_level]
        );
        assert_eq!(registration_only_sibling_refs(&spec), vec![nested]);
    }

    /// Confirm durable refs, paths, and inline bodies are not classified as siblings.
    ///
    /// # Panics
    /// Panics when a non-sibling reference is collected.
    #[test]
    fn registration_only_sibling_refs_ignore_other_reference_forms() {
        let durable = sample_ref();
        let path = PathBuf::from("nested/prompt.yaml");
        let mut service = ServiceSpec::default();
        service.components.extend([
            ServiceComponent {
                alias: "durable".to_owned(),
                card_ref: Ref::Ref(durable),
                verified_by: Vec::new(),
                source: None,
                config: BTreeMap::new(),
                credential_refs: Vec::new(),
            },
            ServiceComponent {
                alias: "path".to_owned(),
                card_ref: Ref::Path(path),
                verified_by: Vec::new(),
                source: None,
                config: BTreeMap::new(),
                credential_refs: Vec::new(),
            },
        ]);
        let judge = nested_judge(InlineableRef::Inline(Box::new(nested_agent(
            InlineableRef::Inline(Box::new(nested_prompt())),
        ))));

        assert!(registration_only_sibling_refs(&Spec::Service(service)).is_empty());
        assert!(registration_only_sibling_refs(&judge).is_empty());
    }
}