polyc-capability 2026.7.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
#![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));
}

// ── 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]),
    ];
    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"
    );
}