pma-core 0.7.0

pma's store, scanning, dispatch and workflows, and the Query/Action API its front ends share
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
//! Routing policy: which worker and model take a task, and how much autonomy
//! the result gets. The policy is an artifact, not a judgment per task. One
//! decision per revision, applied deterministically to every dispatch.
//!
//! Everything a match reads is computed without a model: class from the
//! signal type or the item's tags, complexity from the versioned rule, tier
//! from the project. The document is JSON because that is what this crate
//! already parses; the design called it `routing.toml`, and adding a TOML
//! parser plus `serde` derive for one file is a larger change than the
//! syntax is worth.
//!
//! Nothing here approves, publishes or merges. A route names an approval mode;
//! phases 4b and 4c are what act on one.

use serde_json::Value;

use crate::class::Class;

/// How much autonomy a route's runs get. `pma` records the mode; acting on
/// it belongs to the approval work of phases 4b and 4c.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Approval {
    /// A patch and a summary; nothing is published.
    Propose,
    /// The user approves each run.
    Each,
    /// The user approves a filtered list.
    Batch,
    /// The tool publishes clean runs and reports afterwards.
    Unattended,
}

impl Approval {
    const ALL: [(&'static str, Approval); 4] = [
        ("propose", Approval::Propose),
        ("each", Approval::Each),
        ("batch", Approval::Batch),
        ("unattended", Approval::Unattended),
    ];

    pub fn name(self) -> &'static str {
        Self::ALL
            .iter()
            .find(|(_, a)| *a == self)
            .map_or("", |(n, _)| n)
    }

    pub fn parse(s: &str) -> Option<Approval> {
        Self::ALL.iter().find(|(n, _)| *n == s).map(|(_, a)| *a)
    }
}

/// A second attempt at a stronger model after the check refused the first.
#[derive(Debug, Clone, PartialEq)]
pub struct Escalate {
    pub model: String,
    /// Attempts beyond the first. Only 1 is honoured today.
    pub attempts: i64,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Route {
    /// For reading a replay. Defaults to the route's position.
    pub name: String,
    pub classes: Option<Vec<Class>>,
    /// Workflow nodes this route serves: a qualified name, or `*/leaf` to
    /// match one node wherever it was called from. `None` matches only a
    /// dispatch that names no node, so an existing policy keeps its behaviour
    /// exactly rather than absorbing every node into its catch-all.
    pub nodes: Option<Vec<String>>,
    /// Laps the unit has completed, as an inclusive range.
    pub lap: Option<(i64, i64)>,
    pub complexity: Option<(i64, i64)>,
    pub tier: Option<(i64, i64)>,
    pub agent: Option<String>,
    pub model: Option<String>,
    pub escalate: Option<Escalate>,
    /// Overrides the class's own globs. Empty means no bound.
    pub scope: Option<Vec<String>>,
    pub approval: Approval,
}

/// What a dispatch knows before it chooses. Every field is recorded on the
/// run, so a replay reads these back rather than re-deriving them from a
/// task that may since have been edited or rescanned.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Subject<'a> {
    pub class: Class,
    pub complexity: i64,
    pub tier: Option<u8>,
    /// The qualified workflow node this dispatch serves, or `None` for a task
    /// dispatched on its own.
    pub node: Option<&'a str>,
    /// Laps the unit had completed. 0 outside a workflow.
    pub lap: i64,
}

#[derive(Debug, Clone, PartialEq, Default)]
pub struct Policy {
    pub routes: Vec<Route>,
}

/// A node condition matches an exact qualified name, or `*/leaf` against the
/// name's last segment. Two forms, both readable; no glob language.
fn node_matches(pattern: &str, node: &str) -> bool {
    match pattern.strip_prefix("*/") {
        Some(leaf) => node.rsplit('/').next() == Some(leaf),
        None => pattern == node,
    }
}

impl Route {
    fn matches(&self, s: &Subject<'_>) -> bool {
        // Node is a partition rather than a filter: a route that states none
        // serves task dispatch alone.
        match (&self.nodes, s.node) {
            (None, None) => {}
            (None, Some(_)) | (Some(_), None) => return false,
            (Some(names), Some(node)) => {
                if !names.iter().any(|n| node_matches(n, node)) {
                    return false;
                }
            }
        }
        if let Some((lo, hi)) = self.lap
            && !(lo..=hi).contains(&s.lap)
        {
            return false;
        }
        if let Some(classes) = &self.classes
            && !classes.contains(&s.class)
        {
            return false;
        }
        if let Some((lo, hi)) = self.complexity
            && !(lo..=hi).contains(&s.complexity)
        {
            return false;
        }
        if let Some((lo, hi)) = self.tier {
            // An untiered project matches only a route that does not ask.
            match s.tier {
                Some(t) => {
                    if !(lo..=hi).contains(&i64::from(t)) {
                        return false;
                    }
                }
                None => return false,
            }
        }
        true
    }
}

impl Policy {
    /// The first route whose every stated condition holds. Order is the
    /// policy: a document is read top to bottom, like the file it came from.
    pub fn route(&self, s: &Subject<'_>) -> Option<&Route> {
        self.routes.iter().find(|r| r.matches(s))
    }

    /// Whether any route names this node. A read node needs one that states
    /// no class or complexity; an `edit` needs one of any kind. Tier and lap
    /// are left out: whether a route can serve a node at all is the question.
    pub fn names_node(&self, node: &str, edits: bool) -> bool {
        self.routes.iter().any(|r| {
            r.nodes
                .as_ref()
                .is_some_and(|names| names.iter().any(|n| node_matches(n, node)))
                && (edits || (r.classes.is_none() && r.complexity.is_none()))
        })
    }

    /// The first route serving a workflow node that changes no repository.
    /// Class and complexity describe a change, so a route stating either
    /// serves only `edit` nodes and tasks.
    pub fn route_read(&self, node: &str, lap: i64, tier: Option<u8>) -> Option<&Route> {
        let subject = Subject {
            class: Class::Specified,
            complexity: 0,
            tier,
            node: Some(node),
            lap,
        };
        self.routes
            .iter()
            .filter(|r| r.classes.is_none() && r.complexity.is_none())
            .find(|r| r.matches(&subject))
    }

    /// Reads a policy document, refusing anything it cannot apply exactly.
    /// A route that silently does nothing is worse than one that is refused.
    pub fn parse(text: &str) -> Result<Policy, String> {
        let v: Value = serde_json::from_str(text).map_err(|e| format!("not JSON: {e}"))?;
        let list = v
            .get("route")
            .and_then(Value::as_array)
            .ok_or("expected a `route` array")?;
        if list.is_empty() {
            return Err("a policy with no routes would refuse every dispatch".into());
        }
        let routes = list
            .iter()
            .enumerate()
            .map(|(i, r)| parse_route(i, r))
            .collect::<Result<Vec<_>, String>>()?;
        Ok(Policy { routes })
    }

    /// The document as stored, so an activation and a replay read the same
    /// text the author wrote.
    pub fn to_json(&self) -> String {
        let routes: Vec<Value> = self
            .routes
            .iter()
            .map(|r| {
                let mut m = serde_json::Map::new();
                m.insert("name".into(), r.name.clone().into());
                let mut cond = serde_json::Map::new();
                if let Some(c) = &r.classes {
                    cond.insert(
                        "class".into(),
                        c.iter().map(|c| c.name()).collect::<Vec<_>>().into(),
                    );
                }
                if let Some(n) = &r.nodes {
                    cond.insert("node".into(), n.clone().into());
                }
                if let Some((lo, hi)) = r.lap {
                    cond.insert("lap".into(), format!("{lo}-{hi}").into());
                }
                if let Some((lo, hi)) = r.complexity {
                    cond.insert("complexity".into(), format!("{lo}-{hi}").into());
                }
                if let Some((lo, hi)) = r.tier {
                    cond.insert("tier".into(), format!("{lo}-{hi}").into());
                }
                m.insert("match".into(), Value::Object(cond));
                if let Some(a) = &r.agent {
                    m.insert("agent".into(), a.clone().into());
                }
                if let Some(x) = &r.model {
                    m.insert("model".into(), x.clone().into());
                }
                if let Some(e) = &r.escalate {
                    m.insert(
                        "escalate".into(),
                        serde_json::json!({"model": e.model, "attempts": e.attempts}),
                    );
                }
                if let Some(s) = &r.scope {
                    m.insert("scope".into(), s.clone().into());
                }
                m.insert("approval".into(), r.approval.name().into());
                Value::Object(m)
            })
            .collect();
        serde_json::to_string_pretty(&serde_json::json!({ "route": routes })).unwrap_or_default()
    }
}

/// Refuses a key outside `known`. A misspelt condition would otherwise read
/// as absent, which widens the route to match everything.
fn known_keys(v: &Value, what: &str, known: &[&str]) -> Result<(), String> {
    let Value::Object(m) = v else {
        return Err(format!("{what} must be an object, not {v}"));
    };
    match m.keys().find(|k| !known.contains(&k.as_str())) {
        Some(k) => Err(format!(
            "unknown key `{k}` in {what}; expected one of {}",
            known.join(", ")
        )),
        None => Ok(()),
    }
}

/// A string field, or `None` when absent. Any other type is refused rather
/// than dropped.
fn text(v: &Value, key: &str) -> Result<Option<String>, String> {
    match &v[key] {
        Value::Null => Ok(None),
        Value::String(s) => Ok(Some(s.clone())),
        other => Err(format!("{key} must be a string, not {other}")),
    }
}

fn parse_route(i: usize, v: &Value) -> Result<Route, String> {
    let at = |e: String| format!("route {}: {e}", i + 1);
    known_keys(
        v,
        "a route",
        &[
            "name", "match", "agent", "model", "escalate", "scope", "approval",
        ],
    )
    .map_err(at)?;
    let name = text(v, "name")
        .map_err(at)?
        .unwrap_or_else(|| format!("#{}", i + 1));
    let cond = &v["match"];
    if !cond.is_null() {
        known_keys(
            cond,
            "match",
            &["class", "node", "lap", "complexity", "tier"],
        )
        .map_err(at)?;
    }
    let classes = match &cond["class"] {
        Value::Null => None,
        Value::String(s) => Some(vec![
            Class::parse(s).ok_or_else(|| at(format!("unknown class `{s}`")))?,
        ]),
        Value::Array(a) => Some(
            a.iter()
                .map(|c| {
                    c.as_str()
                        .and_then(Class::parse)
                        .ok_or_else(|| at(format!("unknown class `{c}`")))
                })
                .collect::<Result<Vec<_>, String>>()?,
        ),
        other => return Err(at(format!("class must be a name or a list, not {other}"))),
    };
    let nodes = match &cond["node"] {
        Value::Null => None,
        Value::String(s) => Some(vec![s.clone()]),
        Value::Array(a) => {
            let names = a
                .iter()
                .map(|n| {
                    n.as_str()
                        .map(String::from)
                        .ok_or_else(|| at("a node condition takes names".into()))
                })
                .collect::<Result<Vec<_>, String>>()?;
            if names.is_empty() {
                return Err(at("an empty node list matches nothing".into()));
            }
            Some(names)
        }
        other => return Err(at(format!("node must be a name or a list, not {other}"))),
    };
    // `bounds` is what the value can take, so a range outside it, which
    // would match nothing, is refused.
    let range = |key: &str, (min, max): (i64, i64)| -> Result<Option<(i64, i64)>, String> {
        let (lo, hi) = match &cond[key] {
            Value::Null => return Ok(None),
            Value::Number(n) => {
                let n = n
                    .as_i64()
                    .ok_or_else(|| at(format!("{key} must be whole")))?;
                (n, n)
            }
            Value::String(s) => {
                let (lo, hi) = s.split_once('-').unwrap_or((s, s));
                let lo: i64 = lo
                    .trim()
                    .parse()
                    .map_err(|_| at(format!("{key} `{s}` is not a range")))?;
                let hi: i64 = hi
                    .trim()
                    .parse()
                    .map_err(|_| at(format!("{key} `{s}` is not a range")))?;
                if lo > hi {
                    return Err(at(format!("{key} `{s}` is empty")));
                }
                (lo, hi)
            }
            other => {
                return Err(at(format!(
                    "{key} must be a number or a range, not {other}"
                )));
            }
        };
        if lo < min || hi > max {
            let bound = match max {
                i64::MAX => format!("at least {min}"),
                _ => format!("{min} to {max}"),
            };
            return Err(at(format!("{key} must be {bound}, not {}", cond[key])));
        }
        Ok(Some((lo, hi)))
    };
    let escalate = match &v["escalate"] {
        Value::Null => None,
        e => {
            known_keys(e, "escalate", &["model", "attempts"]).map_err(at)?;
            let model = text(e, "model")
                .map_err(at)?
                .ok_or_else(|| at("escalate needs a model".into()))?;
            let attempts = match &e["attempts"] {
                Value::Null => 1,
                a => a
                    .as_i64()
                    .filter(|n| (0..=1).contains(n))
                    .ok_or_else(|| at(format!("escalate attempts must be 0 or 1, not {a}")))?,
            };
            Some(Escalate { model, attempts })
        }
    };
    let scope = match &v["scope"] {
        Value::Null => None,
        Value::Array(a) => Some(
            a.iter()
                .map(|g| {
                    g.as_str()
                        .map(String::from)
                        .ok_or_else(|| at("scope globs must be strings".into()))
                })
                .collect::<Result<Vec<_>, String>>()?,
        ),
        _ => return Err(at("scope must be a list of globs".into())),
    };
    let approval = match v["approval"].as_str() {
        None => return Err(at("no approval mode; state one explicitly".into())),
        Some(s) => Approval::parse(s).ok_or_else(|| at(format!("unknown approval `{s}`")))?,
    };
    let route = Route {
        name,
        classes,
        nodes,
        lap: range("lap", (0, i64::MAX))?,
        complexity: range("complexity", (1, 5))?,
        tier: range("tier", (1, 5))?,
        agent: text(v, "agent").map_err(at)?,
        model: text(v, "model").map_err(at)?,
        escalate,
        scope,
        approval,
    };
    // A limit no policy may raise. Checked when the document is read, so an
    // unacceptable route cannot be stored, let alone activated.
    if route.approval == Approval::Unattended
        && route.classes.as_ref().is_none_or(|c| {
            c.iter()
                .any(|c| matches!(c, Class::Privileged | Class::Judgment | Class::Never))
        })
    {
        return Err(at(
            "unattended needs an explicit class list, and never covers A-, C or D".into(),
        ));
    }
    Ok(route)
}

/// What a candidate policy would have done to the runs already recorded.
/// The comparison reads each run's own snapshot, so a task edited, retiered,
/// rescanned or reworked since does not change the answer.
pub struct Difference {
    pub run: i64,
    pub was: String,
    pub would_be: String,
}

/// `runs` are compared by the route each would match now. A run dispatched
/// before any policy existed has no recorded route; it is reported as `-`,
/// which is a difference worth seeing rather than a match.
pub fn replay(policy: &Policy, runs: &[crate::store::Run]) -> (Vec<Difference>, usize) {
    let mut differences = Vec::new();
    let mut compared = 0;
    for run in runs {
        let (Some(class), Some(complexity)) = (run.class, run.complexity) else {
            continue;
        };
        compared += 1;
        let subject = Subject {
            class,
            complexity,
            tier: run.tier,
            node: run.node.as_deref(),
            lap: run.lap,
        };
        let was = describe(
            run.route.as_deref(),
            run.agent.as_str(),
            run.model.as_deref(),
            run.approval,
            &run.scope,
        );
        let would_be = match policy.route(&subject) {
            None => "refused: no route matches".to_string(),
            Some(r) => describe(
                Some(&r.name),
                r.agent.as_deref().unwrap_or(&run.agent),
                r.model.as_deref().or(run.model.as_deref()),
                Some(r.approval),
                r.scope.as_ref().unwrap_or(&class.scope()),
            ),
        };
        if was != would_be {
            differences.push(Difference {
                run: run.id,
                was,
                would_be,
            });
        }
    }
    (differences, compared)
}

fn describe(
    route: Option<&str>,
    agent: &str,
    model: Option<&str>,
    approval: Option<Approval>,
    scope: &[String],
) -> String {
    format!(
        "{} {agent}{} {}{}",
        route.unwrap_or("-"),
        model.map_or(String::new(), |m| format!("/{m}")),
        approval.map_or("-", Approval::name),
        match scope {
            [] => String::new(),
            globs => format!(" in {}", globs.join(",")),
        }
    )
}

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

    /// A change to approval or scope changes what happens to a run, so a
    /// replay that saw only the route, agent and model would call it a match.
    #[test]
    fn replay_compares_approval_and_scope() {
        let policy = |approval: &str, scope: &str| {
            Policy::parse(&format!(
                r#"{{"route":[{{"name":"r","match":{{}},"approval":"{approval}"{scope}}}]}}"#
            ))
            .unwrap()
        };
        let run = crate::store::Run {
            id: 1,
            agent: "claude".into(),
            class: Some(Class::Specified),
            complexity: Some(3),
            route: Some("r".into()),
            approval: Some(Approval::Each),
            scope: Class::Specified.scope(),
            ..crate::store::Run::blank()
        };
        let runs = [run];
        assert!(replay(&policy("each", ""), &runs).0.is_empty());
        assert_eq!(replay(&policy("batch", ""), &runs).0.len(), 1);
        let (d, _) = replay(&policy("each", r#","scope":["src/**"]"#), &runs);
        assert!(d[0].would_be.ends_with("in src/**"), "{}", d[0].would_be);
    }

    const DOC: &str = r#"{
      "route": [
        {"name": "chores", "match": {"class": "A", "complexity": "1-2"},
         "agent": "claude", "model": "haiku",
         "escalate": {"model": "sonnet", "attempts": 1},
         "approval": "batch"},
        {"name": "specified", "match": {"class": ["B"], "complexity": "3-4", "tier": "1-3"},
         "model": "sonnet", "approval": "each"},
        {"name": "rest", "match": {}, "approval": "propose"}
      ]
    }"#;

    fn subject(class: Class, complexity: i64, tier: Option<u8>) -> Subject<'static> {
        Subject {
            class,
            complexity,
            tier,
            node: None,
            lap: 0,
        }
    }

    fn at_node<'a>(node: &'a str, lap: i64) -> Subject<'a> {
        Subject {
            node: Some(node),
            lap,
            ..subject(Class::Specified, 3, Some(1))
        }
    }

    #[test]
    fn the_first_matching_route_wins() {
        let p = Policy::parse(DOC).unwrap();
        let named = |s| p.route(&s).unwrap().name.clone();
        assert_eq!(named(subject(Class::Mechanical, 1, Some(4))), "chores");
        assert_eq!(named(subject(Class::Specified, 3, Some(1))), "specified");
        // Right class, complexity outside the range.
        assert_eq!(named(subject(Class::Specified, 5, Some(1))), "rest");
        // Right class and complexity, tier outside it.
        assert_eq!(named(subject(Class::Specified, 3, Some(5))), "rest");
        // A condition that is not stated does not narrow anything.
        assert_eq!(named(subject(Class::Judgment, 5, None)), "rest");
    }

    /// Node is a partition, not a filter: an existing policy keeps serving
    /// task dispatch and does not absorb a workflow's nodes into its
    /// catch-all, which would route them at whatever approval it names.
    #[test]
    fn a_node_route_and_a_task_route_do_not_overlap() {
        let doc = r#"{
          "route": [
            {"name": "audits", "match": {"node": "*/audit"}, "model": "opus", "approval": "each"},
            {"name": "fixes", "match": {"node": ["repair/fix"], "lap": "1-2"},
             "model": "sonnet", "approval": "batch"},
            {"name": "tasks", "match": {}, "approval": "propose"}
          ]
        }"#;
        let p = Policy::parse(doc).unwrap();
        let named = |s: Subject<'_>| p.route(&s).map(|r| r.name.clone());

        // A task names no node, so only the node-less route serves it.
        assert_eq!(
            named(subject(Class::Specified, 3, Some(1))).as_deref(),
            Some("tasks")
        );
        // A node is served by a node route, and never by the catch-all.
        assert_eq!(named(at_node("issues/audit", 0)).as_deref(), Some("audits"));
        assert_eq!(named(at_node("repair/fix", 1)).as_deref(), Some("fixes"));
        // `*/audit` matches the leaf wherever it was called from; an exact
        // name does not.
        assert_eq!(named(at_node("other/audit", 0)).as_deref(), Some("audits"));
        assert_eq!(named(at_node("other/fix", 1)), None, "no route serves it");
        // Lap narrows: the first attempt at `repair/fix` matches nothing.
        assert_eq!(named(at_node("repair/fix", 0)), None);
    }

    /// A node that edits nothing has no class or complexity, so only a node
    /// route that states neither serves it, and a task route never does.
    #[test]
    fn a_read_node_takes_a_node_route_that_states_no_class() {
        let policy = Policy::parse(
            r#"{"route": [
            {"name": "edits", "match": {"node": "*/review", "class": "B"}, "model": "opus", "approval": "each"},
            {"name": "reads", "match": {"node": "*/review", "lap": "0"}, "model": "haiku", "approval": "each"},
            {"name": "tasks", "approval": "each"}
        ]}"#,
        )
        .unwrap();
        let named = |node: &str, lap: i64| {
            policy
                .route_read(node, lap, Some(1))
                .map(|r| r.name.clone())
        };
        assert_eq!(named("look/review", 0).as_deref(), Some("reads"));
        assert_eq!(named("look/review", 1), None, "outside the lap range");
        assert_eq!(
            named("look/confirm", 0),
            None,
            "the catch-all serves tasks only"
        );
    }

    #[test]
    fn a_node_is_named_by_a_route_that_can_serve_it() {
        let policy = Policy::parse(
            r#"{"route": [
            {"match": {"node": "*/fix", "class": "B"}, "approval": "each"},
            {"match": {"node": "look/review"}, "approval": "each"},
            {"approval": "each"}
        ]}"#,
        )
        .unwrap();
        assert!(policy.names_node("look/review", false));
        assert!(
            policy.names_node("repair/fix", true),
            "an edit takes a class route"
        );
        assert!(
            !policy.names_node("repair/fix", false),
            "a read node does not"
        );
        assert!(
            !policy.names_node("look/confirm", false),
            "the catch-all names no node"
        );
    }

    #[test]
    fn an_empty_node_list_is_refused() {
        let e =
            Policy::parse(r#"{"route":[{"match":{"node":[]},"approval":"each"}]}"#).unwrap_err();
        assert!(e.contains("matches nothing"), "{e}");
    }

    /// A route that asks about tier cannot match a project without one.
    #[test]
    fn an_untiered_project_matches_only_routes_that_do_not_ask() {
        let p = Policy::parse(DOC).unwrap();
        assert_eq!(
            p.route(&subject(Class::Specified, 3, None)).unwrap().name,
            "rest"
        );
    }

    #[test]
    fn a_policy_that_matches_nothing_is_refused_rather_than_empty() {
        let p = Policy {
            routes: vec![Route {
                name: "narrow".into(),
                classes: Some(vec![Class::Mechanical]),
                nodes: None,
                lap: None,
                complexity: None,
                tier: None,
                agent: None,
                model: None,
                escalate: None,
                scope: None,
                approval: Approval::Each,
            }],
        };
        assert!(p.route(&subject(Class::Specified, 3, Some(1))).is_none());
        assert!(Policy::parse(r#"{"route": []}"#).is_err());
        assert!(Policy::parse(r#"{"routes": []}"#).is_err());
    }

    #[test]
    fn a_document_round_trips_through_its_stored_form() {
        let p = Policy::parse(DOC).unwrap();
        assert_eq!(Policy::parse(&p.to_json()), Ok(p));
    }

    #[test]
    fn unreadable_routes_are_refused_with_their_position() {
        for (doc, why) in [
            (
                r#"{"route":[{"match":{},"approval":"maybe"}]}"#,
                "unknown approval",
            ),
            (r#"{"route":[{"match":{}}]}"#, "no approval mode"),
            (
                r#"{"route":[{"match":{"class":"Z"},"approval":"each"}]}"#,
                "unknown class",
            ),
            (
                r#"{"route":[{"match":{"complexity":"4-2"},"approval":"each"}]}"#,
                "is empty",
            ),
            (
                r#"{"route":[{"match":{"complexity":"low"},"approval":"each"}]}"#,
                "not a range",
            ),
            (
                r#"{"route":[{"match":{},"escalate":{"attempts":1},"approval":"each"}]}"#,
                "escalate needs a model",
            ),
            // A misspelt key would read as absent and match everything.
            (
                r#"{"route":[{"match":{"clas":"A"},"approval":"each"}]}"#,
                "unknown key `clas` in match",
            ),
            (
                r#"{"route":[{"match":{"complexty":"1-2"},"approval":"each"}]}"#,
                "unknown key `complexty`",
            ),
            (
                r#"{"route":[{"match":{},"modle":"haiku","approval":"each"}]}"#,
                "unknown key `modle` in a route",
            ),
            (
                r#"{"route":[{"match":{},"escalate":{"model":"opus","attempt":1},"approval":"each"}]}"#,
                "unknown key `attempt` in escalate",
            ),
            (
                r#"{"route":[{"match":"A","approval":"each"}]}"#,
                "match must be an object",
            ),
            (r#"{"route":["A"]}"#, "a route must be an object"),
            (
                r#"{"route":[{"match":{},"model":4,"approval":"each"}]}"#,
                "model must be a string",
            ),
            (
                r#"{"route":[{"match":{},"agent":["claude"],"approval":"each"}]}"#,
                "agent must be a string",
            ),
            (
                r#"{"route":[{"name":7,"match":{},"approval":"each"}]}"#,
                "name must be a string",
            ),
            (
                r#"{"route":[{"match":{},"escalate":{"model":"opus","attempts":3},"approval":"each"}]}"#,
                "attempts must be 0 or 1",
            ),
            (
                r#"{"route":[{"match":{"complexity":"4-9"},"approval":"each"}]}"#,
                "complexity must be 1 to 5",
            ),
            (
                r#"{"route":[{"match":{"tier":0},"approval":"each"}]}"#,
                "tier must be 1 to 5",
            ),
            (
                r#"{"route":[{"match":{"lap":-1},"approval":"each"}]}"#,
                "lap must be at least 0",
            ),
        ] {
            let e = Policy::parse(doc).unwrap_err();
            assert!(e.contains(why) && e.contains("route 1"), "{doc}: {e}");
        }
    }

    /// A limit no document may raise, refused where it is read rather than
    /// where it would be acted on.
    #[test]
    fn unattended_never_covers_a_privileged_or_judgment_class() {
        for class in ["A-", "C", "D"] {
            let doc = format!(
                r#"{{"route":[{{"match":{{"class":"{class}"}},"approval":"unattended"}}]}}"#
            );
            assert!(Policy::parse(&doc).is_err(), "{class}");
        }
        // An unstated class list would cover them all.
        assert!(Policy::parse(r#"{"route":[{"match":{},"approval":"unattended"}]}"#).is_err());
        assert!(
            Policy::parse(r#"{"route":[{"match":{"class":["A","B"]},"approval":"unattended"}]}"#)
                .is_ok()
        );
    }
}