cml-rs 0.4.0

Content Markup Language (CML) v0.2 parser, generator, validator, and embedding store for structured documents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
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
//! CML Profile System
//!
//! JSON-based profile definitions for validating CML documents.
//! Profiles define allowed elements, attributes, and type vocabularies.
//!
//! ## Directory Structure
//!
//! Each profile lives in its own directory with separate concerns:
//! ```text
//! schemas/0.2/profiles/
//! ├── core/
//! │   ├── core.json        # Element definitions
//! │   └── constraints.json # Validation rules
//! ├── standard/
//! │   ├── standard.json
//! │   ├── constraints.json
//! │   └── dictionary.json  # BytePunch compression
//! └── legal/
//!     ├── legal.json
//!     ├── constraints.json
//!     └── dictionary.json
//! ```
//!
//! ## Profile Hierarchy
//!
//! - **core**: Structural minimum (cml, header, body, footer, title)
//! - **standard**: All v0.2 elements (extends core)
//! - **legal**: Legal documents (extends standard with include whitelist)
//! - **code**: API documentation (extends standard)
//! - **bookstack**: Wiki-style documentation (extends standard)

use crate::{CmlError, Result};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::path::Path;

/// A CML profile definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Profile {
    /// Profile name (e.g., "core", "standard", "legal")
    pub name: String,

    /// Profile version
    pub version: String,

    /// Parent profile to inherit from
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extends: Option<String>,

    /// Human-readable description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Whitelist of elements to include from parent
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub include: Vec<String>,

    /// Blacklist of elements to exclude from parent
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub exclude: Vec<String>,

    /// Element definitions
    #[serde(default)]
    pub elements: HashMap<String, ElementDef>,

    /// Global attribute definitions
    #[serde(default)]
    pub attributes: HashMap<String, AttributeDef>,

    /// Type vocabularies (enums for type attributes)
    #[serde(default)]
    pub types: HashMap<String, Vec<String>>,
}

/// Element definition within a profile
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ElementDef {
    /// Human-readable description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Content model: "empty", "text", "inline", "block", "mixed"
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,

    /// Attribute definitions for this element
    #[serde(default)]
    pub attributes: HashMap<String, AttributeDef>,

    /// Allowed child elements
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub children: Vec<String>,

    /// Valid parent elements
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub parents: Vec<String>,

    /// Required child elements
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub required_children: Vec<String>,

    /// Minimum occurrences
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_occurs: Option<u32>,

    /// Maximum occurrences
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_occurs: Option<u32>,
}

/// Attribute definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AttributeDef {
    /// Human-readable description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Attribute type: "string", "integer", "boolean", "date", "uri", "enum"
    #[serde(rename = "type", default = "default_attr_type")]
    pub attr_type: String,

    /// Whether the attribute is required
    #[serde(default)]
    pub required: bool,

    /// Default value
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,

    /// Valid values if type is "enum"
    #[serde(rename = "enum", default, skip_serializing_if = "Vec::is_empty")]
    pub enum_values: Vec<String>,

    /// Regex pattern for validation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pattern: Option<String>,
}

fn default_attr_type() -> String {
    "string".to_string()
}

// =============================================================================
// Constraint Types
// =============================================================================

/// Profile constraints definition
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ProfileConstraints {
    /// Profile this constraint applies to
    #[serde(default)]
    pub profile: String,

    /// Constraint version
    #[serde(default)]
    pub version: String,

    /// Parent constraints to inherit from
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extends: Option<String>,

    /// Description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Document-level constraints
    #[serde(default)]
    pub document: Option<DocumentConstraint>,

    /// Element-specific constraints
    #[serde(default)]
    pub elements: HashMap<String, ElementConstraint>,

    /// Attribute validation rules
    #[serde(default)]
    pub attributes: HashMap<String, AttributeConstraint>,

    /// Parent-child relationship constraints
    #[serde(default)]
    pub hierarchy: HashMap<String, HierarchyConstraint>,

    /// Nesting constraints
    #[serde(default)]
    pub nesting: Option<NestingConstraint>,

    /// List-specific constraints
    #[serde(default)]
    pub list_constraints: Option<ListConstraints>,

    /// Semantic rules
    #[serde(default)]
    pub semantic_rules: HashMap<String, SemanticRule>,
}

/// Document-level constraints
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DocumentConstraint {
    /// Required attributes on root element
    #[serde(default)]
    pub required_attributes: Vec<String>,

    /// Required child elements
    #[serde(default)]
    pub required_children: Vec<String>,

    /// Required order of children
    #[serde(default)]
    pub child_order: Vec<String>,
}

/// Element-specific constraint
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ElementConstraint {
    /// Minimum occurrences
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_occurs: Option<u32>,

    /// Maximum occurrences
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_occurs: Option<u32>,

    /// Minimum number of children
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_children: Option<u32>,

    /// Maximum number of children
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_children: Option<u32>,

    /// Minimum content length
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_content: Option<u32>,

    /// Minimum text length
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_length: Option<u32>,

    /// Required attributes
    #[serde(default)]
    pub required_attributes: Vec<String>,

    /// Required children
    #[serde(default)]
    pub required_children: Vec<String>,

    /// Required child types
    #[serde(default)]
    pub required_child_types: Vec<String>,

    /// Preserve whitespace
    #[serde(default)]
    pub preserve_whitespace: bool,

    /// Disallow nesting
    #[serde(default)]
    pub no_nesting: bool,

    /// Allow self-nesting
    #[serde(default)]
    pub allow_nesting: bool,

    /// Reserved for future use
    #[serde(default)]
    pub reserved: bool,

    /// Warning message
    #[serde(skip_serializing_if = "Option::is_none")]
    pub warning: Option<String>,

    /// Size constraints
    #[serde(skip_serializing_if = "Option::is_none")]
    pub size: Option<SizeConstraint>,
}

/// Size constraint for heading levels etc.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SizeConstraint {
    pub min: Option<u32>,
    pub max: Option<u32>,
}

/// Attribute constraint
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AttributeConstraint {
    /// Description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Type (string, integer, boolean, etc.)
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub attr_type: Option<String>,

    /// Format (iso8601, uri, etc.)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub format: Option<String>,

    /// Regex pattern
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pattern: Option<String>,

    /// Enum values
    #[serde(rename = "enum", default)]
    pub enum_values: Vec<String>,

    /// Recommended values
    #[serde(default)]
    pub recommended: Vec<String>,

    /// Must be unique across document
    #[serde(default)]
    pub unique: bool,

    /// Minimum value
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min: Option<i32>,

    /// Maximum value
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max: Option<i32>,

    /// Default value
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default: Option<serde_json::Value>,
}

/// Hierarchy constraint
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct HierarchyConstraint {
    /// Allowed parent elements
    #[serde(default)]
    pub allowed_parents: Vec<String>,

    /// Allowed child elements
    #[serde(default)]
    pub allowed_children: Vec<String>,

    /// Maximum occurrences within parent
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_occurs: Option<u32>,

    /// Must be first child of parent
    #[serde(default)]
    pub must_be_first: bool,
}

/// Nesting constraints
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct NestingConstraint {
    /// Maximum section nesting depth
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_section_depth: Option<u32>,

    /// Maximum inline nesting depth
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_inline_depth: Option<u32>,

    /// Elements that cannot self-nest
    #[serde(default)]
    pub no_self_nesting: Vec<String>,
}

/// List-specific constraints
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ListConstraints {
    /// Ordered list constraints
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ordered: Option<OrderedListConstraint>,

    /// Unordered list constraints
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unordered: Option<UnorderedListConstraint>,
}

/// Ordered list constraint
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct OrderedListConstraint {
    /// Order enforcement: "alphanumeric", "numeric", "none"
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enforce_order: Option<String>,

    /// Description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// Unordered list constraint
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UnorderedListConstraint {
    /// Description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// Semantic rule
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SemanticRule {
    /// Description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Preferred element
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prefer: Option<String>,

    /// Element to avoid
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instead_of: Option<String>,
}

/// Resolved constraints with inheritance applied
#[derive(Debug, Clone, Default)]
pub struct ResolvedConstraints {
    /// Profile name
    pub profile: String,

    /// Document constraints
    pub document: Option<DocumentConstraint>,

    /// Element constraints
    pub elements: HashMap<String, ElementConstraint>,

    /// Attribute constraints
    pub attributes: HashMap<String, AttributeConstraint>,

    /// Hierarchy constraints
    pub hierarchy: HashMap<String, HierarchyConstraint>,

    /// Nesting constraints
    pub nesting: Option<NestingConstraint>,

    /// List constraints
    pub list_constraints: Option<ListConstraints>,

    /// Semantic rules
    pub semantic_rules: HashMap<String, SemanticRule>,
}

/// Resolved profile with inheritance applied
#[derive(Debug, Clone)]
pub struct ResolvedProfile {
    /// Profile name
    pub name: String,

    /// Profile version
    pub version: String,

    /// All allowed elements (after inheritance + include/exclude)
    pub elements: HashMap<String, ElementDef>,

    /// All type vocabularies (merged from inheritance chain)
    pub types: HashMap<String, Vec<String>>,
}

/// Profile registry for loading and resolving profiles
pub struct ProfileRegistry {
    /// Loaded profiles by name
    profiles: HashMap<String, Profile>,

    /// Resolved profiles (with inheritance applied)
    resolved: HashMap<String, ResolvedProfile>,
}

impl ProfileRegistry {
    /// Create a new empty registry
    pub fn new() -> Self {
        Self {
            profiles: HashMap::new(),
            resolved: HashMap::new(),
        }
    }

    /// Create a registry with built-in profiles
    pub fn with_builtins() -> Result<Self> {
        let mut registry = Self::new();
        registry.load_builtin_profiles()?;
        Ok(registry)
    }

    /// Load built-in profiles (core, standard, legal, legal:constitution, code, code:api, wiki)
    fn load_builtin_profiles(&mut self) -> Result<()> {
        // Core profile
        let core: Profile = serde_json::from_str(include_str!(
            "../schemas/0.2/profiles/core/core.json"
        ))
        .map_err(|e| CmlError::ValidationError(format!("Failed to parse core profile: {}", e)))?;
        self.profiles.insert("core".to_string(), core);

        // Standard profile
        let standard: Profile = serde_json::from_str(include_str!(
            "../schemas/0.2/profiles/standard/standard.json"
        ))
        .map_err(|e| {
            CmlError::ValidationError(format!("Failed to parse standard profile: {}", e))
        })?;
        self.profiles.insert("standard".to_string(), standard);

        // Legal profile (base)
        let legal: Profile =
            serde_json::from_str(include_str!("../schemas/0.2/profiles/legal/legal.json"))
                .map_err(|e| {
                    CmlError::ValidationError(format!("Failed to parse legal profile: {}", e))
                })?;
        self.profiles.insert("legal".to_string(), legal);

        // Legal:constitution sub-profile
        let legal_constitution: Profile = serde_json::from_str(include_str!(
            "../schemas/0.2/profiles/legal/constitution/constitution.json"
        ))
        .map_err(|e| {
            CmlError::ValidationError(format!("Failed to parse legal:constitution profile: {}", e))
        })?;
        self.profiles
            .insert("legal:constitution".to_string(), legal_constitution);

        // Code profile (base)
        let code: Profile = serde_json::from_str(include_str!(
            "../schemas/0.2/profiles/code/code.json"
        ))
        .map_err(|e| CmlError::ValidationError(format!("Failed to parse code profile: {}", e)))?;
        self.profiles.insert("code".to_string(), code);

        // Code:api sub-profile
        let code_api: Profile =
            serde_json::from_str(include_str!("../schemas/0.2/profiles/code/api/api.json"))
                .map_err(|e| {
                    CmlError::ValidationError(format!("Failed to parse code:api profile: {}", e))
                })?;
        self.profiles.insert("code:api".to_string(), code_api);

        // Wiki profile
        let wiki: Profile = serde_json::from_str(include_str!(
            "../schemas/0.2/profiles/wiki/wiki.json"
        ))
        .map_err(|e| CmlError::ValidationError(format!("Failed to parse wiki profile: {}", e)))?;
        self.profiles.insert("wiki".to_string(), wiki);

        Ok(())
    }

    /// Load a profile from a JSON file
    pub fn load_from_file<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
        let content = std::fs::read_to_string(path.as_ref())?;
        let profile: Profile = serde_json::from_str(&content)
            .map_err(|e| CmlError::ValidationError(format!("Failed to parse profile: {}", e)))?;
        self.profiles.insert(profile.name.clone(), profile);
        Ok(())
    }

    /// Load a profile from a JSON string
    pub fn load_from_str(&mut self, json: &str) -> Result<()> {
        let profile: Profile = serde_json::from_str(json)
            .map_err(|e| CmlError::ValidationError(format!("Failed to parse profile: {}", e)))?;
        self.profiles.insert(profile.name.clone(), profile);
        Ok(())
    }

    /// Get a resolved profile by name
    pub fn get(&mut self, name: &str) -> Result<&ResolvedProfile> {
        // Check if already resolved
        if self.resolved.contains_key(name) {
            return Ok(self.resolved.get(name).unwrap());
        }

        // Resolve the profile
        let resolved = self.resolve_profile(name)?;
        self.resolved.insert(name.to_string(), resolved);
        Ok(self.resolved.get(name).unwrap())
    }

    /// Resolve a profile with inheritance
    fn resolve_profile(&self, name: &str) -> Result<ResolvedProfile> {
        let profile = self
            .profiles
            .get(name)
            .ok_or_else(|| CmlError::ValidationError(format!("Profile not found: {}", name)))?;

        // Start with parent profile if exists
        let mut elements: HashMap<String, ElementDef> = HashMap::new();
        let mut types: HashMap<String, Vec<String>> = HashMap::new();

        if let Some(parent_name) = &profile.extends {
            let parent = self.resolve_profile(parent_name)?;

            // Apply include/exclude filtering
            if !profile.include.is_empty() {
                // Whitelist mode: only include specified elements
                let include_set: HashSet<&str> =
                    profile.include.iter().map(|s| s.as_str()).collect();
                for (name, def) in parent.elements {
                    if include_set.contains(name.as_str()) {
                        elements.insert(name, def);
                    }
                }
            } else if !profile.exclude.is_empty() {
                // Blacklist mode: exclude specified elements
                let exclude_set: HashSet<&str> =
                    profile.exclude.iter().map(|s| s.as_str()).collect();
                for (name, def) in parent.elements {
                    if !exclude_set.contains(name.as_str()) {
                        elements.insert(name, def);
                    }
                }
            } else {
                // No filtering: inherit all
                elements = parent.elements;
            }

            // Inherit types
            types = parent.types;
        }

        // Add/override with this profile's elements
        for (name, def) in &profile.elements {
            elements.insert(name.clone(), def.clone());
        }

        // Merge types (profile types override parent)
        for (name, values) in &profile.types {
            types.insert(name.clone(), values.clone());
        }

        Ok(ResolvedProfile {
            name: profile.name.clone(),
            version: profile.version.clone(),
            elements,
            types,
        })
    }

    /// Check if an element is allowed in a profile
    pub fn is_element_allowed(&mut self, profile: &str, element: &str) -> Result<bool> {
        let resolved = self.get(profile)?;
        Ok(resolved.elements.contains_key(element))
    }

    /// Get valid type values for an element
    pub fn get_type_values(
        &mut self,
        profile: &str,
        type_name: &str,
    ) -> Result<Option<Vec<String>>> {
        let resolved = self.get(profile)?;
        Ok(resolved.types.get(type_name).cloned())
    }

    /// Validate a type value against the profile
    pub fn validate_type_value(
        &mut self,
        profile: &str,
        type_name: &str,
        value: &str,
    ) -> Result<bool> {
        let resolved = self.get(profile)?;
        match resolved.types.get(type_name) {
            Some(values) => Ok(values.contains(&value.to_string())),
            None => Ok(true), // No restriction if type not defined
        }
    }
}

impl Default for ProfileRegistry {
    fn default() -> Self {
        Self::new()
    }
}

// =============================================================================
// Constraint Registry
// =============================================================================

/// Constraint registry for loading and resolving profile constraints
pub struct ConstraintRegistry {
    /// Loaded constraints by profile name
    constraints: HashMap<String, ProfileConstraints>,

    /// Resolved constraints (with inheritance applied)
    resolved: HashMap<String, ResolvedConstraints>,
}

impl ConstraintRegistry {
    /// Create a new empty registry
    pub fn new() -> Self {
        Self {
            constraints: HashMap::new(),
            resolved: HashMap::new(),
        }
    }

    /// Create a registry with built-in constraints
    pub fn with_builtins() -> Result<Self> {
        let mut registry = Self::new();
        registry.load_builtin_constraints()?;
        Ok(registry)
    }

    /// Load built-in constraints
    fn load_builtin_constraints(&mut self) -> Result<()> {
        // Core constraints
        let core: ProfileConstraints = serde_json::from_str(include_str!(
            "../schemas/0.2/profiles/core/constraints.json"
        ))
        .map_err(|e| {
            CmlError::ValidationError(format!("Failed to parse core constraints: {}", e))
        })?;
        self.constraints.insert("core".to_string(), core);

        // Standard constraints
        let standard: ProfileConstraints = serde_json::from_str(include_str!(
            "../schemas/0.2/profiles/standard/constraints.json"
        ))
        .map_err(|e| {
            CmlError::ValidationError(format!("Failed to parse standard constraints: {}", e))
        })?;
        self.constraints.insert("standard".to_string(), standard);

        // Legal constraints
        let legal: ProfileConstraints = serde_json::from_str(include_str!(
            "../schemas/0.2/profiles/legal/constraints.json"
        ))
        .map_err(|e| {
            CmlError::ValidationError(format!("Failed to parse legal constraints: {}", e))
        })?;
        self.constraints.insert("legal".to_string(), legal);

        // Code constraints
        let code: ProfileConstraints = serde_json::from_str(include_str!(
            "../schemas/0.2/profiles/code/constraints.json"
        ))
        .map_err(|e| {
            CmlError::ValidationError(format!("Failed to parse code constraints: {}", e))
        })?;
        self.constraints.insert("code".to_string(), code);

        // Wiki constraints
        let wiki: ProfileConstraints = serde_json::from_str(include_str!(
            "../schemas/0.2/profiles/wiki/constraints.json"
        ))
        .map_err(|e| {
            CmlError::ValidationError(format!("Failed to parse wiki constraints: {}", e))
        })?;
        self.constraints.insert("wiki".to_string(), wiki);

        Ok(())
    }

    /// Load constraints from a JSON string
    pub fn load_from_str(&mut self, json: &str) -> Result<()> {
        let constraints: ProfileConstraints = serde_json::from_str(json).map_err(|e| {
            CmlError::ValidationError(format!("Failed to parse constraints: {}", e))
        })?;
        self.constraints
            .insert(constraints.profile.clone(), constraints);
        Ok(())
    }

    /// Get resolved constraints by profile name
    pub fn get(&mut self, name: &str) -> Result<&ResolvedConstraints> {
        if self.resolved.contains_key(name) {
            return Ok(self.resolved.get(name).unwrap());
        }

        let resolved = self.resolve_constraints(name)?;
        self.resolved.insert(name.to_string(), resolved);
        Ok(self.resolved.get(name).unwrap())
    }

    /// Resolve constraints with inheritance
    fn resolve_constraints(&self, name: &str) -> Result<ResolvedConstraints> {
        let constraints = self
            .constraints
            .get(name)
            .ok_or_else(|| CmlError::ValidationError(format!("Constraints not found: {}", name)))?;

        let mut resolved = ResolvedConstraints {
            profile: name.to_string(),
            ..Default::default()
        };

        // Inherit from parent if exists
        if let Some(parent_name) = &constraints.extends {
            let parent = self.resolve_constraints(parent_name)?;
            resolved.document = parent.document;
            resolved.elements = parent.elements;
            resolved.attributes = parent.attributes;
            resolved.hierarchy = parent.hierarchy;
            resolved.nesting = parent.nesting;
            resolved.list_constraints = parent.list_constraints;
            resolved.semantic_rules = parent.semantic_rules;
        }

        // Override with this profile's constraints
        if constraints.document.is_some() {
            resolved.document = constraints.document.clone();
        }

        for (name, constraint) in &constraints.elements {
            resolved.elements.insert(name.clone(), constraint.clone());
        }

        for (name, constraint) in &constraints.attributes {
            resolved.attributes.insert(name.clone(), constraint.clone());
        }

        for (name, constraint) in &constraints.hierarchy {
            resolved.hierarchy.insert(name.clone(), constraint.clone());
        }

        if constraints.nesting.is_some() {
            resolved.nesting = constraints.nesting.clone();
        }

        if constraints.list_constraints.is_some() {
            resolved.list_constraints = constraints.list_constraints.clone();
        }

        for (name, rule) in &constraints.semantic_rules {
            resolved.semantic_rules.insert(name.clone(), rule.clone());
        }

        Ok(resolved)
    }
}

impl Default for ConstraintRegistry {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_load_core_profile() {
        let json = r#"{
            "name": "test-core",
            "version": "0.2",
            "elements": {
                "cml": { "content": "block" },
                "header": { "content": "block" },
                "body": { "content": "block" },
                "footer": { "content": "block" }
            }
        }"#;

        let profile: Profile = serde_json::from_str(json).unwrap();
        assert_eq!(profile.name, "test-core");
        assert_eq!(profile.elements.len(), 4);
    }

    #[test]
    fn test_profile_inheritance() {
        let mut registry = ProfileRegistry::new();

        // Load parent
        registry
            .load_from_str(
                r#"{
                "name": "parent",
                "version": "0.2",
                "elements": {
                    "a": { "content": "text" },
                    "b": { "content": "text" },
                    "c": { "content": "text" }
                }
            }"#,
            )
            .unwrap();

        // Load child with include whitelist
        registry
            .load_from_str(
                r#"{
                "name": "child",
                "version": "0.2",
                "extends": "parent",
                "include": ["a", "b"],
                "elements": {
                    "d": { "content": "text" }
                }
            }"#,
            )
            .unwrap();

        let resolved = registry.get("child").unwrap();
        assert!(resolved.elements.contains_key("a"));
        assert!(resolved.elements.contains_key("b"));
        assert!(!resolved.elements.contains_key("c")); // Excluded by whitelist
        assert!(resolved.elements.contains_key("d")); // Added by child
    }

    #[test]
    fn test_type_vocabularies() {
        let mut registry = ProfileRegistry::new();

        registry
            .load_from_str(
                r#"{
                "name": "typed",
                "version": "0.2",
                "types": {
                    "date": ["created", "updated", "published"],
                    "section": ["intro", "body", "conclusion"]
                }
            }"#,
            )
            .unwrap();

        assert!(registry
            .validate_type_value("typed", "date", "created")
            .unwrap());
        assert!(registry
            .validate_type_value("typed", "date", "published")
            .unwrap());
        assert!(!registry
            .validate_type_value("typed", "date", "invalid")
            .unwrap());
    }
}