polyc-capability 2026.8.0

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

use serde_json::json;

use super::*;

fn spec(name: &str) -> ToolSpec {
    ToolSpec::new(name, "d", json!({}))
}

fn profile(origin: ToolOrigin) -> ToolProfile {
    ToolProfile {
        origin,
        read_only: false,
        destructive: false,
        open_world: false,
    }
}

const fn set(caps: &[Capability]) -> CapabilitySet {
    let mut s = CapabilitySet::EMPTY;
    let mut i = 0;
    while i < caps.len() {
        s = s.with(caps[i]);
        i += 1;
    }
    s
}

// ── Set type ─────────────────────────────────────────────────────────────────

#[test]
fn set_algebra_is_sound() {
    let a = set(&[Capability::LocalRead, Capability::ArbitraryEgress]);
    let b = set(&[Capability::ArbitraryEgress, Capability::MutateExternal]);
    assert!(a.contains(Capability::LocalRead));
    assert!(!a.contains(Capability::MutateExternal));
    assert_eq!(
        a.union(b),
        set(&[
            Capability::LocalRead,
            Capability::ArbitraryEgress,
            Capability::MutateExternal
        ])
    );
    assert_eq!(a.intersection(b), set(&[Capability::ArbitraryEgress]));
    assert_eq!(a.difference(b), set(&[Capability::LocalRead]));
    assert!(set(&[Capability::LocalRead]).is_subset_of(a));
    assert!(!a.is_subset_of(b));
    assert!(CapabilitySet::EMPTY.is_empty());
    assert!(CapabilitySet::EMPTY.is_subset_of(CapabilitySet::EMPTY));
    // `all()` contains every member of the taxonomy.
    for c in Capability::ALL {
        assert!(
            CapabilitySet::all().contains(c),
            "{} missing from all()",
            c.as_str()
        );
    }
    // Iteration round-trips through FromIterator.
    let rebuilt: CapabilitySet = a.iter().collect();
    assert_eq!(rebuilt, a);
}

#[test]
fn names_round_trip_and_unknown_names_grant_nothing() {
    // Every capability's stable name parses back to itself.
    for c in Capability::ALL {
        assert_eq!(Capability::from_name(c.as_str()), Some(c), "{}", c.as_str());
    }
    assert_eq!(Capability::from_name("egress"), None);
    assert_eq!(Capability::from_name(""), None);

    // from_names: recognized names land in the set; unknown names are
    // reported, never granted (a typo in operator config grants nothing).
    let (parsed, unknown) =
        CapabilitySet::from_names(["arbitrary-egress", "definitely-not-a-capability", ""]);
    assert_eq!(parsed, set(&[Capability::ArbitraryEgress]));
    assert_eq!(
        unknown,
        vec!["definitely-not-a-capability".to_owned(), String::new()]
    );

    // names() is the inverse of from_names for valid input.
    let all_names = CapabilitySet::all().names();
    let (reparsed, unknown) = CapabilitySet::from_names(all_names);
    assert_eq!(reparsed, CapabilitySet::all());
    assert!(unknown.is_empty());
}

// ── Requirement derivation ────────────────────────────────────────────────────

// The derivation table, one row per annotation × origin combination that
// exists in the tool surface today (#591 acceptance).
#[test]
fn required_capabilities_maps_annotations_and_provenance() {
    // Sandbox-confined read-only built-in (file_read, grep, glob).
    let local_read = ToolProfile {
        read_only: true,
        ..profile(ToolOrigin::LocalSandbox)
    };
    assert_eq!(
        required_capabilities(local_read),
        set(&[Capability::LocalRead])
    );

    // Sandbox-confined mutating built-in (file_write, shell_exec) — even a
    // destructive one mutates only inside the box, so it stays local.
    let local_write = ToolProfile {
        destructive: true,
        ..profile(ToolOrigin::LocalSandbox)
    };
    assert_eq!(
        required_capabilities(local_write),
        set(&[Capability::LocalRead, Capability::LocalWrite])
    );

    // Open-world fetcher (web_fetch): arbitrary egress.
    let web = ToolProfile {
        read_only: true,
        open_world: true,
        ..profile(ToolOrigin::Fetcher)
    };
    assert_eq!(
        required_capabilities(web),
        set(&[Capability::ArbitraryEgress])
    );

    // Paying fetcher (paid_fetch, destructive): egress + external mutation.
    let paid = ToolProfile {
        destructive: true,
        open_world: true,
        ..profile(ToolOrigin::Fetcher)
    };
    assert_eq!(
        required_capabilities(paid),
        set(&[Capability::ArbitraryEgress, Capability::MutateExternal])
    );

    // Read-only operator-registered connector (service_list): fixed-connector
    // read only — the exemption that used to be a special case.
    let registered_read = ToolProfile {
        read_only: true,
        ..profile(ToolOrigin::RegisteredConnector)
    };
    assert_eq!(
        required_capabilities(registered_read),
        set(&[Capability::FixedConnectorRead])
    );

    // Open-world flag on a REGISTERED read-only connector affects ingestion
    // (taint), not the required set: the dial still goes to the one
    // operator-vouched endpoint (the service_status case, #585).
    let registered_open_read = ToolProfile {
        read_only: true,
        open_world: true,
        ..profile(ToolOrigin::RegisteredConnector)
    };
    assert_eq!(
        required_capabilities(registered_open_read),
        set(&[Capability::FixedConnectorRead])
    );

    // Mutating registered connector: reaches its endpoint AND mutates outside.
    let registered_mutating = profile(ToolOrigin::RegisteredConnector);
    assert_eq!(
        required_capabilities(registered_mutating),
        set(&[Capability::FixedConnectorRead, Capability::MutateExternal])
    );

    // Destructive dominates read_only for a connector (an incoherent
    // self-declaration must not shed the mutation requirement).
    let registered_destructive_read = ToolProfile {
        read_only: true,
        destructive: true,
        ..profile(ToolOrigin::RegisteredConnector)
    };
    assert_eq!(
        required_capabilities(registered_destructive_read),
        set(&[Capability::FixedConnectorRead, Capability::MutateExternal])
    );

    // First-party built-ins (history/wallet families): same shape as a
    // registered connector.
    let first_party_read = ToolProfile {
        read_only: true,
        ..profile(ToolOrigin::FirstParty)
    };
    assert_eq!(
        required_capabilities(first_party_read),
        set(&[Capability::FixedConnectorRead])
    );

    // Unclassifiable ⇒ the full privileged set, fail closed (#591 acceptance).
    let unknown = ToolProfile {
        read_only: true, // self-declared hints do not help an unknown origin
        ..profile(ToolOrigin::Unknown)
    };
    assert_eq!(required_capabilities(unknown), CapabilitySet::all());
}

#[test]
fn profile_reads_spec_annotations() {
    let s = spec("t").read_only().open_world();
    let p = ToolProfile::for_spec(&s, ToolOrigin::RegisteredConnector);
    assert!(p.read_only && p.open_world && !p.destructive);
    assert_eq!(p.origin, ToolOrigin::RegisteredConnector);
}

// A self-declared read-only, closed-world connector WITHOUT operator
// registration is not taint-immune: taint-immunity (fixed-connector read) is
// earned only by registry provenance, never by the connector's own hints
// (the MCP-spec rule, #592's trust scoping — pinned here in the pure core).
#[test]
fn self_declared_hints_never_earn_taint_immunity() {
    let self_declared = ToolProfile {
        read_only: true,
        ..profile(ToolOrigin::Unknown)
    };
    let required = required_capabilities(self_declared);
    // Requires the taint-revoked capabilities, so taint gates it.
    assert!(required.contains(Capability::ArbitraryEgress));
    assert!(required.contains(Capability::MutateExternal));
    let granted = granted_capabilities(GrantPolicy::default(), TaintState::Tainted);
    assert!(!required.is_subset_of(granted));
}

// ── Grant derivation ──────────────────────────────────────────────────────────

#[test]
fn taint_revokes_egress_and_external_mutation() {
    let policy = GrantPolicy::default();
    let clean = granted_capabilities(policy, TaintState::Clean);
    assert_eq!(clean, CapabilitySet::all());

    let tainted = granted_capabilities(policy, TaintState::Tainted);
    assert!(!tainted.contains(Capability::ArbitraryEgress));
    assert!(!tainted.contains(Capability::MutateExternal));
    // Everything else survives: local work and fixed-connector reads.
    assert!(tainted.contains(Capability::LocalRead));
    assert!(tainted.contains(Capability::LocalWrite));
    assert!(tainted.contains(Capability::FixedConnectorRead));
}

#[test]
fn taint_resilient_set_survives_only_when_policy_declares_it() {
    // Declared: arbitrary egress survives the subtraction.
    let resilient = GrantPolicy {
        base: CapabilitySet::all(),
        taint_resilient: set(&[Capability::ArbitraryEgress]),
    };
    let granted = granted_capabilities(resilient, TaintState::Tainted);
    assert!(granted.contains(Capability::ArbitraryEgress));
    // Only the declared capability survives — external mutation stays revoked.
    assert!(!granted.contains(Capability::MutateExternal));

    // Not declared (the default): nothing survives.
    let granted = granted_capabilities(GrantPolicy::default(), TaintState::Tainted);
    assert!(!granted.contains(Capability::ArbitraryEgress));

    // The resilient set never grants beyond the base policy.
    let narrow = GrantPolicy {
        base: set(&[Capability::LocalRead]),
        taint_resilient: set(&[Capability::ArbitraryEgress]),
    };
    for taint in [TaintState::Clean, TaintState::Tainted] {
        assert_eq!(
            granted_capabilities(narrow, taint),
            set(&[Capability::LocalRead]),
            "resilience must not mint a capability the base never granted"
        );
    }
}

// Monotonicity, exhaustively: under EVERY fixed policy (all 32×32
// base × taint-resilient combinations), adding taint never adds a capability
// (#591 acceptance).
#[test]
fn grants_are_monotonic_under_every_fixed_policy() {
    let all_sets = || {
        (0..32u8).map(|bits| {
            Capability::ALL
                .into_iter()
                .enumerate()
                .filter(|(i, _)| bits & (1 << i) != 0)
                .map(|(_, c)| c)
                .collect::<CapabilitySet>()
        })
    };
    for base in all_sets() {
        for resilient in all_sets() {
            let policy = GrantPolicy {
                base,
                taint_resilient: resilient,
            };
            let clean = granted_capabilities(policy, TaintState::Clean);
            let tainted = granted_capabilities(policy, TaintState::Tainted);
            assert!(
                tainted.is_subset_of(clean),
                "taint added a capability under base={:?} resilient={:?}",
                base.names(),
                resilient.names()
            );
            assert!(
                tainted.is_subset_of(base),
                "granted escaped the base policy under base={:?} resilient={:?}",
                base.names(),
                resilient.names()
            );
        }
    }
}

// ── Decision engine ───────────────────────────────────────────────────────────

#[test]
fn veto_takes_precedence_over_everything() {
    let policy = CallPolicy {
        veto: Some("path escapes the workspace".to_owned()),
        requires_human: true,
        sandbox_escalation: true,
        transform: ArgTransform::Rewrite("{}".to_owned()),
    };
    // Even a call missing capabilities denies rather than escalates: a human
    // approval cannot satisfy a hard policy veto.
    let out = decide(
        CapabilitySet::all(),
        CapabilitySet::EMPTY,
        &policy,
        "shell_exec",
    );
    assert_eq!(
        out,
        GateOutcome::Deny("path escapes the workspace".to_owned())
    );
}

#[test]
fn missing_capabilities_escalate_with_the_missing_set() {
    let required = set(&[Capability::ArbitraryEgress]);
    let granted = granted_capabilities(GrantPolicy::default(), TaintState::Tainted);
    let out = decide(required, granted, &CallPolicy::default(), "web_fetch");
    let GateOutcome::Escalate { reason, missing } = out else {
        panic!("expected escalate, got {out:?}");
    };
    assert_eq!(missing, set(&[Capability::ArbitraryEgress]));
    assert!(
        reason.contains("web_fetch"),
        "reason names the tool: {reason}"
    );
    assert!(!reason.is_empty());
}

#[test]
fn policy_gate_escalates_with_empty_missing_set_and_empty_reason() {
    // An intrinsic/argument-aware gate (requires_human) escalates even when
    // every capability is granted — with no missing set and no special
    // reason, so edges render their default prompt.
    let policy = CallPolicy {
        requires_human: true,
        ..CallPolicy::default()
    };
    let out = decide(
        set(&[Capability::LocalRead]),
        CapabilitySet::all(),
        &policy,
        "shell_exec",
    );
    assert_eq!(
        out,
        GateOutcome::Escalate {
            reason: String::new(),
            missing: CapabilitySet::EMPTY
        }
    );

    // Same for a sandbox-denial escalation.
    let policy = CallPolicy {
        sandbox_escalation: true,
        ..CallPolicy::default()
    };
    let out = decide(
        set(&[Capability::LocalWrite]),
        CapabilitySet::all(),
        &policy,
        "file_write",
    );
    assert!(matches!(out, GateOutcome::Escalate { missing, .. } if missing.is_empty()));
}

#[test]
fn allowed_calls_honor_the_argument_transform() {
    let granted = CapabilitySet::all();
    let required = set(&[Capability::LocalRead]);

    let out = decide(required, granted, &CallPolicy::default(), "file_read");
    assert_eq!(out, GateOutcome::Allow);

    let rewrite = CallPolicy {
        transform: ArgTransform::Rewrite(r#"{"path":"safe.txt"}"#.to_owned()),
        ..CallPolicy::default()
    };
    assert_eq!(
        decide(required, granted, &rewrite, "file_read"),
        GateOutcome::Modify(r#"{"path":"safe.txt"}"#.to_owned())
    );

    let inject = CallPolicy {
        transform: ArgTransform::InjectContext("note".to_owned()),
        ..CallPolicy::default()
    };
    assert_eq!(
        decide(required, granted, &inject, "file_read"),
        GateOutcome::InjectContext("note".to_owned())
    );

    // A transform never applies to an escalating call — the transform is
    // honored only when the call is otherwise allowed.
    let out = decide(
        CapabilitySet::all(),
        granted.difference(TAINT_REVOKED),
        &rewrite,
        "t",
    );
    assert!(matches!(out, GateOutcome::Escalate { .. }));
}

// The exhaustive table over required × granted: for EVERY pair of sets, the
// engine's outcome is pinned by pure subset algebra (no veto / policy gate).
#[test]
fn decision_table_is_exhaustive_over_required_and_granted() {
    let all_sets = || {
        (0..32u8).map(|bits| {
            Capability::ALL
                .into_iter()
                .enumerate()
                .filter(|(i, _)| bits & (1 << i) != 0)
                .map(|(_, c)| c)
                .collect::<CapabilitySet>()
        })
    };
    for required in all_sets() {
        for granted in all_sets() {
            let out = decide(required, granted, &CallPolicy::default(), "t");
            if required.is_subset_of(granted) {
                assert_eq!(
                    out,
                    GateOutcome::Allow,
                    "required={:?} granted={:?}",
                    required.names(),
                    granted.names()
                );
            } else {
                let GateOutcome::Escalate { missing, .. } = out else {
                    panic!(
                        "expected escalate for required={:?} granted={:?}",
                        required.names(),
                        granted.names()
                    );
                };
                assert_eq!(missing, required.difference(granted));
                assert!(!missing.is_empty());
            }
        }
    }
}

// The three rows that change behavior relative to the old OR-of-heuristics
// (#591 acceptance), driven through derivation + engine end-to-end.
#[test]
fn behavior_changing_rows_are_pinned() {
    let tainted_grants = granted_capabilities(GrantPolicy::default(), TaintState::Tainted);

    // Row 1: tainted × mutate-external × policy-would-allow ⇒ escalate.
    // (A mutating connector call under taint used to pass when base policy
    // allowed it — a message body is an exfiltration channel.)
    let mutating = required_capabilities(profile(ToolOrigin::RegisteredConnector));
    let out = decide(
        mutating,
        tainted_grants,
        &CallPolicy::default(),
        "send_message",
    );
    assert!(
        matches!(out, GateOutcome::Escalate { ref missing, .. } if missing.contains(Capability::MutateExternal)),
        "got {out:?}"
    );

    // Row 2: tainted × arbitrary-egress × taint-resilient policy ⇒ allow.
    let resilient_policy = GrantPolicy {
        base: CapabilitySet::all(),
        taint_resilient: set(&[Capability::ArbitraryEgress]),
    };
    let resilient_grants = granted_capabilities(resilient_policy, TaintState::Tainted);
    let fetch = required_capabilities(ToolProfile {
        read_only: true,
        open_world: true,
        ..profile(ToolOrigin::Fetcher)
    });
    assert_eq!(
        decide(fetch, resilient_grants, &CallPolicy::default(), "web_fetch"),
        GateOutcome::Allow
    );

    // Row 3: tainted × fixed-connector-read ⇒ allow (the read-only
    // first-party exemption, now structural instead of a carve-out).
    let read = required_capabilities(ToolProfile {
        read_only: true,
        ..profile(ToolOrigin::RegisteredConnector)
    });
    assert_eq!(
        decide(read, tainted_grants, &CallPolicy::default(), "service_list"),
        GateOutcome::Allow
    );
}

// Extending the taxonomy requires no decision-engine change: the engine is
// pure set algebra and never names a specific capability. Pinned by driving
// every single-member set through the same subset rule — a new member added
// to `Capability::ALL` automatically joins this loop (and the exhaustive
// tables above) with no edit to `decide`.
#[test]
fn engine_is_uniform_over_the_taxonomy() {
    for c in Capability::ALL {
        let single = CapabilitySet::of(c);
        let out = decide(single, CapabilitySet::EMPTY, &CallPolicy::default(), "t");
        assert!(
            matches!(out, GateOutcome::Escalate { missing, .. } if missing == single),
            "{}",
            c.as_str()
        );
        assert_eq!(
            decide(single, single, &CallPolicy::default(), "t"),
            GateOutcome::Allow,
            "{}",
            c.as_str()
        );
    }
}

// ── Annotation-monotonicity clamp (#598 seed) ────────────────────────────────

#[test]
fn redeclaration_only_ever_grows_the_required_set() {
    let origins = [
        ToolOrigin::LocalSandbox,
        ToolOrigin::Fetcher,
        ToolOrigin::FirstParty,
        ToolOrigin::RegisteredConnector,
        ToolOrigin::Unknown,
    ];
    let bools = [false, true];
    let mut profiles = Vec::new();
    for origin in origins {
        for read_only in bools {
            for destructive in bools {
                for open_world in bools {
                    profiles.push(ToolProfile {
                        origin,
                        read_only,
                        destructive,
                        open_world,
                    });
                }
            }
        }
    }
    // Exhaustive over old × new profiles: the clamped re-declaration never
    // shrinks the required set and never earns taint-immunity at runtime.
    for &old in &profiles {
        for &new in &profiles {
            let clamped = monotonic_redeclaration(old, new);
            let before = required_capabilities(old);
            let after = required_capabilities(clamped);
            assert!(
                before.is_subset_of(after),
                "re-declaration shrank requirements: old={old:?} new={new:?} clamped={clamped:?}"
            );
            // The specific downgrades called out in #598: open-world ⇒
            // closed-world and gaining read-only never take effect.
            assert!(
                !old.open_world || clamped.open_world,
                "open-world never downgrades to closed-world"
            );
            assert!(
                old.read_only || !clamped.read_only,
                "a tool never gains read-only at runtime"
            );
        }
    }

    // Growth still works: a connector declaring a new destructive tool grows
    // the requirement.
    let old = ToolProfile {
        read_only: true,
        ..profile(ToolOrigin::RegisteredConnector)
    };
    let new = ToolProfile {
        destructive: true,
        ..profile(ToolOrigin::RegisteredConnector)
    };
    let clamped = monotonic_redeclaration(old, new);
    assert!(required_capabilities(clamped).contains(Capability::MutateExternal));
}

// ── Access grant (the admin invite, #700) ─────────────────────────────────────

// The never-granted marker: `GrantAccess` is held out of the grantable
// taxonomy, so it is absent from `all()`, from the default grant in EVERY taint
// state, and from name parsing — no policy or wire input can seed it.
#[test]
fn grant_access_is_never_granted_by_any_input() {
    // Not in the grantable taxonomy, so not in `all()` (the default base and the
    // fail-closed requirement for an unknown tool).
    assert!(!Capability::ALL.contains(&Capability::GrantAccess));
    assert!(!CapabilitySet::all().contains(Capability::GrantAccess));

    // Never in a derived grant, for either taint state, under the default and
    // an all-granting policy alike.
    for policy in [
        GrantPolicy::default(),
        GrantPolicy {
            base: CapabilitySet::all(),
            taint_resilient: CapabilitySet::all(),
        },
    ] {
        for taint in [TaintState::Clean, TaintState::Tainted] {
            assert!(
                !granted_capabilities(policy, taint).contains(Capability::GrantAccess),
                "grant-access must never be granted (policy={policy:?}, taint={taint:?})"
            );
        }
    }

    // Unnameable in operator config: the name exists for display/telemetry but
    // cannot be parsed back INTO a grant, so a CR list can't confer it.
    assert_eq!(Capability::from_name("grant-access"), None);
    let (parsed, unknown) = CapabilitySet::from_names(["grant-access"]);
    assert!(parsed.is_empty(), "grant-access parses to nothing");
    assert_eq!(unknown, vec!["grant-access".to_owned()]);
}

// The load-bearing #700 invariant: the admin invite (an `AccessGrant`-origin
// tool) escalates for EVERY taint state and policy mode — a clean conversation
// included. This is the assertion that FAILS under #699's classification
// (invite as a first-party mutation, allowed on a clean context) and PASSES
// now.
#[test]
fn access_grant_always_escalates_in_every_state() {
    // The invite's requirement, regardless of how it declares itself.
    let required = required_capabilities(ToolProfile {
        read_only: false,
        destructive: true,
        open_world: true,
        ..profile(ToolOrigin::AccessGrant)
    });
    assert!(
        required.contains(Capability::GrantAccess),
        "an access-grant tool requires the never-granted marker"
    );

    for policy in [
        GrantPolicy::default(),
        GrantPolicy {
            base: CapabilitySet::all(),
            taint_resilient: CapabilitySet::all(),
        },
    ] {
        for taint in [TaintState::Clean, TaintState::Tainted] {
            let granted = granted_capabilities(policy, taint);
            let out = decide(required, granted, &CallPolicy::default(), "invite");
            // #699 regression: a clean conversation must NOT be an autonomous
            // allow.
            assert_ne!(out, GateOutcome::Allow, "policy={policy:?} taint={taint:?}");
            let GateOutcome::Escalate { reason, missing } = out else {
                panic!("expected escalate for policy={policy:?} taint={taint:?}");
            };
            assert!(
                missing.contains(Capability::GrantAccess),
                "the shortfall names the access-grant marker"
            );
            assert!(reason.contains("invite"), "reason names the tool: {reason}");
        }
    }
}

// The #713 sibling of `grant_access_is_never_granted_by_any_input`: the
// remove-access marker must be equally un-grantable, or the removal tool
// could stop escalating under some future policy/taint combination.
#[test]
fn revoke_access_is_never_granted_by_any_input() {
    // Not in the grantable taxonomy, so not in `all()` (the default base and
    // the fail-closed requirement for an unknown tool).
    assert!(!Capability::ALL.contains(&Capability::RevokeAccess));
    assert!(!CapabilitySet::all().contains(Capability::RevokeAccess));

    // Never in a derived grant, for either taint state, under the default and
    // an all-granting policy alike.
    for policy in [
        GrantPolicy::default(),
        GrantPolicy {
            base: CapabilitySet::all(),
            taint_resilient: CapabilitySet::all(),
        },
    ] {
        for taint in [TaintState::Clean, TaintState::Tainted] {
            assert!(
                !granted_capabilities(policy, taint).contains(Capability::RevokeAccess),
                "revoke-access must never be granted (policy={policy:?}, taint={taint:?})"
            );
        }
    }

    // Unnameable in operator config: the name exists for display/telemetry but
    // cannot be parsed back INTO a grant, so a CR list can't confer it.
    assert_eq!(Capability::from_name("revoke-access"), None);
    let (parsed, unknown) = CapabilitySet::from_names(["revoke-access"]);
    assert!(parsed.is_empty(), "revoke-access parses to nothing");
    assert_eq!(unknown, vec!["revoke-access".to_owned()]);
}

// The #713 sibling of `access_grant_always_escalates_in_every_state`: the
// remove-access tool (an `AccessRevoke`-origin tool) escalates for EVERY
// taint state and policy mode — a clean conversation included, exactly like
// the admin invite it mirrors.
#[test]
fn revoke_access_always_escalates_in_every_state() {
    let required = required_capabilities(ToolProfile {
        read_only: false,
        destructive: true,
        open_world: false,
        ..profile(ToolOrigin::AccessRevoke)
    });
    assert!(
        required.contains(Capability::RevokeAccess),
        "an access-revoke tool requires the never-granted marker"
    );

    for policy in [
        GrantPolicy::default(),
        GrantPolicy {
            base: CapabilitySet::all(),
            taint_resilient: CapabilitySet::all(),
        },
    ] {
        for taint in [TaintState::Clean, TaintState::Tainted] {
            let granted = granted_capabilities(policy, taint);
            let out = decide(required, granted, &CallPolicy::default(), "revoke");
            assert_ne!(out, GateOutcome::Allow, "policy={policy:?} taint={taint:?}");
            let GateOutcome::Escalate { reason, missing } = out else {
                panic!("expected escalate for policy={policy:?} taint={taint:?}");
            };
            assert!(
                missing.contains(Capability::RevokeAccess),
                "the shortfall names the revoke-access marker"
            );
            assert!(reason.contains("revoke"), "reason names the tool: {reason}");
        }
    }
}

// The #715 sibling of `revoke_access_is_never_granted_by_any_input`: the
// manage-admin marker must be equally un-grantable, or the demote tool could
// stop escalating under some future policy/taint combination.
#[test]
fn manage_admin_is_never_granted_by_any_input() {
    // Not in the grantable taxonomy, so not in `all()` (the default base and
    // the fail-closed requirement for an unknown tool).
    assert!(!Capability::ALL.contains(&Capability::ManageAdmin));
    assert!(!CapabilitySet::all().contains(Capability::ManageAdmin));

    // Never in a derived grant, for either taint state, under the default and
    // an all-granting policy alike.
    for policy in [
        GrantPolicy::default(),
        GrantPolicy {
            base: CapabilitySet::all(),
            taint_resilient: CapabilitySet::all(),
        },
    ] {
        for taint in [TaintState::Clean, TaintState::Tainted] {
            assert!(
                !granted_capabilities(policy, taint).contains(Capability::ManageAdmin),
                "manage-admin must never be granted (policy={policy:?}, taint={taint:?})"
            );
        }
    }

    // Unnameable in operator config: the name exists for display/telemetry but
    // cannot be parsed back INTO a grant, so a CR list can't confer it.
    assert_eq!(Capability::from_name("manage-admin"), None);
    let (parsed, unknown) = CapabilitySet::from_names(["manage-admin"]);
    assert!(parsed.is_empty(), "manage-admin parses to nothing");
    assert_eq!(unknown, vec!["manage-admin".to_owned()]);
}

// The #715 sibling of `revoke_access_always_escalates_in_every_state`: the
// demote tool (an `AdminManage`-origin tool) escalates for EVERY taint state
// and policy mode — a clean conversation included, exactly like the admin
// invite/revoke it completes the set alongside.
#[test]
fn manage_admin_always_escalates_in_every_state() {
    let required = required_capabilities(ToolProfile {
        read_only: false,
        destructive: true,
        open_world: false,
        ..profile(ToolOrigin::AdminManage)
    });
    assert!(
        required.contains(Capability::ManageAdmin),
        "an admin-manage tool requires the never-granted marker"
    );

    for policy in [
        GrantPolicy::default(),
        GrantPolicy {
            base: CapabilitySet::all(),
            taint_resilient: CapabilitySet::all(),
        },
    ] {
        for taint in [TaintState::Clean, TaintState::Tainted] {
            let granted = granted_capabilities(policy, taint);
            let out = decide(required, granted, &CallPolicy::default(), "demote");
            assert_ne!(out, GateOutcome::Allow, "policy={policy:?} taint={taint:?}");
            let GateOutcome::Escalate { reason, missing } = out else {
                panic!("expected escalate for policy={policy:?} taint={taint:?}");
            };
            assert!(
                missing.contains(Capability::ManageAdmin),
                "the shortfall names the manage-admin marker"
            );
            assert!(reason.contains("demote"), "reason names the tool: {reason}");
        }
    }
}

// ── Copy ──────────────────────────────────────────────────────────────────────

#[test]
fn escalation_reason_is_plain_language_on_every_shape() {
    let shapes = [
        set(&[Capability::ArbitraryEgress]),
        set(&[Capability::MutateExternal]),
        set(&[Capability::ArbitraryEgress, Capability::MutateExternal]),
        set(&[Capability::LocalWrite]),
        set(&[Capability::GrantAccess]),
    ];
    for missing in shapes {
        let reason = escalation_reason("my_tool", missing);
        assert!(reason.contains("my_tool"), "{reason}");
        // The user-facing copy rules: no internal jargon, no apology words.
        for banned in [
            "capability",
            "trifecta",
            "egress",
            "exfiltrat",
            "taint",
            "please",
            "sorry",
            "unfortunately",
        ] {
            assert!(
                !reason.to_lowercase().contains(banned),
                "banned word {banned:?} in {reason:?}"
            );
        }
    }
    // The wording is honest, not alarming: a lower-risk call reads as a
    // routine check, and the outcome labels are stable for telemetry.
    assert_eq!(GateOutcome::Allow.label(), "allow");
    assert_eq!(
        GateOutcome::Escalate {
            reason: String::new(),
            missing: CapabilitySet::EMPTY
        }
        .label(),
        "escalate"
    );
    assert_eq!(GateOutcome::Deny(String::new()).label(), "deny");
    assert_eq!(GateOutcome::Modify(String::new()).label(), "modify");
    assert_eq!(
        GateOutcome::InjectContext(String::new()).label(),
        "inject_context"
    );
}

// ── Deployment viability (#1415) ────────────────────────────────────────────────

#[test]
fn requirement_name_round_trips_through_from_name() {
    for req in Requirement::ALL {
        assert_eq!(Requirement::from_name(req.as_str()), Some(req));
    }
    assert_eq!(Requirement::from_name("no-such-requirement"), None);
}

#[test]
fn requirement_names_are_unique() {
    let mut names: Vec<&str> = Requirement::ALL.iter().map(|r| r.as_str()).collect();
    let before = names.len();
    names.sort_unstable();
    names.dedup();
    assert_eq!(
        names.len(),
        before,
        "every Requirement must have a distinct wire name"
    );
}

#[test]
fn deployment_capabilities_default_is_nothing_viable() {
    let caps = DeploymentCapabilities::default();
    for req in Requirement::ALL {
        assert!(
            !caps.is_viable(req),
            "{req:?} must not be viable by default"
        );
    }
    assert!(caps.viable_names().is_empty());
}

#[test]
fn deployment_capabilities_viable_names_round_trips_through_from_names() {
    let caps = DeploymentCapabilities {
        mail_relay: true,
        wallet_link_ceremony: false,
        email_magic_link_ceremony: true,
        payments_proxy: false,
        mandate_issuer: true,
    };
    let names = caps.viable_names();
    assert_eq!(
        names,
        vec![
            "mail-relay",
            "ceremony-page:email-magic-link",
            "mandate-issuer"
        ]
    );
    assert_eq!(DeploymentCapabilities::from_names(names), caps);
}

#[test]
fn deployment_capabilities_from_names_ignores_unknown_entries() {
    let caps = DeploymentCapabilities::from_names(["mail-relay", "not-a-real-requirement"]);
    assert!(caps.mail_relay);
    assert!(!caps.payments_proxy);
}

#[test]
fn all_viable_is_true_only_when_every_requirement_is_met() {
    let caps = DeploymentCapabilities {
        mail_relay: true,
        payments_proxy: false,
        ..DeploymentCapabilities::default()
    };
    assert!(
        caps.all_viable(&[]),
        "an empty requirement list is always viable"
    );
    assert!(caps.all_viable(&[Requirement::MailRelay]));
    assert!(!caps.all_viable(&[Requirement::MailRelay, Requirement::PaymentsProxy]));
    assert!(!caps.all_viable(&[Requirement::PaymentsProxy]));
}