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
//! Reference slot visitor for traversing and mutating Card references within specs.
//!
//! This module provides the canonical visitor pattern for iterating over all reference
//! slots in a Card's spec. The visitor yields mutable handles to each reference position,
//! enabling reference resolution, validation, and transformation during the loader pipeline.

use crate::card::agent::AgentSpec;
use crate::card::artifact::ArtifactSpec;
use crate::card::audit::AuditSpec;
use crate::card::data::{DataInterface, DataSpec, SplitStrategy};
use crate::card::drift::{DriftSignal, DriftSpec};
use crate::card::eval::EvalSpec;
use crate::card::experiment::ExperimentSpec;
use crate::card::mcp::McpSpec;
use crate::card::model::ModelSpec;
use crate::card::operator::OperatorSpec;
use crate::card::service::ServiceSpec;
use crate::card::trigger::TriggerSpec;
use crate::card::verifier::{
    VerificationBinding, VerifierImplementation, VerifierSpec, VerifierTask,
};
use crate::envelope::Spec;
use crate::reference::{CardRef, InlineableRef, Ref};
use crate::vala::eval::EvalTask;
use skald_spec::Prompt;

/// A yielded reference slot with metadata about its kind and a mutable handle.
pub struct SlotEntry<'a> {
    /// The path to this slot in dot notation (e.g. `spec.verified_by[0].verifier`).
    pub path: String,
    /// The slot value yielded for inspection or mutation.
    pub value: SlotValue<'a>,
}

/// The slot value identifies the concrete reference shape at the slot.
pub enum SlotValue<'a> {
    /// A durable-only reference slot.
    Durable(&'a mut Ref),
    /// An inlineable Skald prompt slot.
    InlineablePrompt(&'a mut InlineableRef<Prompt>),
    /// An inlineable Agent spec slot.
    InlineableAgent(&'a mut InlineableRef<AgentSpec>),
    /// An inlineable Trigger spec slot (`verified_by[..].runs_on`).
    InlineableTrigger(&'a mut InlineableRef<TriggerSpec>),
    /// An inlineable Operator spec slot (`verified_by[..].on_failure[..]`).
    InlineableOperator(&'a mut InlineableRef<OperatorSpec>),
}

impl SlotValue<'_> {
    /// Return the resolved [`CardRef`] this slot carries.
    ///
    /// Returns `None` for an unresolved `Path` and for an inline body, which
    /// has no separate Card identity.
    #[must_use]
    pub fn as_card_ref(&self) -> Option<&CardRef> {
        match self {
            Self::Durable(reference) => reference.as_card_ref(),
            Self::InlineablePrompt(reference) => reference.as_card_ref(),
            Self::InlineableAgent(reference) => reference.as_card_ref(),
            Self::InlineableTrigger(reference) => reference.as_card_ref(),
            Self::InlineableOperator(reference) => reference.as_card_ref(),
        }
    }

    /// Return the exact identity when this slot holds a loader-projected sibling.
    #[must_use]
    pub fn as_sibling(&self) -> Option<&CardRef> {
        match self {
            Self::Durable(reference) => reference.as_sibling(),
            Self::InlineablePrompt(reference) => reference.as_sibling(),
            Self::InlineableAgent(reference) => reference.as_sibling(),
            Self::InlineableTrigger(reference) => reference.as_sibling(),
            Self::InlineableOperator(reference) => reference.as_sibling(),
        }
    }

    /// Mutable variant of [`SlotValue::as_card_ref`].
    #[must_use]
    pub fn as_card_ref_mut(&mut self) -> Option<&mut CardRef> {
        match self {
            Self::Durable(reference) => reference.as_card_ref_mut(),
            Self::InlineablePrompt(reference) => reference.as_card_ref_mut(),
            Self::InlineableAgent(reference) => reference.as_card_ref_mut(),
            Self::InlineableTrigger(reference) => reference.as_card_ref_mut(),
            Self::InlineableOperator(reference) => reference.as_card_ref_mut(),
        }
    }

    /// Rewrite this slot from an authored path to a loader-projected sibling.
    ///
    /// Each slot shape keeps its own sibling form, so the loader does not need
    /// to know which concrete reference type it is holding. Slots that are not
    /// currently a `Path` are left untouched.
    pub fn resolve_path_to_sibling(&mut self, sibling: CardRef) {
        match self {
            Self::Durable(reference) => {
                if matches!(reference, Ref::Path(_)) {
                    **reference = Ref::Sibling { sibling };
                }
            }
            Self::InlineablePrompt(reference) => set_inlineable_sibling(reference, sibling),
            Self::InlineableAgent(reference) => set_inlineable_sibling(reference, sibling),
            Self::InlineableTrigger(reference) => set_inlineable_sibling(reference, sibling),
            Self::InlineableOperator(reference) => set_inlineable_sibling(reference, sibling),
        }
    }

    /// Return the authored local path when this slot is still unresolved.
    #[must_use]
    pub fn as_path(&self) -> Option<&std::path::Path> {
        match self {
            Self::Durable(Ref::Path(path))
            | Self::InlineablePrompt(InlineableRef::Path(path))
            | Self::InlineableAgent(InlineableRef::Path(path))
            | Self::InlineableTrigger(InlineableRef::Path(path))
            | Self::InlineableOperator(InlineableRef::Path(path)) => Some(path),
            _ => None,
        }
    }
}

/// Replace one inlineable slot's authored path with its sibling projection.
fn set_inlineable_sibling<T>(reference: &mut InlineableRef<T>, sibling: CardRef) {
    if matches!(reference, InlineableRef::Path(_)) {
        *reference = InlineableRef::Sibling { sibling };
    }
}

/// Canonical visitor that yields every reference slot on a `Spec`.
pub struct ReferenceSlotVisitor;

impl ReferenceSlotVisitor {
    /// Visit every reference slot on the given spec.
    ///
    /// Calls `f` once per slot with the slot's path, kind, and a mutable handle.
    /// The visitor yields slots in declaration order.
    pub fn visit<F>(spec: &mut Spec, mut f: F)
    where
        F: FnMut(SlotEntry<'_>),
    {
        match spec {
            Spec::Data(data) => data.visit(&mut f),
            Spec::Model(model) => model.visit(&mut f),
            Spec::Experiment(experiment) => experiment.visit(&mut f),
            Spec::Prompt(_)
            | Spec::Policy(_)
            | Spec::Trigger(_)
            | Spec::Source(_)
            | Spec::Operator(_) => {}
            Spec::Agent(agent) => agent.visit(&mut f),
            Spec::Verifier(verifier) => verifier.visit(&mut f),
            Spec::Service(service) => service.visit(&mut f),
            Spec::Mcp(mcp) => mcp.visit(&mut f),
            Spec::Audit(audit) => audit.visit(&mut f),
            Spec::Artifact(artifact) => artifact.visit(&mut f),
        }
    }
}

/// Trait for specs that carry reference slots.
pub trait Visit {
    /// Visit every reference slot on this spec, invoking `f` for each.
    fn visit<F>(&mut self, f: &mut F)
    where
        F: FnMut(SlotEntry<'_>);
}

impl Visit for DataSpec {
    /// Visit intrinsic Data lineage and materialization references.
    fn visit<F>(&mut self, f: &mut F)
    where
        F: FnMut(SlotEntry<'_>),
    {
        for (i, card_ref) in self.card_refs.iter_mut().enumerate() {
            f(SlotEntry {
                path: format!("spec.card_refs[{i}]"),
                value: SlotValue::Durable(card_ref),
            });
        }
        for (label, split) in &mut self.splits {
            if let SplitStrategy::Materialized(card_ref) = &mut split.strategy {
                f(SlotEntry {
                    path: format!("spec.splits[{label}].strategy.Materialized"),
                    value: SlotValue::Durable(card_ref),
                });
            }
        }
        match &mut self.interface {
            DataInterface::Image(meta) => {
                if let Some(card_ref) = &mut meta.manifest_ref {
                    f(SlotEntry {
                        path: "spec.interface.Image.manifest_ref".to_owned(),
                        value: SlotValue::Durable(card_ref),
                    });
                }
            }
            DataInterface::Text(meta) => {
                if let Some(card_ref) = &mut meta.manifest_ref {
                    f(SlotEntry {
                        path: "spec.interface.Text.manifest_ref".to_owned(),
                        value: SlotValue::Durable(card_ref),
                    });
                }
            }
            _ => {}
        }
    }
}

impl Visit for ModelSpec {
    /// Visit intrinsic Model artifact and lineage references.
    fn visit<F>(&mut self, f: &mut F)
    where
        F: FnMut(SlotEntry<'_>),
    {
        for (i, card_ref) in self.card_refs.iter_mut().enumerate() {
            f(SlotEntry {
                path: format!("spec.card_refs[{i}]"),
                value: SlotValue::Durable(card_ref),
            });
        }
    }
}

impl Visit for ExperimentSpec {
    fn visit<F>(&mut self, f: &mut F)
    where
        F: FnMut(SlotEntry<'_>),
    {
        for (i, card_ref) in self.target_refs.iter_mut().enumerate() {
            f(SlotEntry {
                path: format!("spec.target_refs[{i}]"),
                value: SlotValue::Durable(card_ref),
            });
        }
        for (i, card_ref) in self.card_refs.iter_mut().enumerate() {
            f(SlotEntry {
                path: format!("spec.card_refs[{i}]"),
                value: SlotValue::Durable(card_ref),
            });
        }
    }
}

impl Visit for AgentSpec {
    fn visit<F>(&mut self, f: &mut F)
    where
        F: FnMut(SlotEntry<'_>),
    {
        visit_agent(self, "spec", f);
    }
}

impl Visit for EvalSpec {
    /// Visit the dataset reference and every LLM-judge Agent slot.
    fn visit<F>(&mut self, f: &mut F)
    where
        F: FnMut(SlotEntry<'_>),
    {
        self.visit_at("spec.implementation.spec", f);
    }
}

impl EvalSpec {
    /// Visit this Eval payload's reference slots under an explicit path prefix.
    ///
    /// The payload is only reachable inside a Verifier implementation, so the
    /// prefix names that enclosing slot rather than a bare `spec`.
    fn visit_at<F>(&mut self, prefix: &str, f: &mut F)
    where
        F: FnMut(SlotEntry<'_>),
    {
        if let Some(dataset_ref) = &mut self.dataset {
            f(SlotEntry {
                path: format!("{prefix}.dataset"),
                value: SlotValue::Durable(&mut dataset_ref.0),
            });
        }

        for (task_id, task) in &mut self.tasks {
            if let EvalTask::LlmJudge(llm_judge_task) = task {
                let path = format!("{prefix}.tasks[{}].LlmJudge.judge_ref", task_id.as_str());
                f(SlotEntry {
                    path: path.clone(),
                    value: SlotValue::InlineableAgent(&mut llm_judge_task.judge_ref),
                });
                if let InlineableRef::Inline(agent) = &mut llm_judge_task.judge_ref {
                    visit_agent(agent, &path, f);
                }
            }
        }
    }
}

impl Visit for DriftSpec {
    /// Visit the baseline Data reference carried by a `Distribution` signal.
    fn visit<F>(&mut self, f: &mut F)
    where
        F: FnMut(SlotEntry<'_>),
    {
        self.visit_at("spec.implementation.spec", f);
    }
}

impl DriftSpec {
    /// Visit this Drift payload's reference slots under an explicit path prefix.
    ///
    /// The payload is only reachable inside a Verifier implementation, so the
    /// prefix names that enclosing slot rather than a bare `spec`.
    fn visit_at<F>(&mut self, prefix: &str, f: &mut F)
    where
        F: FnMut(SlotEntry<'_>),
    {
        match &mut self.signal {
            DriftSignal::Distribution { baseline_ref, .. } => {
                f(SlotEntry {
                    path: format!("{prefix}.signal.Distribution.baseline_ref"),
                    value: SlotValue::Durable(baseline_ref),
                });
            }
            DriftSignal::Metric { .. } => {}
        }
    }
}

impl Visit for VerifierSpec {
    /// Visit the reference slots owned by this Verifier's one implementation.
    fn visit<F>(&mut self, f: &mut F)
    where
        F: FnMut(SlotEntry<'_>),
    {
        match &mut self.implementation {
            VerifierImplementation::Drift(drift) => {
                drift.visit_at("spec.implementation.spec", f);
            }
            VerifierImplementation::Eval(eval) => {
                eval.visit_at("spec.implementation.spec", f);
            }
            VerifierImplementation::Task(task) => {
                if let VerifierTask::LlmJudge(judge) = &mut task.definition {
                    let path = "spec.implementation.spec.judge_ref".to_owned();
                    f(SlotEntry {
                        path: path.clone(),
                        value: SlotValue::InlineableAgent(&mut judge.judge_ref),
                    });
                    if let InlineableRef::Inline(agent) = &mut judge.judge_ref {
                        visit_agent(agent, &path, f);
                    }
                }
            }
        }
    }
}

impl Visit for ServiceSpec {
    /// Visit component identities, component verification bindings, and Service bindings.
    fn visit<F>(&mut self, f: &mut F)
    where
        F: FnMut(SlotEntry<'_>),
    {
        for (i, component) in self.components.iter_mut().enumerate() {
            f(SlotEntry {
                path: format!("spec.components[{i}].ref"),
                value: SlotValue::Durable(&mut component.card_ref),
            });
            visit_verified_by(
                &mut component.verified_by,
                &format!("spec.components[{i}].verified_by"),
                f,
            );
        }
        visit_verified_by(&mut self.verified_by, "spec.verified_by", f);
    }
}

impl Visit for McpSpec {
    fn visit<F>(&mut self, f: &mut F)
    where
        F: FnMut(SlotEntry<'_>),
    {
        for (i, card_ref) in self.tool_refs.iter_mut().enumerate() {
            f(SlotEntry {
                path: format!("spec.tool_refs[{i}]"),
                value: SlotValue::Durable(card_ref),
            });
        }
    }
}

impl Visit for AuditSpec {
    fn visit<F>(&mut self, f: &mut F)
    where
        F: FnMut(SlotEntry<'_>),
    {
        for (i, card_ref) in self.subject_refs.iter_mut().enumerate() {
            f(SlotEntry {
                path: format!("spec.subject_refs[{i}]"),
                value: SlotValue::Durable(card_ref),
            });
        }
        for (i, card_ref) in self.policy_refs.iter_mut().enumerate() {
            f(SlotEntry {
                path: format!("spec.policy_refs[{i}]"),
                value: SlotValue::Durable(card_ref),
            });
        }
        for (i, card_ref) in self.evidence_refs.iter_mut().enumerate() {
            f(SlotEntry {
                path: format!("spec.evidence_refs[{i}]"),
                value: SlotValue::Durable(card_ref),
            });
        }
    }
}

impl Visit for ArtifactSpec {
    fn visit<F>(&mut self, f: &mut F)
    where
        F: FnMut(SlotEntry<'_>),
    {
        if let Some(schema_ref) = &mut self.schema_ref {
            f(SlotEntry {
                path: "spec.schema_ref".to_owned(),
                value: SlotValue::Durable(schema_ref),
            });
        }
    }
}

/// Visit one verification-binding list using the exact owning field path.
///
/// Each binding yields its Verifier reference, its `runs_on` Trigger slot when
/// one is authored, and
/// every `on_failure` Operator slot. Inline Triggers and Operators carry no
/// references of their own.
fn visit_verified_by<F>(bindings: &mut [VerificationBinding], path: &str, f: &mut F)
where
    F: FnMut(SlotEntry<'_>),
{
    for (index, binding) in bindings.iter_mut().enumerate() {
        f(SlotEntry {
            path: format!("{path}[{index}].verifier"),
            value: SlotValue::Durable(&mut binding.verifier),
        });
        if let Some(runs_on) = &mut binding.runs_on {
            f(SlotEntry {
                path: format!("{path}[{index}].runs_on"),
                value: SlotValue::InlineableTrigger(runs_on),
            });
        }
        for (operator_index, operator) in binding.on_failure.iter_mut().enumerate() {
            f(SlotEntry {
                path: format!("{path}[{index}].on_failure[{operator_index}]"),
                value: SlotValue::InlineableOperator(operator),
            });
        }
    }
}

fn visit_agent<F>(agent: &mut AgentSpec, prefix: &str, f: &mut F)
where
    F: FnMut(SlotEntry<'_>),
{
    f(SlotEntry {
        path: format!("{prefix}.prompt"),
        value: SlotValue::InlineablePrompt(&mut agent.prompt),
    });
    visit_verified_by(&mut agent.verified_by, &format!("{prefix}.verified_by"), f);
}

#[cfg(test)]
mod completeness_tests {
    use std::collections::{BTreeMap, HashMap};

    use serde_json::json;
    use skald_spec::Prompt;

    use super::{ReferenceSlotVisitor, SlotValue};
    use crate::card::agent::{AgentRunConfigSpec, AgentSpec};
    use crate::card::artifact::ArtifactSpec;
    use crate::card::audit::AuditSpec;
    use crate::card::data::{
        ColorMode, DataInterface, DataSchema, DataSpec, DataSplit, DataStats, ImageFormat,
        ImageMeta, PandasMeta, ParquetCompression, SplitStrategy, TextMeta,
    };
    use crate::card::drift::{
        DriftCondition, DriftMethod, DriftProfile, DriftSignal, DriftSpec, PsiBinningStrategy,
        PsiProfile, PsiThreshold,
    };
    use crate::card::experiment::ExperimentSpec;
    use crate::card::field::FieldSpec;
    use crate::card::mcp::McpSpec;
    use crate::card::model::{ModelInterface, ModelSignature, ModelSpec, SklearnMeta, TaskType};
    use crate::card::operator::OperatorSpec;
    use crate::card::service::{ServiceComponent, ServiceSpec};
    use crate::card::trigger::{TriggerActivation, TriggerSpec};
    use crate::card::verifier::{VerificationBinding, VerifierImplementation, VerifierSpec};
    use crate::envelope::{CardKind, Spec};
    use crate::ids::{CardName, ColumnName, SpaceName};
    use crate::reference::{CardRef, InlineableRef, Ref};
    use crate::vala::eval::ids::TaskId;
    use crate::vala::eval::{ComparisonOperator, DatasetRef, EvalSpec, EvalTask, LlmJudgeTask};
    use wyrd_semver::VersionBlock;

    fn card_ref(kind: CardKind, name: &str) -> CardRef {
        CardRef {
            kind,
            name: CardName::new(name).expect("fixture card name is valid"),
            version: VersionBlock::parse("1.0.0").expect("fixture version is valid"),
            space: Some(SpaceName::new("default").expect("fixture space is valid")),
            uid: None,
        }
    }

    fn prompt() -> Prompt {
        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(
                        "judge ${context}".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")
    }

    /// A native-route Agent spec with an inline Prompt and a one-iteration run
    /// config, used as a nested reference slot.
    ///
    /// # Panics
    /// Panics when the fixture Prompt is invalid.
    fn agent() -> AgentSpec {
        AgentSpec {
            prompt: InlineableRef::Inline(Box::new(prompt())),
            execution_route: crate::card::agent::ExecutionRoute::Native {},
            tool_names: Vec::new(),
            run_config: AgentRunConfigSpec {
                max_iterations: Some(1),
                ..AgentRunConfigSpec::default()
            },
            verified_by: Vec::new(),
        }
    }

    fn data(interface: DataInterface) -> DataSpec {
        DataSpec {
            interface,
            schema: DataSchema::new(vec![FieldSpec::new(
                ColumnName::new("value").expect("fixture column is valid"),
                "int64",
            )]),
            card_refs: vec![Ref::Ref(card_ref(CardKind::Artifact, "data-artifact"))],
            splits: HashMap::from([(
                crate::ids::SplitName::new("train").expect("fixture split is valid"),
                DataSplit {
                    label: crate::ids::SplitName::new("train").expect("fixture split is valid"),
                    strategy: SplitStrategy::Materialized(Ref::Ref(card_ref(
                        CardKind::Artifact,
                        "split-artifact",
                    ))),
                },
            )]),
            target_columns: Vec::new(),
            sql: None,
            stats: DataStats {
                row_count: Some(1),
                col_count: Some(1),
                byte_count: 1,
                sha256: "a".repeat(64),
            },
        }
    }

    fn model() -> ModelSpec {
        ModelSpec {
            interface: ModelInterface::Sklearn(SklearnMeta {
                framework_version: "1.0".to_owned(),
                model_subtype: None,
            }),
            task_type: TaskType::Regression,
            signature: ModelSignature::new(
                vec![FieldSpec::new(
                    ColumnName::new("input").expect("fixture column is valid"),
                    "float32",
                )],
                vec![FieldSpec::new(
                    ColumnName::new("output").expect("fixture column is valid"),
                    "float32",
                )],
            ),
            sample_input: None,
            card_refs: vec![Ref::Ref(card_ref(CardKind::Artifact, "model-artifact"))],
        }
    }

    fn eval() -> EvalSpec {
        let task_id = TaskId::new("judge").expect("fixture task id is valid");
        let judge = LlmJudgeTask::new(
            task_id.clone(),
            agent(),
            ComparisonOperator::Equals,
            json!(true),
        )
        .expect("fixture judge is valid");
        let mut eval = EvalSpec::new(BTreeMap::from([(task_id, EvalTask::LlmJudge(judge))]))
            .expect("fixture eval is valid");
        eval.dataset = Some(DatasetRef(Ref::Ref(card_ref(CardKind::Data, "dataset"))));
        eval
    }

    /// Build a PSI Drift payload whose baseline is the only reference slot.
    fn drift() -> DriftSpec {
        DriftSpec {
            description: None,
            method: DriftMethod::Psi,
            signal: DriftSignal::Distribution {
                baseline_ref: Ref::Ref(card_ref(CardKind::Data, "baseline")),
                features: vec!["value".parse().expect("fixture feature is valid")],
            },
            condition: DriftCondition::Statistical,
            profile: Some(DriftProfile::Psi(PsiProfile {
                binning_strategy: PsiBinningStrategy::Quantile { n_bins: 10 },
                categorical_features: Vec::new(),
                threshold: PsiThreshold::Fixed { value: 0.25 },
            })),
        }
    }

    /// An inline notify Operator, which carries no reference slots.
    ///
    /// # Panics
    /// Panics when the fixed notify body stops decoding as an Operator.
    fn notify_operator() -> OperatorSpec {
        serde_json::from_value(json!({
            "kind": "notify",
            "channel": {
                "kind": "pager_duty",
                "connection": "pagerduty",
                "route": "team-a",
                "severity": "critical",
                "summary": "verification failed",
            },
        }))
        .expect("fixture notify Operator decodes")
    }

    /// Build one binding with a referenced Trigger, a referenced Operator, and
    /// an inline Operator so every `verified_by` slot shape is visited.
    fn binding(verifier: &str) -> VerificationBinding {
        VerificationBinding {
            verifier: Ref::Ref(card_ref(CardKind::Verifier, verifier)),
            runs_on: Some(InlineableRef::Ref(card_ref(CardKind::Trigger, "hourly"))),
            on_failure: vec![
                InlineableRef::Ref(card_ref(CardKind::Operator, "page")),
                InlineableRef::Inline(Box::new(notify_operator())),
            ],
        }
    }

    /// Project a visited spec into `(path, slot shape)` pairs in visit order.
    fn visit_paths(mut spec: Spec) -> Vec<(String, &'static str)> {
        let mut paths = Vec::new();
        ReferenceSlotVisitor::visit(&mut spec, |entry| {
            let kind = match entry.value {
                SlotValue::Durable(_) => "durable",
                SlotValue::InlineablePrompt(_) => "inlineable_prompt",
                SlotValue::InlineableAgent(_) => "inlineable_agent",
                SlotValue::InlineableTrigger(_) => "inlineable_trigger",
                SlotValue::InlineableOperator(_) => "inlineable_operator",
            };
            paths.push((entry.path, kind));
        });
        paths
    }

    /// Confirm the canonical visitor exposes every supported reference slot exactly once.
    ///
    /// # Panics
    /// Panics when a fixture is invalid or the visitor reports another set of
    /// slots.
    #[test]
    fn every_spec_ref_field_is_ref_or_inlineable_ref() {
        let image = data(DataInterface::Image(ImageMeta {
            format: ImageFormat::Png,
            manifest_ref: Some(Ref::Ref(card_ref(CardKind::Artifact, "manifest"))),
            color_mode: ColorMode::Rgb,
        }));
        let text = data(DataInterface::Text(TextMeta {
            encoding: "utf-8".to_owned(),
            manifest_ref: Some(Ref::Ref(card_ref(CardKind::Artifact, "text-manifest"))),
        }));
        let mut experiment = ExperimentSpec {
            target_refs: vec![Ref::Ref(card_ref(CardKind::Model, "target"))],
            card_refs: vec![Ref::Ref(card_ref(CardKind::Artifact, "artifact"))],
            ..ExperimentSpec::default()
        };
        let mut artifact = ArtifactSpec {
            artifact_kind: "file".to_owned(),
            schema_ref: Some(Ref::Ref(card_ref(CardKind::Data, "schema"))),
            ..ArtifactSpec::default()
        };
        let mut audit = AuditSpec {
            subject_refs: vec![Ref::Ref(card_ref(CardKind::Model, "subject"))],
            policy_refs: vec![Ref::Ref(card_ref(CardKind::Policy, "policy"))],
            evidence_refs: vec![Ref::Ref(card_ref(CardKind::Artifact, "evidence"))],
            ..AuditSpec::default()
        };
        let mut mcp = McpSpec {
            server_name: "fixture".to_owned(),
            tool_refs: vec![Ref::Ref(card_ref(CardKind::Service, "tool"))],
            ..McpSpec::default()
        };
        let mut service = ServiceSpec {
            components: vec![ServiceComponent {
                alias: "model".to_owned(),
                card_ref: Ref::Ref(card_ref(CardKind::Model, "component")),
                verified_by: vec![binding("component-quality")],
                source: None,
                config: BTreeMap::new(),
                credential_refs: Vec::new(),
            }],
            ..ServiceSpec::default()
        };
        let mut trigger = TriggerSpec {
            description: None,
            activation: TriggerActivation::Schedule {
                cron: "0 * * * *".to_owned(),
                tz: None,
            },
        };
        let mut operator = notify_operator();
        let mut drift = drift();
        let mut eval = eval();
        let mut image = image;
        let mut text = text;
        let mut model = model();
        let mut agent = agent();

        let mut count = 0;
        for spec in [
            Spec::Data(image.clone()),
            Spec::Data(text.clone()),
            Spec::Model(model.clone()),
            Spec::Experiment(experiment.clone()),
            Spec::Agent(agent.clone()),
            Spec::Verifier(VerifierSpec {
                description: None,
                implementation: VerifierImplementation::Eval(eval.clone()),
            }),
            Spec::Verifier(VerifierSpec {
                description: None,
                implementation: VerifierImplementation::Drift(drift.clone()),
            }),
            Spec::Service(service.clone()),
            Spec::Mcp(mcp.clone()),
            Spec::Audit(audit.clone()),
            Spec::Artifact(artifact.clone()),
            Spec::Trigger(trigger.clone()),
            Spec::Operator(operator.clone()),
        ] {
            count += visit_paths(spec).len();
        }
        assert_eq!(count, 24);
        assert!(visit_paths(Spec::Service(service.clone())).contains(&(
            "spec.components[0].verified_by[0].verifier".to_owned(),
            "durable"
        )));
        assert!(
            visit_paths(Spec::Service(service.clone()))
                .contains(&("spec.components[0].ref".to_owned(), "durable"))
        );

        let _ = (
            &mut image,
            &mut text,
            &mut model,
            &mut experiment,
            &mut agent,
        );
        let _ = (&mut eval, &mut drift, &mut service, &mut mcp);
        let _ = (&mut audit, &mut artifact, &mut trigger, &mut operator);
    }

    /// Pin the exact path and slot shape of every reference the visitor yields,
    /// including Verifier implementation payloads and each `verified_by`
    /// binding's `verifier`, `runs_on`, and `on_failure` slots.
    #[test]
    fn visitor_covers_every_slot_in_the_migration_table() {
        let expected = vec![
            ("spec.card_refs[0]".to_owned(), "durable"),
            (
                "spec.splits[train].strategy.Materialized".to_owned(),
                "durable",
            ),
        ];
        let actual = visit_paths(Spec::Data(data(DataInterface::Pandas(PandasMeta {
            framework_version: "2".to_owned(),
            compression: ParquetCompression::Snappy,
        }))));
        assert_eq!(actual, expected);

        assert_eq!(
            visit_paths(Spec::Verifier(VerifierSpec {
                description: None,
                implementation: VerifierImplementation::Eval(eval()),
            })),
            vec![
                ("spec.implementation.spec.dataset".to_owned(), "durable"),
                (
                    "spec.implementation.spec.tasks[judge].LlmJudge.judge_ref".to_owned(),
                    "inlineable_agent"
                ),
                (
                    "spec.implementation.spec.tasks[judge].LlmJudge.judge_ref.prompt".to_owned(),
                    "inlineable_prompt"
                ),
            ]
        );
        assert_eq!(
            visit_paths(Spec::Verifier(VerifierSpec {
                description: None,
                implementation: VerifierImplementation::Drift(drift()),
            })),
            vec![(
                "spec.implementation.spec.signal.Distribution.baseline_ref".to_owned(),
                "durable"
            )]
        );

        let binding_slots = |prefix: &str| {
            vec![
                (format!("{prefix}[0].verifier"), "durable"),
                (format!("{prefix}[0].runs_on"), "inlineable_trigger"),
                (format!("{prefix}[0].on_failure[0]"), "inlineable_operator"),
                (format!("{prefix}[0].on_failure[1]"), "inlineable_operator"),
            ]
        };
        let service = ServiceSpec {
            components: vec![ServiceComponent {
                alias: "model".to_owned(),
                card_ref: Ref::Ref(card_ref(CardKind::Model, "component")),
                verified_by: vec![binding("component-quality")],
                source: None,
                config: BTreeMap::new(),
                credential_refs: Vec::new(),
            }],
            verified_by: vec![binding("service-quality")],
            ..ServiceSpec::default()
        };
        let mut expected = vec![("spec.components[0].ref".to_owned(), "durable")];
        expected.extend(binding_slots("spec.components[0].verified_by"));
        expected.extend(binding_slots("spec.verified_by"));
        assert_eq!(visit_paths(Spec::Service(service)), expected);

        let agent = AgentSpec {
            verified_by: vec![binding("agent-quality")],
            ..agent()
        };
        let mut expected = vec![("spec.prompt".to_owned(), "inlineable_prompt")];
        expected.extend(binding_slots("spec.verified_by"));
        assert_eq!(visit_paths(Spec::Agent(agent)), expected);
    }
}