doctrine 0.15.2

Project tooling CLI
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
// SPDX-License-Identifier: GPL-3.0-only
//! `config` — the `[priority]` section of `doctrine.toml` (SL-133 PHASE-03).
//!
//! Declares the project's priority scoring coefficients: per-kind weights,
//! per-tag coefficients, value/risk/consequence multipliers. Purely advisory —
//! `load` never errors, silently clamping every out-of-bounds coefficient to a
//! safe finite range so downstream products stay bounded (no NaN poison).
//! Contrast `dispatch_config`, which deliberately hard-errors on malformed input.

use serde::Deserialize;
use std::collections::BTreeMap;
use std::path::Path;

/// Cap all coefficients so downstream products stay finite.
/// NaN / +/-inf clamp to the field-specific default; negatives → 0.0;
/// values above this → `COEFF_MAX`.
pub(crate) const COEFF_MAX: f64 = 1e9;

// ── sub-structs ───────────────────────────────────────────────────────────

#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub(crate) struct Coefficients {
    #[serde(default = "default_value_coeff")]
    pub(crate) value: f64,
    #[serde(default = "default_risk_coeff")]
    pub(crate) risk: f64,
}

impl Default for Coefficients {
    fn default() -> Self {
        Self {
            value: 1.0,
            risk: 2.0,
        }
    }
}

fn default_value_coeff() -> f64 {
    1.0
}
fn default_risk_coeff() -> f64 {
    2.0
}

#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub(crate) struct ConsequenceCoeffs {
    #[serde(default = "default_dep_coeff")]
    pub(crate) dep_coeff: f64,
    #[serde(default = "default_ref_coeff")]
    pub(crate) ref_coeff: f64,
}

impl Default for ConsequenceCoeffs {
    fn default() -> Self {
        Self {
            dep_coeff: 0.5,
            ref_coeff: 1.0,
        }
    }
}

fn default_dep_coeff() -> f64 {
    0.5
}
fn default_ref_coeff() -> f64 {
    1.0
}

#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub(crate) struct EstimateCost {
    #[serde(default = "default_skew")]
    pub(crate) skew: f64,
    #[serde(default = "default_margin")]
    pub(crate) margin: f64,
}

impl Default for EstimateCost {
    fn default() -> Self {
        Self {
            skew: 0.65,
            margin: 1.0,
        }
    }
}

fn default_skew() -> f64 {
    0.65
}
fn default_margin() -> f64 {
    1.0
}

// ── top-level config ──────────────────────────────────────────────────────

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub(crate) struct PriorityConfig {
    #[serde(default)]
    pub(crate) coefficients: Coefficients,
    #[serde(default)]
    pub(crate) kind_weights: BTreeMap<String, f64>,
    #[serde(default)]
    pub(crate) tag_coefficients: BTreeMap<String, f64>,
    #[serde(default)]
    pub(crate) consequence: ConsequenceCoeffs,
    #[serde(default)]
    pub(crate) estimate: EstimateCost,
}

// ── accessors ─────────────────────────────────────────────────────────────

impl PriorityConfig {
    /// Look up the weight for a given kind string; returns 1.0 when absent.
    pub(crate) fn kind_weight(&self, kind: &str) -> f64 {
        self.kind_weights.get(kind).copied().unwrap_or(1.0)
    }

    /// Look up the coefficient for a given tag string; returns 1.0 when absent.
    pub(crate) fn tag_coeff(&self, tag: &str) -> f64 {
        self.tag_coefficients.get(tag).copied().unwrap_or(1.0)
    }
}

// ── load (impure shell) ──────────────────────────────────────────────────

/// Read `<root>/doctrine.toml`, deserialise the `[priority]` section, and clamp
/// every coefficient to a safe finite range. NEVER errors — absent file, missing
/// section, and malformed values all silently fall back to defaults.
pub(crate) fn load(root: &Path) -> PriorityConfig {
    let Some(table) = read_priority_table(root) else {
        return PriorityConfig::default();
    };
    load_from_table(&table)
}

pub(crate) fn read_priority_table(root: &Path) -> Option<toml::Table> {
    let text = std::fs::read_to_string(root.join(crate::dtoml::DOCTRINE_TOML)).ok()?;
    let raw: toml::Value = text.parse().ok()?;
    raw.get("priority")?.as_table().cloned()
}

pub(crate) fn load_from_table(table: &toml::value::Table) -> PriorityConfig {
    let mut cfg = PriorityConfig::default();

    if let Some(t) = table.get("coefficients").and_then(|v| v.as_table()) {
        cfg.coefficients.value = f64_or(t, "value", 1.0);
        cfg.coefficients.risk = f64_or(t, "risk", 2.0);
    }
    if let Some(t) = table.get("consequence").and_then(|v| v.as_table()) {
        cfg.consequence.dep_coeff = f64_or(t, "dep_coeff", 0.5);
        cfg.consequence.ref_coeff = f64_or(t, "ref_coeff", 1.0);
    }
    if let Some(t) = table.get("estimate").and_then(|v| v.as_table()) {
        cfg.estimate.skew = f64_or(t, "skew", 0.65);
        cfg.estimate.margin = f64_or(t, "margin", 1.0);
    }
    if let Some(t) = table.get("kind_weights").and_then(|v| v.as_table()) {
        for (k, v) in t {
            if let Some(f) = f64_val(v) {
                cfg.kind_weights.insert(k.clone(), f);
            }
        }
    }
    if let Some(t) = table.get("tag_coefficients").and_then(|v| v.as_table()) {
        for (k, v) in t {
            if let Some(f) = f64_val(v) {
                cfg.tag_coefficients.insert(k.clone(), f);
            }
        }
    }

    clamp(cfg)
}

/// Extract an f64 from a TOML value, accepting integers (TOML `3` → 3.0).
/// Returns `None` for strings, booleans, arrays, and other non-numeric types.
#[expect(
    clippy::as_conversions,
    clippy::cast_precision_loss,
    reason = "i64→f64 safe for TOML config coefficients (never near i64::MAX)"
)]
fn f64_val(v: &toml::Value) -> Option<f64> {
    v.as_float().or_else(|| v.as_integer().map(|i| i as f64))
}

fn f64_or(table: &toml::value::Table, key: &str, default: f64) -> f64 {
    table.get(key).and_then(f64_val).unwrap_or(default)
}

// ── clamping ──────────────────────────────────────────────────────────────

/// Clamp every coefficient in-place so downstream products stay finite.
/// NaN / inf → field default; negative → 0.0; > `COEFF_MAX` → `COEFF_MAX`.
/// `dep_coeff` is tighter: (0, 1].
fn clamp(mut cfg: PriorityConfig) -> PriorityConfig {
    // General coefficients: value, risk, ref_coeff
    cfg.coefficients.value = clamp_general(cfg.coefficients.value, 1.0);
    cfg.coefficients.risk = clamp_general(cfg.coefficients.risk, 2.0);
    cfg.consequence.ref_coeff = clamp_general(cfg.consequence.ref_coeff, 1.0);

    // dep_coeff: (0, 1]
    cfg.consequence.dep_coeff = clamp_dep(cfg.consequence.dep_coeff);

    // estimate: skew → [0.0, 1.0]; margin → non-negative (reuse clamp_general)
    cfg.estimate.skew = clamp_skew(cfg.estimate.skew);
    cfg.estimate.margin = clamp_general(cfg.estimate.margin, 1.0);

    // kind_weights and tag_coefficients: clamp each value
    for v in cfg.kind_weights.values_mut() {
        *v = clamp_general(*v, 1.0);
    }
    for v in cfg.tag_coefficients.values_mut() {
        *v = clamp_general(*v, 1.0);
    }

    cfg
}

/// General coefficient clamp: non-finite → fallback; negative → 0.0; > `COEFF_MAX` → `COEFF_MAX`.
pub(crate) fn clamp_general(value: f64, fallback: f64) -> f64 {
    if !value.is_finite() {
        return fallback;
    }
    if value < 0.0 {
        return 0.0;
    }
    if value > COEFF_MAX {
        return COEFF_MAX;
    }
    value
}

/// Dep-coeff clamp: non-finite → fallback (0.5); ≤ 0 → 0.0; > 1 → 1.0.
pub(crate) fn clamp_dep(value: f64) -> f64 {
    if !value.is_finite() {
        return 0.5;
    }
    if value <= 0.0 {
        return 0.0;
    }
    if value > 1.0 {
        return 1.0;
    }
    value
}

/// Skew clamp (estimate): non-finite → fallback (0.65); < 0 → 0.0; > 1 → 1.0.
pub(crate) fn clamp_skew(value: f64) -> f64 {
    if !value.is_finite() {
        return 0.65;
    }
    if value < 0.0 {
        return 0.0;
    }
    if value > 1.0 {
        return 1.0;
    }
    value
}

// ── tests ─────────────────────────────────────────────────────────────────

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

    /// Write a `doctrine.toml` into `root` and call `load(root)`.
    fn load_from(body: &str) -> PriorityConfig {
        let dir = tempfile::tempdir().unwrap();
        let config_dir = dir.path().join(".doctrine");
        fs::create_dir_all(&config_dir).unwrap();
        fs::write(dir.path().join(crate::dtoml::DOCTRINE_TOML), body).unwrap();
        load(dir.path())
    }

    // ---- absent / missing ----

    #[test]
    fn missing_priority_section_is_defaults() {
        let cfg = load_from("[dispatch]\npreferred-subprocess-harness = \"pi\"\n");
        assert_eq!(cfg.coefficients.value, 1.0);
        assert_eq!(cfg.coefficients.risk, 2.0);
        assert_eq!(cfg.consequence.dep_coeff, 0.5);
        assert_eq!(cfg.consequence.ref_coeff, 1.0);
        assert!(cfg.kind_weights.is_empty());
        assert!(cfg.tag_coefficients.is_empty());
    }

    #[test]
    fn no_doctrine_toml_is_defaults() {
        let dir = tempfile::tempdir().unwrap();
        let cfg = load(dir.path());
        assert_eq!(cfg.coefficients.value, 1.0);
        assert_eq!(cfg.coefficients.risk, 2.0);
    }

    // ---- partial section — per-field defaults ----

    #[test]
    fn partial_section_fills_defaults() {
        let cfg = load_from("[priority]\nkind_weights = { SL = 2.5 }\n");
        assert_eq!(cfg.coefficients.value, 1.0); // missing → default
        assert_eq!(cfg.coefficients.risk, 2.0); // missing → default
        assert_eq!(cfg.consequence.dep_coeff, 0.5); // missing → default
        assert_eq!(cfg.consequence.ref_coeff, 1.0); // missing → default
        assert_eq!(cfg.kind_weight("SL"), 2.5);
        assert_eq!(cfg.kind_weight("ADR"), 1.0); // absent → default
        assert!(cfg.tag_coefficients.is_empty());
    }

    // ---- unknown key ignored ----

    #[test]
    fn unknown_key_ignored() {
        let cfg = load_from("[priority]\ncoefficients = { value = 3.0, risk = 4.0, extra = 99 }\n");
        assert_eq!(cfg.coefficients.value, 3.0);
        assert_eq!(cfg.coefficients.risk, 4.0);
        // extra key is silently ignored by serde(ignore_unknown)
    }

    // ---- non-finite → default ----

    #[test]
    fn nan_coefficient_clamps_to_default() {
        let cfg = load_from("[priority]\ncoefficients = { value = nan, risk = nan }\n");
        assert_eq!(cfg.coefficients.value, 1.0);
        assert_eq!(cfg.coefficients.risk, 2.0);
    }

    #[test]
    fn inf_coefficient_clamps_to_default() {
        let cfg = load_from("[priority]\ncoefficients = { value = inf, risk = -inf }\n");
        assert_eq!(cfg.coefficients.value, 1.0);
        assert_eq!(cfg.coefficients.risk, 2.0);
    }

    // ---- negative → 0.0 ----

    #[test]
    fn negative_coefficient_clamps_to_zero() {
        let cfg = load_from("[priority]\ncoefficients = { value = -5.0, risk = -0.1 }\n");
        assert_eq!(cfg.coefficients.value, 0.0);
        assert_eq!(cfg.coefficients.risk, 0.0);
    }

    // ---- over COEFF_MAX → COEFF_MAX ----

    #[test]
    fn over_max_coefficient_clamps_to_max() {
        let body = format!(
            "[priority]\ncoefficients = {{ value = {max}, risk = {max} }}\n",
            max = COEFF_MAX + 1.0
        );
        let cfg = load_from(&body);
        assert_eq!(cfg.coefficients.value, COEFF_MAX);
        assert_eq!(cfg.coefficients.risk, COEFF_MAX);
    }

    // ---- dep_coeff: > 1 → 1.0 ----

    #[test]
    fn dep_coeff_over_one_clamps_to_one() {
        let cfg = load_from("[priority]\nconsequence = { dep_coeff = 5.0 }\n");
        assert_eq!(cfg.consequence.dep_coeff, 1.0);
    }

    // ---- dep_coeff: ≤ 0 → 0.0 ----

    #[test]
    fn dep_coeff_zero_or_negative_clamps_to_zero() {
        let cfg = load_from("[priority]\nconsequence = { dep_coeff = 0.0 }\n");
        assert_eq!(cfg.consequence.dep_coeff, 0.0);

        let cfg2 = load_from("[priority]\nconsequence = { dep_coeff = -0.5 }\n");
        assert_eq!(cfg2.consequence.dep_coeff, 0.0);
    }

    // ---- malformed value clamps and load does NOT error ----

    #[test]
    fn malformed_toml_in_priority_section_returns_defaults() {
        // A missing closing bracket — malformed TOML in the [priority] value.
        let cfg = load_from("[priority]\ncoefficients = { value = 3.0\n");
        assert_eq!(cfg.coefficients.value, 1.0); // default
    }

    #[test]
    fn non_numeric_value_clamps_returns_defaults() {
        // A string where a number was expected — per-field isolation: only the
        // offending field falls back to its default; the sibling field survives.
        let cfg = load_from("[priority]\ncoefficients = { value = \"abc\", risk = 4.0 }\n");
        assert_eq!(cfg.coefficients.value, 1.0); // wrong-type → field default
        assert_eq!(cfg.coefficients.risk, 4.0); // preserved — per-field isolation
    }

    // ---- kind_weight / tag_coeff absent key returns 1.0 ----

    #[test]
    fn kind_weight_absent_key_returns_default_one() {
        let cfg = PriorityConfig::default();
        assert_eq!(cfg.kind_weight("NONEXISTENT"), 1.0);
    }

    #[test]
    fn tag_coeff_absent_key_returns_default_one() {
        let cfg = PriorityConfig::default();
        assert_eq!(cfg.tag_coeff("nonexistent"), 1.0);
    }

    // ---- kind_weight / tag_coeff present key returns stored value ----

    #[test]
    fn kind_weight_present_key_returns_stored() {
        let cfg = load_from("[priority]\nkind_weights = { SL = 3.0, ADR = 1.5 }\n");
        assert_eq!(cfg.kind_weight("SL"), 3.0);
        assert_eq!(cfg.kind_weight("ADR"), 1.5);
    }

    #[test]
    fn tag_coeff_present_key_returns_stored() {
        let cfg = load_from("[priority]\ntag_coefficients = { \"area:risk\" = 2.0 }\n");
        assert_eq!(cfg.tag_coeff("area:risk"), 2.0);
    }

    // ---- estimate sub-table (SL-172) ----

    /// VT-1: absent file AND a `[priority]` with no `estimate` sub-table ⇒ defaults.
    #[test]
    fn estimate_absent_uses_defaults() {
        let cfg = load_from("[priority]\ncoefficients = { value = 3.0 }\n");
        assert_eq!(cfg.estimate.skew, 0.65);
        assert_eq!(cfg.estimate.margin, 1.0);

        let dir = tempfile::tempdir().unwrap();
        let cfg2 = load(dir.path());
        assert_eq!(cfg2.estimate.skew, 0.65);
        assert_eq!(cfg2.estimate.margin, 1.0);
    }

    /// VT-2: clamps — out-of-range, negative, NaN/inf → safe defaults.
    #[test]
    fn estimate_clamps_values() {
        // skew > 1 → 1.0; margin < 0 → 0.0
        let cfg = load_from("[priority]\nestimate = { skew = 1.5, margin = -3 }\n");
        assert_eq!(cfg.estimate.skew, 1.0);
        assert_eq!(cfg.estimate.margin, 0.0);

        // skew < 0 → 0.0
        let cfg2 = load_from("[priority]\nestimate = { skew = -0.2 }\n");
        assert_eq!(cfg2.estimate.skew, 0.0);

        // NaN/inf → field defaults
        let cfg3 = load_from("[priority]\nestimate = { skew = nan, margin = inf }\n");
        assert_eq!(cfg3.estimate.skew, 0.65);
        assert_eq!(cfg3.estimate.margin, 1.0);
    }

    /// VT-3: round-trip — valid in-range values survive.
    #[test]
    fn estimate_roundtrip_valid_values() {
        let cfg = load_from("[priority]\nestimate = { skew = 0.7, margin = 2 }\n");
        assert_eq!(cfg.estimate.skew, 0.7);
        assert_eq!(cfg.estimate.margin, 2.0);
    }
}