vellaveto-types 6.1.1

Core type definitions for Vellaveto policy engine
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
// Copyright 2026 Paolo Vella
// SPDX-License-Identifier: MPL-2.0

//! Policy lifecycle management types.
//!
//! Provides versioned policy lifecycle with status transitions:
//! `Draft → Staging → Active → Archived`
//!
//! Used by Phase 47 for policy approval workflows, staging shadow evaluation,
//! structural diffs, and rollback.

use serde::{Deserialize, Serialize};

use crate::has_dangerous_chars;

// ─── Constants ───────────────────────────────────────────────────────────────

/// Maximum number of versions stored per policy.
pub const MAX_VERSIONS_PER_POLICY: usize = 100;

/// Maximum total versions across all policies.
pub const MAX_TOTAL_VERSIONS: usize = 10_000;

/// Maximum number of required approvers for a version promotion.
pub const MAX_REQUIRED_APPROVERS: usize = 20;

/// Maximum length of a version comment.
pub const MAX_VERSION_COMMENT_LEN: usize = 4_096;

/// Maximum length of lifecycle identity strings (created_by, approved_by).
pub const MAX_LIFECYCLE_IDENTITY_LEN: usize = 256;

/// Maximum number of approvals per version.
pub const MAX_APPROVALS_PER_VERSION: usize = 50;

/// Maximum number of staging report divergence entries.
pub const MAX_STAGING_REPORT_ENTRIES: usize = 10_000;

/// Maximum number of diff changes.
pub const MAX_DIFF_CHANGES: usize = 100;

/// Maximum length for tool/function name strings in staging comparison entries.
/// Matches MAX_NAME_LEN (256) used in core.rs for Action tool/function validation.
pub const MAX_STAGING_NAME_LEN: usize = 256;

/// Maximum length for verdict strings in staging comparison entries.
pub const MAX_VERDICT_STRING_LEN: usize = 128;

/// Maximum length for individual diff change description strings.
pub const MAX_DIFF_CHANGE_LEN: usize = 4_096;

/// Maximum length for policy_id in PolicyVersionDiff.
pub const MAX_DIFF_POLICY_ID_LEN: usize = 256;

// ─── Types ───────────────────────────────────────────────────────────────────

/// Status of a policy version in its lifecycle.
///
/// Transitions: Draft → Staging → Active → Archived
/// - `Draft`: Initial state, can be edited and approved
/// - `Staging`: Shadow evaluation mode, no enforcement impact
/// - `Active`: Live enforcement, only one active version per policy
/// - `Archived`: Historical record, immutable
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum PolicyVersionStatus {
    Draft,
    Staging,
    Active,
    Archived,
}

impl std::fmt::Display for PolicyVersionStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Draft => write!(f, "draft"),
            Self::Staging => write!(f, "staging"),
            Self::Active => write!(f, "active"),
            Self::Archived => write!(f, "archived"),
        }
    }
}

/// An approval record for a policy version.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PolicyApproval {
    /// Identity of the approver.
    pub approved_by: String,
    /// ISO 8601 timestamp of when the approval was recorded.
    pub approved_at: String,
    /// Optional comment from the approver.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub comment: Option<String>,
}

impl PolicyApproval {
    /// Validate approval fields.
    pub fn validate(&self) -> Result<(), String> {
        if self.approved_by.is_empty() || self.approved_by.trim().is_empty() {
            return Err("approved_by must be non-empty".to_string());
        }
        if self.approved_by.len() > MAX_LIFECYCLE_IDENTITY_LEN {
            return Err(format!(
                "approved_by exceeds {MAX_LIFECYCLE_IDENTITY_LEN} chars"
            ));
        }
        if has_dangerous_chars(&self.approved_by) {
            return Err("approved_by contains invalid characters".to_string());
        }
        if self.approved_at.is_empty() {
            return Err("approved_at must be non-empty".to_string());
        }
        if has_dangerous_chars(&self.approved_at) {
            return Err("approved_at contains invalid characters".to_string());
        }
        // Validate timestamp format
        crate::time_util::parse_iso8601_secs(&self.approved_at)
            .map_err(|e| format!("approved_at: {e}"))?;
        if let Some(ref c) = self.comment {
            if c.len() > MAX_VERSION_COMMENT_LEN {
                return Err(format!(
                    "approval comment exceeds {MAX_VERSION_COMMENT_LEN} chars"
                ));
            }
            if has_dangerous_chars(c) {
                return Err("approval comment contains invalid characters".to_string());
            }
        }
        Ok(())
    }
}

/// A versioned policy record with lifecycle status and approval tracking.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PolicyVersion {
    /// Unique identifier for this version (e.g., UUID).
    pub version_id: String,
    /// Policy ID this version belongs to.
    pub policy_id: String,
    /// Monotonically increasing version number within this policy.
    pub version: u64,
    /// The full policy definition at this version.
    pub policy: crate::Policy,
    /// Identity of the user who created this version.
    pub created_by: String,
    /// ISO 8601 timestamp of creation.
    pub created_at: String,
    /// Current lifecycle status.
    pub status: PolicyVersionStatus,
    /// Optional comment describing the change.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub comment: Option<String>,
    /// Approvals collected for this version.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub approvals: Vec<PolicyApproval>,
    /// Number of approvals required before promotion.
    #[serde(default)]
    pub required_approvals: u32,
    /// Link to the previous version (for rollback chain).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub previous_version_id: Option<String>,

    /// ISO 8601 timestamp of when this version entered Staging status.
    /// Set automatically when promoting Draft → Staging.
    /// Used to enforce `staging_period_secs` before allowing Staging → Active.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub staged_at: Option<String>,
}

impl PolicyVersion {
    /// Validate all fields of this version.
    pub fn validate(&self) -> Result<(), String> {
        // version_id
        if self.version_id.is_empty() {
            return Err("version_id must be non-empty".to_string());
        }
        if self.version_id.len() > MAX_LIFECYCLE_IDENTITY_LEN {
            return Err(format!(
                "version_id exceeds {MAX_LIFECYCLE_IDENTITY_LEN} chars"
            ));
        }
        if has_dangerous_chars(&self.version_id) {
            return Err("version_id contains invalid characters".to_string());
        }
        // policy_id
        if self.policy_id.is_empty() {
            return Err("policy_id must be non-empty".to_string());
        }
        // MAX_POLICY_ID_LEN = 256 (matches core.rs Policy::validate())
        if self.policy_id.len() > 256 {
            return Err("policy_id exceeds 256 chars".to_string());
        }
        if has_dangerous_chars(&self.policy_id) {
            return Err("policy_id contains invalid characters".to_string());
        }
        // version
        if self.version == 0 {
            return Err("version must be >= 1".to_string());
        }
        // policy
        self.policy.validate().map_err(|e| format!("policy: {e}"))?;
        // created_by
        if self.created_by.is_empty() || self.created_by.trim().is_empty() {
            return Err("created_by must be non-empty".to_string());
        }
        if self.created_by.len() > MAX_LIFECYCLE_IDENTITY_LEN {
            return Err(format!(
                "created_by exceeds {MAX_LIFECYCLE_IDENTITY_LEN} chars"
            ));
        }
        if has_dangerous_chars(&self.created_by) {
            return Err("created_by contains invalid characters".to_string());
        }
        // created_at
        if self.created_at.is_empty() {
            return Err("created_at must be non-empty".to_string());
        }
        if has_dangerous_chars(&self.created_at) {
            return Err("created_at contains invalid characters".to_string());
        }
        crate::time_util::parse_iso8601_secs(&self.created_at)
            .map_err(|e| format!("created_at: {e}"))?;
        // comment
        if let Some(ref c) = self.comment {
            if c.len() > MAX_VERSION_COMMENT_LEN {
                return Err(format!("comment exceeds {MAX_VERSION_COMMENT_LEN} chars"));
            }
            if has_dangerous_chars(c) {
                return Err("comment contains invalid characters".to_string());
            }
        }
        // approvals
        if self.approvals.len() > MAX_APPROVALS_PER_VERSION {
            return Err(format!(
                "approvals count {} exceeds max {}",
                self.approvals.len(),
                MAX_APPROVALS_PER_VERSION
            ));
        }
        for (i, a) in self.approvals.iter().enumerate() {
            a.validate().map_err(|e| format!("approval[{i}]: {e}"))?;
        }
        // required_approvals
        if self.required_approvals as usize > MAX_REQUIRED_APPROVERS {
            return Err(format!(
                "required_approvals {} exceeds max {}",
                self.required_approvals, MAX_REQUIRED_APPROVERS
            ));
        }
        // staged_at
        if let Some(ref ts) = self.staged_at {
            if ts.is_empty() {
                return Err("staged_at must be non-empty when present".to_string());
            }
            if has_dangerous_chars(ts) {
                return Err("staged_at contains invalid characters".to_string());
            }
            crate::time_util::parse_iso8601_secs(ts).map_err(|e| format!("staged_at: {e}"))?;
        }
        // previous_version_id
        if let Some(ref prev) = self.previous_version_id {
            if prev.len() > MAX_LIFECYCLE_IDENTITY_LEN {
                return Err(format!(
                    "previous_version_id exceeds {MAX_LIFECYCLE_IDENTITY_LEN} chars"
                ));
            }
            if has_dangerous_chars(prev) {
                return Err("previous_version_id contains invalid characters".to_string());
            }
        }
        Ok(())
    }
}

/// Structural diff between two policy versions.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PolicyVersionDiff {
    /// Policy ID being compared.
    pub policy_id: String,
    /// Source version number.
    pub from_version: u64,
    /// Target version number.
    pub to_version: u64,
    /// List of human-readable changes.
    pub changes: Vec<String>,
}

impl PolicyVersionDiff {
    /// Validate diff fields.
    pub fn validate(&self) -> Result<(), String> {
        if self.policy_id.is_empty() {
            return Err("policy_id must be non-empty".to_string());
        }
        if self.policy_id.len() > MAX_DIFF_POLICY_ID_LEN {
            return Err(format!("policy_id exceeds {MAX_DIFF_POLICY_ID_LEN} chars"));
        }
        if has_dangerous_chars(&self.policy_id) {
            return Err("policy_id contains invalid characters".to_string());
        }
        if self.changes.len() > MAX_DIFF_CHANGES {
            return Err(format!(
                "changes count {} exceeds max {}",
                self.changes.len(),
                MAX_DIFF_CHANGES
            ));
        }
        // SECURITY (FIND-R205-004): Validate individual change strings
        // to prevent unbounded allocation and dangerous character injection.
        for (i, change) in self.changes.iter().enumerate() {
            if change.len() > MAX_DIFF_CHANGE_LEN {
                return Err(format!("changes[{i}] exceeds {MAX_DIFF_CHANGE_LEN} chars"));
            }
            if has_dangerous_chars(change) {
                return Err(format!("changes[{i}] contains invalid characters"));
            }
        }
        Ok(())
    }
}

/// A single staging comparison entry recording a divergence between
/// active and staging policy evaluation results.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StagingComparisonEntry {
    /// ISO 8601 timestamp of the evaluation.
    pub timestamp: String,
    /// Tool name from the action.
    pub tool: String,
    /// Function name from the action.
    pub function: String,
    /// Verdict from the active policy set.
    pub active_verdict: String,
    /// Verdict from the staging policy set.
    pub staging_verdict: String,
}

impl StagingComparisonEntry {
    /// Validate all fields of this staging comparison entry.
    ///
    /// SECURITY (FIND-R205-002): Each string field is checked for dangerous
    /// characters and bounded by length. The timestamp is validated as ISO 8601.
    pub fn validate(&self) -> Result<(), String> {
        // timestamp
        if self.timestamp.is_empty() {
            return Err("timestamp must be non-empty".to_string());
        }
        if has_dangerous_chars(&self.timestamp) {
            return Err("timestamp contains invalid characters".to_string());
        }
        crate::time_util::parse_iso8601_secs(&self.timestamp)
            .map_err(|e| format!("timestamp: {e}"))?;
        // tool
        if self.tool.is_empty() {
            return Err("tool must be non-empty".to_string());
        }
        if self.tool.len() > MAX_STAGING_NAME_LEN {
            return Err(format!("tool exceeds {MAX_STAGING_NAME_LEN} chars"));
        }
        if has_dangerous_chars(&self.tool) {
            return Err("tool contains invalid characters".to_string());
        }
        // function
        if self.function.is_empty() {
            return Err("function must be non-empty".to_string());
        }
        if self.function.len() > MAX_STAGING_NAME_LEN {
            return Err(format!("function exceeds {MAX_STAGING_NAME_LEN} chars"));
        }
        if has_dangerous_chars(&self.function) {
            return Err("function contains invalid characters".to_string());
        }
        // active_verdict
        if self.active_verdict.is_empty() {
            return Err("active_verdict must be non-empty".to_string());
        }
        if self.active_verdict.len() > MAX_VERDICT_STRING_LEN {
            return Err(format!(
                "active_verdict exceeds {MAX_VERDICT_STRING_LEN} chars"
            ));
        }
        if has_dangerous_chars(&self.active_verdict) {
            return Err("active_verdict contains invalid characters".to_string());
        }
        // staging_verdict
        if self.staging_verdict.is_empty() {
            return Err("staging_verdict must be non-empty".to_string());
        }
        if self.staging_verdict.len() > MAX_VERDICT_STRING_LEN {
            return Err(format!(
                "staging_verdict exceeds {MAX_VERDICT_STRING_LEN} chars"
            ));
        }
        if has_dangerous_chars(&self.staging_verdict) {
            return Err("staging_verdict contains invalid characters".to_string());
        }
        Ok(())
    }
}

/// Report summarizing staging shadow evaluation results.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StagingReport {
    /// Policy ID being staged.
    pub policy_id: String,
    /// Version number in staging.
    pub staging_version: u64,
    /// Total evaluations observed during staging.
    pub total_evaluations: u64,
    /// Number of evaluations where staging differed from active.
    pub divergent_evaluations: u64,
    /// Detailed divergence entries (bounded by MAX_STAGING_REPORT_ENTRIES).
    pub divergences: Vec<StagingComparisonEntry>,
    /// ISO 8601 timestamp when staging began.
    pub staging_started_at: String,
}

impl StagingReport {
    /// Validate report fields.
    pub fn validate(&self) -> Result<(), String> {
        if self.policy_id.is_empty() {
            return Err("policy_id must be non-empty".to_string());
        }
        // SECURITY (FIND-R209-004): Enforce length bound on policy_id,
        // matching PolicyVersionDiff::validate() which uses MAX_DIFF_POLICY_ID_LEN.
        if self.policy_id.len() > MAX_DIFF_POLICY_ID_LEN {
            return Err(format!("policy_id exceeds {MAX_DIFF_POLICY_ID_LEN} chars"));
        }
        if has_dangerous_chars(&self.policy_id) {
            return Err("policy_id contains invalid characters".to_string());
        }
        // SECURITY (FIND-R224-004): Reject divergent_evaluations exceeding total_evaluations.
        // This invariant must always hold; a violation indicates data corruption or tampering.
        if self.divergent_evaluations > self.total_evaluations {
            return Err(format!(
                "divergent_evaluations ({}) exceeds total_evaluations ({})",
                self.divergent_evaluations, self.total_evaluations
            ));
        }
        if self.divergences.len() > MAX_STAGING_REPORT_ENTRIES {
            return Err(format!(
                "divergences count {} exceeds max {}",
                self.divergences.len(),
                MAX_STAGING_REPORT_ENTRIES
            ));
        }
        // SECURITY (FIND-R205-002): Validate each divergence entry.
        for (i, entry) in self.divergences.iter().enumerate() {
            entry
                .validate()
                .map_err(|e| format!("divergences[{i}]: {e}"))?;
        }
        // IMP-R206-010: Validate staging_started_at timestamp (parity
        // with PolicyApproval::validate and PolicyVersion::validate).
        if self.staging_started_at.is_empty() {
            return Err("staging_started_at must be non-empty".to_string());
        }
        if has_dangerous_chars(&self.staging_started_at) {
            return Err("staging_started_at contains invalid characters".to_string());
        }
        crate::time_util::parse_iso8601_secs(&self.staging_started_at)
            .map_err(|e| format!("staging_started_at: {e}"))?;
        Ok(())
    }
}

/// Status summary of the policy lifecycle subsystem.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PolicyLifecycleStatus {
    /// Whether policy lifecycle management is enabled.
    pub enabled: bool,
    /// Number of policies with version tracking.
    pub tracked_policies: usize,
    /// Total number of versions across all policies.
    pub total_versions: usize,
    /// Number of policies currently in staging.
    pub staging_count: usize,
    /// Whether approval workflow is required (required_approvals > 0).
    pub approval_workflow_enabled: bool,
}

impl PolicyLifecycleStatus {
    /// Validate structural invariants on deserialized status data.
    ///
    /// SECURITY (FIND-R224-007): Prevents inconsistent or oversized status values
    /// from untrusted deserialized payloads.
    pub fn validate(&self) -> Result<(), String> {
        if self.total_versions > MAX_TOTAL_VERSIONS {
            return Err(format!(
                "total_versions ({}) exceeds MAX_TOTAL_VERSIONS ({})",
                self.total_versions, MAX_TOTAL_VERSIONS
            ));
        }
        if self.staging_count > self.tracked_policies {
            return Err(format!(
                "staging_count ({}) exceeds tracked_policies ({})",
                self.staging_count, self.tracked_policies
            ));
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Policy, PolicyType};

    // ── Helper: minimal valid Policy ────────────────────────────────────

    fn valid_policy() -> Policy {
        Policy {
            id: "pol-1".to_string(),
            name: "Test Policy".to_string(),
            policy_type: PolicyType::Allow,
            priority: 100,
            path_rules: None,
            network_rules: None,
        }
    }

    // ── Helper: minimal valid PolicyVersion ──────────────────────────────

    fn valid_version() -> PolicyVersion {
        PolicyVersion {
            version_id: "ver-001".to_string(),
            policy_id: "pol-1".to_string(),
            version: 1,
            policy: valid_policy(),
            created_by: "admin".to_string(),
            created_at: "2025-06-01T12:00:00Z".to_string(),
            status: PolicyVersionStatus::Draft,
            comment: None,
            approvals: vec![],
            required_approvals: 0,
            previous_version_id: None,
            staged_at: None,
        }
    }

    // ── PolicyVersion::validate() — valid baseline ──────────────────────

    #[test]
    fn test_policy_version_validate_valid_baseline_ok() {
        assert!(valid_version().validate().is_ok());
    }

    // ── version_id validation ───────────────────────────────────────────

    #[test]
    fn test_policy_version_validate_empty_version_id_rejected() {
        let mut pv = valid_version();
        pv.version_id = String::new();
        assert!(pv
            .validate()
            .unwrap_err()
            .contains("version_id must be non-empty"));
    }

    #[test]
    fn test_policy_version_validate_version_id_too_long_rejected() {
        let mut pv = valid_version();
        pv.version_id = "v".repeat(MAX_LIFECYCLE_IDENTITY_LEN + 1);
        assert!(pv.validate().unwrap_err().contains("version_id exceeds"));
    }

    #[test]
    fn test_policy_version_validate_version_id_control_chars_rejected() {
        let mut pv = valid_version();
        pv.version_id = "ver\x00null".to_string();
        assert!(pv
            .validate()
            .unwrap_err()
            .contains("version_id contains invalid"));
    }

    // ── policy_id validation ────────────────────────────────────────────

    #[test]
    fn test_policy_version_validate_empty_policy_id_rejected() {
        let mut pv = valid_version();
        pv.policy_id = String::new();
        assert!(pv
            .validate()
            .unwrap_err()
            .contains("policy_id must be non-empty"));
    }

    #[test]
    fn test_policy_version_validate_policy_id_too_long_rejected() {
        let mut pv = valid_version();
        pv.policy_id = "p".repeat(257);
        assert!(pv.validate().unwrap_err().contains("policy_id exceeds 256"));
    }

    // ── version number ──────────────────────────────────────────────────

    #[test]
    fn test_policy_version_validate_version_zero_rejected() {
        let mut pv = valid_version();
        pv.version = 0;
        assert!(pv.validate().unwrap_err().contains("version must be >= 1"));
    }

    // ── created_by validation ───────────────────────────────────────────

    #[test]
    fn test_policy_version_validate_empty_created_by_rejected() {
        let mut pv = valid_version();
        pv.created_by = String::new();
        assert!(pv
            .validate()
            .unwrap_err()
            .contains("created_by must be non-empty"));
    }

    #[test]
    fn test_policy_version_validate_whitespace_only_created_by_rejected() {
        let mut pv = valid_version();
        pv.created_by = "   ".to_string();
        assert!(pv
            .validate()
            .unwrap_err()
            .contains("created_by must be non-empty"));
    }

    // ── created_at timestamp validation ─────────────────────────────────

    #[test]
    fn test_policy_version_validate_invalid_timestamp_rejected() {
        let mut pv = valid_version();
        pv.created_at = "not-a-timestamp".to_string();
        assert!(pv.validate().unwrap_err().contains("created_at:"));
    }

    #[test]
    fn test_policy_version_validate_empty_created_at_rejected() {
        let mut pv = valid_version();
        pv.created_at = String::new();
        assert!(pv
            .validate()
            .unwrap_err()
            .contains("created_at must be non-empty"));
    }

    // ── comment bounds ──────────────────────────────────────────────────

    #[test]
    fn test_policy_version_validate_comment_too_long_rejected() {
        let mut pv = valid_version();
        pv.comment = Some("c".repeat(MAX_VERSION_COMMENT_LEN + 1));
        assert!(pv.validate().unwrap_err().contains("comment exceeds"));
    }

    #[test]
    fn test_policy_version_validate_comment_control_chars_rejected() {
        let mut pv = valid_version();
        pv.comment = Some("note\x07bell".to_string());
        assert!(pv
            .validate()
            .unwrap_err()
            .contains("comment contains invalid"));
    }

    // ── approvals overflow ──────────────────────────────────────────────

    #[test]
    fn test_policy_version_validate_too_many_approvals_rejected() {
        let mut pv = valid_version();
        pv.approvals = (0..MAX_APPROVALS_PER_VERSION + 1)
            .map(|i| PolicyApproval {
                approved_by: format!("user-{i}"),
                approved_at: "2025-06-01T12:00:00Z".to_string(),
                comment: None,
            })
            .collect();
        assert!(pv.validate().unwrap_err().contains("approvals count"));
    }

    // ── staged_at validation ────────────────────────────────────────────

    #[test]
    fn test_policy_version_validate_staged_at_empty_when_present_rejected() {
        let mut pv = valid_version();
        pv.staged_at = Some(String::new());
        assert!(pv
            .validate()
            .unwrap_err()
            .contains("staged_at must be non-empty"));
    }

    #[test]
    fn test_policy_version_validate_staged_at_bad_timestamp_rejected() {
        let mut pv = valid_version();
        pv.staged_at = Some("bad-ts".to_string());
        assert!(pv.validate().unwrap_err().contains("staged_at:"));
    }

    // ── PolicyApproval::validate() ──────────────────────────────────────

    #[test]
    fn test_policy_approval_validate_valid_ok() {
        let pa = PolicyApproval {
            approved_by: "reviewer".to_string(),
            approved_at: "2025-06-01T12:00:00Z".to_string(),
            comment: Some("looks good".to_string()),
        };
        assert!(pa.validate().is_ok());
    }

    #[test]
    fn test_policy_approval_validate_empty_approved_by_rejected() {
        let pa = PolicyApproval {
            approved_by: String::new(),
            approved_at: "2025-06-01T12:00:00Z".to_string(),
            comment: None,
        };
        assert!(pa
            .validate()
            .unwrap_err()
            .contains("approved_by must be non-empty"));
    }

    #[test]
    fn test_policy_approval_validate_approved_by_too_long_rejected() {
        let pa = PolicyApproval {
            approved_by: "u".repeat(MAX_LIFECYCLE_IDENTITY_LEN + 1),
            approved_at: "2025-06-01T12:00:00Z".to_string(),
            comment: None,
        };
        assert!(pa.validate().unwrap_err().contains("approved_by exceeds"));
    }

    #[test]
    fn test_policy_approval_validate_approved_at_bad_timestamp_rejected() {
        let pa = PolicyApproval {
            approved_by: "admin".to_string(),
            approved_at: "invalid".to_string(),
            comment: None,
        };
        assert!(pa.validate().unwrap_err().contains("approved_at:"));
    }

    #[test]
    fn test_policy_approval_validate_comment_too_long_rejected() {
        let pa = PolicyApproval {
            approved_by: "admin".to_string(),
            approved_at: "2025-06-01T12:00:00Z".to_string(),
            comment: Some("c".repeat(MAX_VERSION_COMMENT_LEN + 1)),
        };
        assert!(pa
            .validate()
            .unwrap_err()
            .contains("approval comment exceeds"));
    }

    #[test]
    fn test_policy_approval_validate_comment_control_chars_rejected() {
        let pa = PolicyApproval {
            approved_by: "admin".to_string(),
            approved_at: "2025-06-01T12:00:00Z".to_string(),
            comment: Some("ok\x01bad".to_string()),
        };
        assert!(pa
            .validate()
            .unwrap_err()
            .contains("approval comment contains invalid"));
    }

    // ── PolicyVersionDiff::validate() ───────────────────────────────────

    #[test]
    fn test_policy_version_diff_validate_valid_ok() {
        let diff = PolicyVersionDiff {
            policy_id: "pol-1".to_string(),
            from_version: 1,
            to_version: 2,
            changes: vec!["Added path rule".to_string()],
        };
        assert!(diff.validate().is_ok());
    }

    #[test]
    fn test_policy_version_diff_validate_too_many_changes_rejected() {
        let diff = PolicyVersionDiff {
            policy_id: "pol-1".to_string(),
            from_version: 1,
            to_version: 2,
            changes: vec!["change".to_string(); MAX_DIFF_CHANGES + 1],
        };
        assert!(diff.validate().unwrap_err().contains("changes count"));
    }

    #[test]
    fn test_policy_version_diff_validate_change_too_long_rejected() {
        let diff = PolicyVersionDiff {
            policy_id: "pol-1".to_string(),
            from_version: 1,
            to_version: 2,
            changes: vec!["x".repeat(MAX_DIFF_CHANGE_LEN + 1)],
        };
        assert!(diff.validate().unwrap_err().contains("changes[0] exceeds"));
    }

    // ── PolicyLifecycleStatus::validate() ───────────────────────────────

    #[test]
    fn test_policy_lifecycle_status_validate_valid_ok() {
        let status = PolicyLifecycleStatus {
            enabled: true,
            tracked_policies: 10,
            total_versions: 50,
            staging_count: 2,
            approval_workflow_enabled: true,
        };
        assert!(status.validate().is_ok());
    }

    #[test]
    fn test_policy_lifecycle_status_validate_total_versions_overflow_rejected() {
        let status = PolicyLifecycleStatus {
            enabled: true,
            tracked_policies: 1,
            total_versions: MAX_TOTAL_VERSIONS + 1,
            staging_count: 0,
            approval_workflow_enabled: false,
        };
        assert!(status.validate().unwrap_err().contains("total_versions"));
    }

    #[test]
    fn test_policy_lifecycle_status_validate_staging_exceeds_tracked_rejected() {
        let status = PolicyLifecycleStatus {
            enabled: true,
            tracked_policies: 5,
            total_versions: 10,
            staging_count: 6,
            approval_workflow_enabled: false,
        };
        assert!(status.validate().unwrap_err().contains("staging_count"));
    }
}