workshop-rs-cli 0.9.0

Standalone CLI for the canonical Workshop core: parse, emit, convert, locales, and catalog identity.
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
//! Public contracts for Workshop test results.

use serde::{Deserialize, Serialize};
use std::collections::HashSet;

use workshop_rs::catalog::{Catalog, CatalogIdentity, Kind, Locale};

pub const CONFORMANCE_SCHEMA_VERSION: u32 = 2;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum FeatureNamespace {
    Catalog,
    Wir,
    Settings,
    Localization,
}

impl FeatureNamespace {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Catalog => "catalog",
            Self::Wir => "wir",
            Self::Settings => "settings",
            Self::Localization => "localization",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum FeatureKind {
    Event,
    Action,
    Value,
    Operator,
    Enum,
    EnumMember,
    Setting,
    Variable,
    Subroutine,
    ControlFlow,
    String,
    Localization,
    ContentId,
    Structural,
}

impl FeatureKind {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Event => "event",
            Self::Action => "action",
            Self::Value => "value",
            Self::Operator => "operator",
            Self::Enum => "enum",
            Self::EnumMember => "enum-member",
            Self::Setting => "setting",
            Self::Variable => "variable",
            Self::Subroutine => "subroutine",
            Self::ControlFlow => "control-flow",
            Self::String => "string",
            Self::Localization => "localization",
            Self::ContentId => "content-id",
            Self::Structural => "structural",
        }
    }
}

impl From<Kind> for FeatureKind {
    fn from(kind: Kind) -> Self {
        match kind {
            Kind::Structural => Self::Structural,
            Kind::Action => Self::Action,
            Kind::Value => Self::Value,
            Kind::Event => Self::Event,
            Kind::Operator => Self::Operator,
            Kind::Enum => Self::Enum,
            Kind::Setting => Self::Setting,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub struct FeatureId {
    pub namespace: FeatureNamespace,
    pub kind: FeatureKind,
    pub name: String,
}

impl FeatureId {
    pub fn new(
        namespace: FeatureNamespace,
        kind: FeatureKind,
        name: impl Into<String>,
    ) -> Result<Self, ConformanceError> {
        let name = name.into();
        if name.is_empty() {
            return Err(ConformanceError::invalid(
                "feature.name",
                "must not be empty",
            ));
        }
        if name
            .chars()
            .any(|character| character.is_whitespace() || character.is_control())
        {
            return Err(ConformanceError::invalid(
                "feature.name",
                "must not contain whitespace or control characters",
            ));
        }
        Ok(Self {
            namespace,
            kind,
            name,
        })
    }

    pub fn from_catalog(kind: Kind, id: impl Into<String>) -> Result<Self, ConformanceError> {
        Self::new(FeatureNamespace::Catalog, kind.into(), id)
    }

    pub fn from_enum_member(
        domain: impl Into<String>,
        member: impl Into<String>,
    ) -> Result<Self, ConformanceError> {
        let domain = domain.into();
        let member = member.into();
        if domain.is_empty() || member.is_empty() {
            return Err(ConformanceError::invalid(
                "feature.name",
                "enum member identities require a domain and member",
            ));
        }
        Self::new(
            FeatureNamespace::Catalog,
            FeatureKind::EnumMember,
            format!("{domain}/{member}"),
        )
    }

    pub fn owned(
        namespace: FeatureNamespace,
        kind: FeatureKind,
        name: impl Into<String>,
    ) -> Result<Self, ConformanceError> {
        Self::new(namespace, kind, name)
    }
}

/// An immutable identity for a test input, expected result, or observed result.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct TestArtifact {
    pub name: String,
    pub revision: Option<String>,
    pub path: Option<String>,
    #[serde(rename = "sha256")]
    pub sha256: Option<String>,
    pub license: Option<String>,
}

impl TestArtifact {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            revision: None,
            path: None,
            sha256: None,
            license: None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Equivalence {
    Semantic,
    Normalized,
    ExactText,
    NotComparable,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Comparison {
    pub mode: Equivalence,
    pub expected: Option<TestArtifact>,
    pub observed: Option<TestArtifact>,
    pub normalizer: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ReasonCode {
    Unsupported,
    KnownGap,
    UnexpectedRegression,
    Inconclusive,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ConformanceReason {
    pub code: ReasonCode,
    pub detail: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ConformanceStatus {
    Matched,
    Unsupported,
    KnownGap,
    UnexpectedRegression,
    Inconclusive,
}

impl ConformanceStatus {
    pub const fn is_match(self) -> bool {
        matches!(self, Self::Matched)
    }
}

/// One machine-readable result from a Workshop test or reference comparison.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ConformanceResult {
    pub schema_version: u32,
    pub case_id: String,
    pub features: Vec<FeatureId>,
    pub status: ConformanceStatus,
    pub comparison: Comparison,
    pub source: TestArtifact,
    pub catalog: CatalogIdentity,
    pub locale: Option<Locale>,
    pub reason: Option<ConformanceReason>,
}

impl ConformanceResult {
    pub fn validate(&self) -> Result<(), ConformanceError> {
        if self.schema_version != CONFORMANCE_SCHEMA_VERSION {
            return Err(ConformanceError::invalid(
                "schemaVersion",
                format!(
                    "unsupported schema version {}; expected {}",
                    self.schema_version, CONFORMANCE_SCHEMA_VERSION
                ),
            ));
        }
        validate_non_empty("caseId", &self.case_id)?;
        let mut seen_features: HashSet<&FeatureId> = HashSet::with_capacity(self.features.len());
        if self.features.is_empty() {
            return Err(ConformanceError::invalid(
                "features",
                "must contain at least one feature",
            ));
        }
        for (index, feature) in self.features.iter().enumerate() {
            FeatureId::new(feature.namespace, feature.kind, feature.name.clone())
                .map_err(|error| error.at(format!("features[{index}]")))?;
            if !seen_features.insert(feature) {
                return Err(ConformanceError::invalid(
                    format!("features[{index}]"),
                    "must not contain duplicate feature identities",
                ));
            }
        }
        validate_artifact("source", &self.source, false, false)?;
        validate_catalog_identity(&self.catalog)?;
        validate_comparison(&self.comparison, &self.source)?;
        if self.status.is_match() {
            if self.comparison.mode == Equivalence::NotComparable {
                return Err(ConformanceError::invalid(
                    "comparison.mode",
                    "matched results must declare semantic, normalized, or exact-text equivalence",
                ));
            }
            if self.comparison.expected.is_none() || self.comparison.observed.is_none() {
                return Err(ConformanceError::invalid(
                    "comparison",
                    "matched results require expected and observed artifacts",
                ));
            }
            if self.reason.is_some() {
                return Err(ConformanceError::invalid(
                    "reason",
                    "matched results must not carry a reason",
                ));
            }
        } else {
            let reason = self.reason.as_ref().ok_or_else(|| {
                ConformanceError::invalid(
                    "reason",
                    "non-matching results require a structured reason",
                )
            })?;
            validate_reason(self.status, reason)?;
            if self.status == ConformanceStatus::UnexpectedRegression
                && self.comparison.mode == Equivalence::NotComparable
            {
                return Err(ConformanceError::invalid(
                    "comparison.mode",
                    "an unexpected regression must identify the comparison contract",
                ));
            }
        }
        Ok(())
    }

    pub fn validate_against(&self, catalog: &Catalog) -> Result<(), ConformanceError> {
        self.validate()?;
        if self.catalog != catalog.identity() {
            return Err(ConformanceError::invalid(
                "catalog",
                "must match the catalog supplied to validate_against",
            ));
        }
        for (index, feature) in self.features.iter().enumerate() {
            if feature.namespace != FeatureNamespace::Catalog {
                continue;
            }
            match feature.kind {
                FeatureKind::Enum => {
                    if catalog.enum_domain(&feature.name).is_none() {
                        return Err(ConformanceError::invalid(
                            format!("features[{index}]"),
                            format!("unknown canonical enum domain '{}'", feature.name),
                        ));
                    }
                }
                FeatureKind::EnumMember => {
                    let (domain, member) = feature.name.split_once('/').ok_or_else(|| {
                        ConformanceError::invalid(
                            format!("features[{index}]"),
                            "enum-member identity must contain domain/member",
                        )
                    })?;
                    let known = catalog.enum_domain(domain).is_some_and(|candidate| {
                        candidate.members.iter().any(|item| item.member == member)
                    });
                    if !known {
                        return Err(ConformanceError::invalid(
                            format!("features[{index}]"),
                            format!("unknown canonical enum member '{domain}/{member}'"),
                        ));
                    }
                }
                kind => {
                    let catalog_kind = match kind {
                        FeatureKind::Event => Kind::Event,
                        FeatureKind::Action => Kind::Action,
                        FeatureKind::Value => Kind::Value,
                        FeatureKind::Operator => Kind::Operator,
                        FeatureKind::Setting => Kind::Setting,
                        FeatureKind::Structural => Kind::Structural,
                        _ => {
                            return Err(ConformanceError::invalid(
                                format!("features[{index}]"),
                                "this feature kind cannot use the catalog namespace",
                            ));
                        }
                    };
                    if catalog.entry(catalog_kind, &feature.name).is_none() {
                        return Err(ConformanceError::invalid(
                            format!("features[{index}]"),
                            format!(
                                "unknown canonical {} '{}'",
                                catalog_kind.as_str(),
                                feature.name
                            ),
                        ));
                    }
                }
            }
        }
        Ok(())
    }

    pub fn from_json(json: &str) -> Result<Self, ConformanceDecodeError> {
        let result: Self = serde_json::from_str(json).map_err(ConformanceDecodeError::Json)?;
        result.validate().map_err(ConformanceDecodeError::Invalid)?;
        Ok(result)
    }

    pub const fn is_match(&self) -> bool {
        self.status.is_match()
    }
}

fn validate_catalog_identity(catalog: &CatalogIdentity) -> Result<(), ConformanceError> {
    validate_non_empty(
        "catalog.implementationVersion",
        &catalog.implementation_version,
    )?;
    validate_non_empty("catalog.catalogVersion", &catalog.catalog_version)?;
    if catalog.catalog_digest.as_deref().is_none_or(str::is_empty) {
        return Err(ConformanceError::invalid(
            "catalog.catalogDigest",
            "must contain a catalog digest",
        ));
    }
    Ok(())
}

fn validate_artifact(
    field: &str,
    artifact: &TestArtifact,
    require_revision: bool,
    require_digest: bool,
) -> Result<(), ConformanceError> {
    validate_non_empty(&format!("{field}.name"), &artifact.name)?;
    if require_revision && artifact.revision.as_deref().is_none_or(str::is_empty) {
        return Err(ConformanceError::invalid(
            format!("{field}.revision"),
            "must identify an immutable revision",
        ));
    }
    if let Some(digest) = &artifact.sha256 {
        if digest.len() != 64 || !digest.bytes().all(|byte| byte.is_ascii_hexdigit()) {
            return Err(ConformanceError::invalid(
                format!("{field}.sha256"),
                "must be a 64-character hexadecimal SHA-256 digest",
            ));
        }
    }
    if require_digest && artifact.sha256.is_none() {
        return Err(ConformanceError::invalid(
            format!("{field}.sha256"),
            "must contain a SHA-256 digest",
        ));
    }
    Ok(())
}

fn validate_comparison(
    comparison: &Comparison,
    source: &TestArtifact,
) -> Result<(), ConformanceError> {
    if comparison.mode == Equivalence::Normalized
        && comparison
            .normalizer
            .as_deref()
            .is_none_or(|normalizer| normalizer.trim().is_empty())
    {
        return Err(ConformanceError::invalid(
            "comparison.normalizer",
            "normalized comparisons require a named normalizer",
        ));
    }
    if let Some(expected) = &comparison.expected {
        validate_artifact("comparison.expected", expected, false, false)?;
        if expected == source {
            return Err(ConformanceError::invalid(
                "comparison.expected",
                "expected artifact must not be the test input",
            ));
        }
    }
    if let Some(observed) = &comparison.observed {
        validate_artifact("comparison.observed", observed, false, false)?;
        if observed == source {
            return Err(ConformanceError::invalid(
                "comparison.observed",
                "observed artifact must not be the test input",
            ));
        }
    }
    if comparison.expected.is_some() && comparison.expected == comparison.observed {
        return Err(ConformanceError::invalid(
            "comparison",
            "expected and observed artifacts must be distinct",
        ));
    }
    Ok(())
}

fn validate_reason(
    status: ConformanceStatus,
    reason: &ConformanceReason,
) -> Result<(), ConformanceError> {
    validate_non_empty("reason.detail", &reason.detail)?;
    let expected = match status {
        ConformanceStatus::Unsupported => ReasonCode::Unsupported,
        ConformanceStatus::KnownGap => ReasonCode::KnownGap,
        ConformanceStatus::UnexpectedRegression => ReasonCode::UnexpectedRegression,
        ConformanceStatus::Inconclusive => ReasonCode::Inconclusive,
        ConformanceStatus::Matched => {
            return Err(ConformanceError::invalid(
                "reason",
                "matched results must not carry a reason",
            ));
        }
    };
    if reason.code != expected {
        return Err(ConformanceError::invalid(
            "reason.code",
            "reason code must match conformance status",
        ));
    }
    Ok(())
}

fn validate_non_empty(field: &str, value: &str) -> Result<(), ConformanceError> {
    if value.trim().is_empty() {
        Err(ConformanceError::invalid(field, "must not be empty"))
    } else {
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConformanceError {
    pub field: String,
    pub message: String,
}

impl ConformanceError {
    fn invalid(field: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            field: field.into(),
            message: message.into(),
        }
    }

    fn at(self, field: String) -> Self {
        Self { field, ..self }
    }
}

impl std::fmt::Display for ConformanceError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            formatter,
            "invalid conformance {}: {}",
            self.field, self.message
        )
    }
}

impl std::error::Error for ConformanceError {}

#[derive(Debug)]
pub enum ConformanceDecodeError {
    Json(serde_json::Error),
    Invalid(ConformanceError),
}

impl std::fmt::Display for ConformanceDecodeError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Json(error) => write!(formatter, "invalid conformance JSON: {error}"),
            Self::Invalid(error) => error.fmt(formatter),
        }
    }
}

impl std::error::Error for ConformanceDecodeError {}

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

    fn catalog() -> CatalogIdentity {
        Catalog::builtin().expect("built-in catalog").identity()
    }

    fn source() -> TestArtifact {
        TestArtifact {
            name: "fixture".to_string(),
            revision: Some("abc123".to_string()),
            path: Some("cases/basic.ws".to_string()),
            sha256: Some("a".repeat(64)),
            license: Some("MIT".to_string()),
        }
    }

    fn artifact(name: &str) -> TestArtifact {
        TestArtifact {
            name: name.to_string(),
            sha256: Some("b".repeat(64)),
            ..TestArtifact::new(name)
        }
    }

    fn matched() -> ConformanceResult {
        ConformanceResult {
            schema_version: CONFORMANCE_SCHEMA_VERSION,
            case_id: "basic-action".to_string(),
            features: vec![
                FeatureId::from_catalog(Kind::Action, "setHealth").expect("valid feature"),
            ],
            status: ConformanceStatus::Matched,
            comparison: Comparison {
                mode: Equivalence::Semantic,
                expected: Some(artifact("expected")),
                observed: Some(artifact("observed")),
                normalizer: None,
            },
            source: source(),
            catalog: catalog(),
            locale: Some(Locale::new("en-US")),
            reason: None,
        }
    }

    #[test]
    fn feature_ids_are_locale_and_provider_independent() {
        let feature = FeatureId::from_catalog(Kind::Action, "setHealth").expect("valid feature");
        assert_eq!(feature.kind, FeatureKind::Action);
        assert_eq!(feature.name, "setHealth");
        assert_eq!(
            serde_json::to_string(&feature).unwrap(),
            r#"{"namespace":"catalog","kind":"action","name":"setHealth"}"#
        );
        let member = FeatureId::from_enum_member("Hero", "ANA").expect("valid member");
        assert_eq!(member.name, "Hero/ANA");
    }

    #[test]
    fn result_serializes_as_test_data_without_evidence_taxonomy() {
        let result = matched();
        result.validate().expect("valid result");
        result
            .validate_against(&Catalog::builtin().expect("built-in catalog"))
            .expect("catalog-backed feature exists");
        let json = serde_json::to_string(&result).expect("serialize result");
        let document: serde_json::Value = serde_json::from_str(&json).expect("valid result JSON");
        assert!(document.get("evidence").is_none());
        assert!(document.get("trackingRef").is_none());
        let decoded = ConformanceResult::from_json(&json).expect("deserialize valid result");
        assert_eq!(decoded, result);
    }

    #[test]
    fn catalog_validation_rejects_fabricated_features_and_catalogs() {
        let mut result = matched();
        result.features = vec![
            FeatureId::from_catalog(Kind::Action, "notAWorkshopAction")
                .expect("syntactically valid feature"),
        ];
        assert!(
            result
                .validate_against(&Catalog::builtin().expect("built-in catalog"))
                .is_err()
        );

        let mut result = matched();
        result.catalog.catalog_digest = Some("f".repeat(64));
        let error = result
            .validate_against(&Catalog::builtin().expect("built-in catalog"))
            .expect_err("result must be bound to the supplied catalog");
        assert_eq!(error.field, "catalog");
    }

    #[test]
    fn non_matching_results_need_the_matching_reason() {
        let mut result = matched();
        result.status = ConformanceStatus::KnownGap;
        result.comparison.mode = Equivalence::NotComparable;
        assert!(result.validate().is_err());
        result.reason = Some(ConformanceReason {
            code: ReasonCode::KnownGap,
            detail: "client spelling is not available".to_string(),
        });
        result.validate().expect("documented gap");
        assert!(!result.is_match());
    }

    #[test]
    fn duplicate_features_blank_details_and_aliasing_are_invalid() {
        let mut result = matched();
        result.features.push(result.features[0].clone());
        assert!(result.validate().is_err());

        let mut result = matched();
        result.status = ConformanceStatus::Inconclusive;
        result.reason = Some(ConformanceReason {
            code: ReasonCode::Inconclusive,
            detail: "  \n".to_string(),
        });
        assert!(result.validate().is_err());

        let mut result = matched();
        result.comparison.observed = Some(result.source.clone());
        assert!(result.validate().is_err());
    }
}