tokmd-gate 1.14.0

Policy evaluation engine for tokmd analysis receipts
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
//! Policy and rule type definitions.

use serde::{Deserialize, Serialize};
use std::path::Path;

/// Errors from policy evaluation.
#[derive(Debug)]
pub enum GateError {
    IoError(std::io::Error),
    TomlError(toml::de::Error),
    InvalidPointer(String),
    TypeMismatch { expected: String, actual: String },
    InvalidOperator { op: String, value_type: String },
    MissingField { name: String, field: String },
}

impl std::fmt::Display for GateError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::IoError(e) => write!(f, "Failed to read policy file: {e}"),
            Self::TomlError(e) => write!(f, "Failed to parse policy TOML: {e}"),
            Self::InvalidPointer(p) => write!(f, "Invalid JSON pointer: {p}"),
            Self::TypeMismatch { expected, actual } => {
                write!(f, "Type mismatch: expected {expected}, got {actual}")
            }
            Self::InvalidOperator { op, value_type } => {
                write!(f, "Invalid operator '{op}' for type '{value_type}'")
            }
            Self::MissingField { name, field } => {
                write!(f, "Rule '{name}' missing required field: {field}")
            }
        }
    }
}

impl std::error::Error for GateError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::IoError(e) => Some(e),
            Self::TomlError(e) => Some(e),
            _ => None,
        }
    }
}

impl From<std::io::Error> for GateError {
    fn from(err: std::io::Error) -> Self {
        Self::IoError(err)
    }
}

impl From<toml::de::Error> for GateError {
    fn from(err: toml::de::Error) -> Self {
        Self::TomlError(err)
    }
}

/// Root policy configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct PolicyConfig {
    /// Policy rules to evaluate.
    pub rules: Vec<PolicyRule>,

    /// Stop evaluation on first error.
    #[serde(default)]
    pub fail_fast: bool,

    /// Allow missing values (treat as pass) instead of error.
    #[serde(default)]
    pub allow_missing: bool,
}

impl PolicyConfig {
    /// Parse policy from TOML string.
    ///
    /// # Examples
    ///
    /// ```
    /// use tokmd_gate::PolicyConfig;
    ///
    /// let toml = r#"
    /// fail_fast = false
    /// allow_missing = true
    ///
    /// [[rules]]
    /// name = "max_tokens"
    /// pointer = "/tokens"
    /// op = "lte"
    /// value = 100000
    /// "#;
    ///
    /// let policy = PolicyConfig::from_toml(toml).unwrap();
    /// assert_eq!(policy.rules.len(), 1);
    /// assert!(policy.allow_missing);
    /// ```
    pub fn from_toml(s: &str) -> Result<Self, GateError> {
        Ok(toml::from_str(s)?)
    }

    /// Load policy from a TOML file.
    pub fn from_file(path: &Path) -> Result<Self, GateError> {
        let content = std::fs::read_to_string(path)?;
        Self::from_toml(&content)
    }
}

/// A single policy rule.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PolicyRule {
    /// Human-readable name for the rule.
    pub name: String,

    /// JSON Pointer to the value to check (RFC 6901).
    pub pointer: String,

    /// Comparison operator.
    pub op: RuleOperator,

    /// Single value for comparison (for >, <, ==, etc.).
    #[serde(default)]
    pub value: Option<serde_json::Value>,

    /// Multiple values for "in" operator.
    #[serde(default)]
    pub values: Option<Vec<serde_json::Value>>,

    /// Negate the result (NOT).
    #[serde(default)]
    pub negate: bool,

    /// Rule severity level.
    #[serde(default)]
    pub level: RuleLevel,

    /// Custom failure message.
    #[serde(default)]
    pub message: Option<String>,
}

/// Comparison operators for rules.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum RuleOperator {
    /// Greater than (>)
    Gt,
    /// Greater than or equal (>=)
    Gte,
    /// Less than (<)
    Lt,
    /// Less than or equal (<=)
    Lte,
    /// Equal (==)
    #[default]
    Eq,
    /// Not equal (!=)
    Ne,
    /// Value is in list
    In,
    /// String/array contains value
    Contains,
    /// JSON pointer exists (value is present)
    Exists,
}

impl std::fmt::Display for RuleOperator {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RuleOperator::Gt => write!(f, ">"),
            RuleOperator::Gte => write!(f, ">="),
            RuleOperator::Lt => write!(f, "<"),
            RuleOperator::Lte => write!(f, "<="),
            RuleOperator::Eq => write!(f, "=="),
            RuleOperator::Ne => write!(f, "!="),
            RuleOperator::In => write!(f, "in"),
            RuleOperator::Contains => write!(f, "contains"),
            RuleOperator::Exists => write!(f, "exists"),
        }
    }
}

/// Rule severity level.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum RuleLevel {
    /// Warning - does not fail the gate.
    Warn,
    /// Error - fails the gate.
    #[default]
    Error,
}

/// Result of evaluating the entire policy.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GateResult {
    /// Overall pass/fail.
    pub passed: bool,

    /// Individual rule results.
    pub rule_results: Vec<RuleResult>,

    /// Count of errors.
    pub errors: usize,

    /// Count of warnings.
    pub warnings: usize,
}

impl GateResult {
    /// Create a new gate result from rule results.
    pub fn from_results(rule_results: Vec<RuleResult>) -> Self {
        let errors = rule_results
            .iter()
            .filter(|r| !r.passed && r.level == RuleLevel::Error)
            .count();
        let warnings = rule_results
            .iter()
            .filter(|r| !r.passed && r.level == RuleLevel::Warn)
            .count();
        let passed = errors == 0;

        Self {
            passed,
            rule_results,
            errors,
            warnings,
        }
    }
}

/// Result of evaluating a single rule.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RuleResult {
    /// Rule name.
    pub name: String,

    /// Whether the rule passed.
    pub passed: bool,

    /// Rule level (error/warn).
    pub level: RuleLevel,

    /// Actual value found (if any).
    pub actual: Option<serde_json::Value>,

    /// Expected value or condition.
    pub expected: String,

    /// Failure message.
    pub message: Option<String>,
}

/// Ratchet rule for gradual improvement.
///
/// Ratchet rules enforce that metrics don't regress beyond acceptable bounds
/// when compared to a baseline. This enables gradual quality improvement by
/// allowing teams to "ratchet" down thresholds over time.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RatchetRule {
    /// JSON pointer to the metric (e.g., "/complexity/avg_cyclomatic").
    pub pointer: String,

    /// Maximum allowed increase percentage from baseline.
    /// For example, 10.0 means the current value can be at most 10% higher than baseline.
    #[serde(default)]
    pub max_increase_pct: Option<f64>,

    /// Maximum allowed absolute value.
    /// This acts as a hard ceiling regardless of baseline.
    #[serde(default)]
    pub max_value: Option<f64>,

    /// Rule severity level.
    #[serde(default)]
    pub level: RuleLevel,

    /// Human-readable description of the rule.
    #[serde(default)]
    pub description: Option<String>,
}

/// Result of ratchet evaluation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RatchetResult {
    /// The rule that was evaluated.
    pub rule: RatchetRule,

    /// Whether the ratchet check passed.
    pub passed: bool,

    /// Baseline value (if found).
    pub baseline_value: Option<f64>,

    /// Current value.
    pub current_value: f64,

    /// Percentage change from baseline (if baseline exists).
    pub change_pct: Option<f64>,

    /// Human-readable message describing the result.
    pub message: String,
}

/// Configuration for ratchet rules.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct RatchetConfig {
    /// Ratchet rules to evaluate.
    pub rules: Vec<RatchetRule>,

    /// Stop evaluation on first error.
    #[serde(default)]
    pub fail_fast: bool,

    /// Allow missing baseline values (treat as pass) instead of error.
    #[serde(default)]
    pub allow_missing_baseline: bool,

    /// Allow missing current values (treat as pass) instead of error.
    #[serde(default)]
    pub allow_missing_current: bool,
}

impl RatchetConfig {
    /// Parse ratchet config from TOML string.
    pub fn from_toml(s: &str) -> Result<Self, GateError> {
        Ok(toml::from_str(s)?)
    }

    /// Load ratchet config from a TOML file.
    pub fn from_file(path: &Path) -> Result<Self, GateError> {
        let content = std::fs::read_to_string(path)?;
        Self::from_toml(&content)
    }
}

/// Overall result of ratchet evaluation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RatchetGateResult {
    /// Overall pass/fail.
    pub passed: bool,

    /// Individual ratchet results.
    pub ratchet_results: Vec<RatchetResult>,

    /// Count of errors.
    pub errors: usize,

    /// Count of warnings.
    pub warnings: usize,
}

impl RatchetGateResult {
    /// Create a new ratchet gate result from ratchet results.
    pub fn from_results(ratchet_results: Vec<RatchetResult>) -> Self {
        let errors = ratchet_results
            .iter()
            .filter(|r| !r.passed && r.rule.level == RuleLevel::Error)
            .count();
        let warnings = ratchet_results
            .iter()
            .filter(|r| !r.passed && r.rule.level == RuleLevel::Warn)
            .count();
        let passed = errors == 0;

        Self {
            passed,
            ratchet_results,
            errors,
            warnings,
        }
    }
}

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

    #[test]
    fn test_parse_policy() {
        let toml = r#"
fail_fast = true
allow_missing = false

[[rules]]
name = "max_tokens"
pointer = "/derived/totals/tokens"
op = "lte"
value = 500000
level = "error"
message = "Too many tokens"

[[rules]]
name = "has_license"
pointer = "/license/effective"
op = "exists"
level = "warn"
"#;
        let policy = PolicyConfig::from_toml(toml).unwrap();
        assert!(policy.fail_fast);
        assert!(!policy.allow_missing);
        assert_eq!(policy.rules.len(), 2);
        assert_eq!(policy.rules[0].name, "max_tokens");
        assert_eq!(policy.rules[0].op, RuleOperator::Lte);
        assert_eq!(policy.rules[1].op, RuleOperator::Exists);
    }

    #[test]
    fn test_gate_result() {
        let results = vec![
            RuleResult {
                name: "rule1".into(),
                passed: true,
                level: RuleLevel::Error,
                actual: None,
                expected: "test".into(),
                message: None,
            },
            RuleResult {
                name: "rule2".into(),
                passed: false,
                level: RuleLevel::Warn,
                actual: None,
                expected: "test".into(),
                message: Some("Warning".into()),
            },
        ];

        let gate = GateResult::from_results(results);
        assert!(gate.passed); // Only warns, no errors
        assert_eq!(gate.errors, 0);
        assert_eq!(gate.warnings, 1);
    }

    #[test]
    fn test_policy_from_file() {
        // Kills mutant: PolicyConfig::from_file -> Ok(Default::default()).
        use std::time::{SystemTime, UNIX_EPOCH};

        let toml = r#"
fail_fast = true
allow_missing = false

[[rules]]
name = "max_tokens"
pointer = "/derived/totals/tokens"
op = "lte"
value = 500000
level = "error"
"#;

        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let path = std::env::temp_dir().join(format!("tokmd-gate-policy-{nanos}.toml"));
        std::fs::write(&path, toml).unwrap();

        let policy = PolicyConfig::from_file(&path).unwrap();
        let _ = std::fs::remove_file(&path);

        assert!(policy.fail_fast);
        assert_eq!(policy.rules.len(), 1);
        assert_eq!(policy.rules[0].name, "max_tokens");
        assert_eq!(policy.rules[0].op, RuleOperator::Lte);
    }

    #[test]
    fn test_rule_operator_display() {
        // Kills mutant in Display impl.
        assert_eq!(RuleOperator::Gt.to_string(), ">");
        assert_eq!(RuleOperator::Gte.to_string(), ">=");
        assert_eq!(RuleOperator::Lt.to_string(), "<");
        assert_eq!(RuleOperator::Lte.to_string(), "<=");
        assert_eq!(RuleOperator::Eq.to_string(), "==");
        assert_eq!(RuleOperator::Ne.to_string(), "!=");
        assert_eq!(RuleOperator::In.to_string(), "in");
        assert_eq!(RuleOperator::Contains.to_string(), "contains");
        assert_eq!(RuleOperator::Exists.to_string(), "exists");
    }

    #[test]
    fn test_gate_result_counts_only_failed_rules() {
        // Kills `&&` -> `||` mutant in warning counting by including a passed WARN.
        let results = vec![
            RuleResult {
                name: "passed_warn".into(),
                passed: true,
                level: RuleLevel::Warn,
                actual: None,
                expected: "x".into(),
                message: None,
            },
            RuleResult {
                name: "failed_warn".into(),
                passed: false,
                level: RuleLevel::Warn,
                actual: None,
                expected: "x".into(),
                message: Some("warn".into()),
            },
        ];

        let gate = GateResult::from_results(results);
        assert!(gate.passed); // warns only
        assert_eq!(gate.errors, 0);
        assert_eq!(gate.warnings, 1);
    }
}