Skip to main content

mur_common/agent/
entitlements.rs

1use super::*;
2
3#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
4pub struct Entitlements {
5    pub network: NetworkEntitlement,
6    pub filesystem: FilesystemEntitlement,
7    pub processes: ProcessesEntitlement,
8    #[serde(default)]
9    pub syscalls: SyscallsEntitlement,
10    #[serde(default)]
11    pub limits: LimitsEntitlement,
12    /// LLM call permission. Default = Allowed (back-compat). Bridges set to Off
13    /// so the supervisor refuses to construct an LLM client.
14    #[serde(default)]
15    pub llm: crate::bridge::llm_entitlement::LlmEntitlement,
16    /// Per-tool allow/ask/deny policy. Empty = all tools use default (Ask).
17    #[serde(default, skip_serializing_if = "Vec::is_empty")]
18    pub tools: Vec<ToolRule>,
19    /// When `true` (the default), a sandbox apply failure is fatal: the agent
20    /// refuses to start rather than running advisory-only (unconfined).
21    /// Set to `false` only for development or trusted-workstation agents that
22    /// intentionally run without kernel sandbox enforcement.
23    #[serde(default = "default_true")]
24    pub fail_closed_on_sandbox_error: bool,
25    /// SSH agent proxy policy. Lives under `entitlements` so the entitlement
26    /// pin covers it — on Linux the pin is the only tamper protection.
27    #[serde(default, skip_serializing_if = "SshEntitlement::is_empty")]
28    pub ssh: SshEntitlement,
29}
30
31/// Default-deny allowlist of key fingerprints and, per key, host-key
32/// fingerprints. Fingerprints are the only identities; labels are display only.
33#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
34pub struct SshEntitlement {
35    #[serde(default, skip_serializing_if = "Vec::is_empty")]
36    pub keys: Vec<SshKeyRule>,
37}
38
39impl SshEntitlement {
40    pub fn is_empty(&self) -> bool {
41        self.keys.is_empty()
42    }
43}
44
45#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
46pub struct SshKeyRule {
47    pub fingerprint: String,
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    pub label: Option<String>,
50    #[serde(default, skip_serializing_if = "Vec::is_empty")]
51    pub allow_hosts: Vec<SshHostRule>,
52}
53
54#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
55#[serde(from = "SshHostRuleWire")]
56pub struct SshHostRule {
57    pub host_key: String,
58    #[serde(default, skip_serializing_if = "Option::is_none")]
59    pub label: Option<String>,
60    /// The `known_hosts` entries the user confirmed for this host key, one
61    /// per name it was added under (`mur agent ssh allow --host`): an alias
62    /// or another port can present the same key, and each name needs its own
63    /// line. Kept so the CLI can regenerate `<agent home>/ssh/known_hosts` on
64    /// every later allow / revoke. Never read by the runtime and never used
65    /// for matching: `host_key` is the only host identity. Empty for a rule
66    /// added by fingerprint alone.
67    #[serde(default, skip_serializing_if = "Vec::is_empty")]
68    pub known_hosts: Vec<SshKnownHost>,
69}
70
71impl SshHostRule {
72    /// Add `kh` unless an identical entry is already confirmed. Returns
73    /// whether it was added.
74    pub fn confirm_known_host(&mut self, kh: SshKnownHost) -> bool {
75        if self.known_hosts.contains(&kh) {
76            return false;
77        }
78        self.known_hosts.push(kh);
79        true
80    }
81}
82
83/// On-disk shape of [`SshHostRule`]. Also accepts the single `known_host`
84/// field written before `known_hosts` existed, so a profile saved by that
85/// build still parses, still matches its pin (the pin is compared after a
86/// round-trip through this schema) and keeps its entry.
87#[derive(Deserialize)]
88struct SshHostRuleWire {
89    host_key: String,
90    #[serde(default)]
91    label: Option<String>,
92    #[serde(default)]
93    known_hosts: Vec<SshKnownHost>,
94    #[serde(default)]
95    known_host: Option<SshKnownHost>,
96}
97
98impl From<SshHostRuleWire> for SshHostRule {
99    fn from(w: SshHostRuleWire) -> Self {
100        let mut rule = SshHostRule {
101            host_key: w.host_key,
102            label: w.label,
103            known_hosts: w.known_hosts,
104        };
105        if let Some(kh) = w.known_host {
106            rule.confirm_known_host(kh);
107        }
108        rule
109    }
110}
111
112/// One confirmed `known_hosts` line: `<host> <key_type> <key_base64>`.
113#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
114pub struct SshKnownHost {
115    /// As written in `known_hosts`: `name`, or `[name]:port` off port 22.
116    pub host: String,
117    pub key_type: String,
118    pub key_base64: String,
119}
120
121#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
122pub struct NetworkEntitlement {
123    pub inbound: InboundNetwork,
124    pub outbound: OutboundNetwork,
125}
126
127#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
128pub struct InboundNetwork {
129    #[serde(default)]
130    pub ports: Vec<u16>,
131}
132
133#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
134pub struct OutboundNetwork {
135    pub mode: NetworkOutboundMode,
136    #[serde(default)]
137    pub allow_hosts: Vec<String>,
138    /// Extra outbound TCP ports granted on top of the built-in web set
139    /// (`RESTRICTED_GENERAL_PORTS`: 80/443/8080/8443). Issue #006: without
140    /// this, a non-web port (ssh 2222, vite 5173, ollama 11434) was
141    /// unreachable under `restricted` and the only escape was
142    /// `unrestricted`, which opens EVERY port.
143    ///
144    /// Honored under `Restricted` ONLY. `Off` stays air-gapped and
145    /// `ProxyOnly` keeps denying general TCP — a stale entry in a profile
146    /// whose mode was later tightened must never silently reopen it.
147    ///
148    /// This is a PORT grant, not a host grant: like the base set, the port
149    /// opens to host `*`, because macOS SBPL's `remote tcp` accepts only
150    /// `*` or `localhost` as the host. Bounding WHICH host is reached on
151    /// that port remains HostGuard's job via `allow_hosts`.
152    #[serde(default, skip_serializing_if = "Vec::is_empty")]
153    pub allow_ports: Vec<u16>,
154    #[serde(default = "default_protocols")]
155    pub protocols: Vec<String>,
156    #[serde(default)]
157    pub resolve_dns: ResolveDnsConfig,
158}
159fn default_protocols() -> Vec<String> {
160    vec!["tcp".to_string()]
161}
162
163/// Record of who authorized a broad egress grant, and when. Attached to a
164/// per-MCP-server `McpServerNetwork` when its mode is `BroadAudited`, so the
165/// grant is persisted, portable, and re-approvable on import.
166#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
167pub struct EgressAuthorization {
168    pub authorized_by: String,
169    pub authorized_at_ms: u64,
170}
171
172#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
173#[serde(rename_all = "lowercase")]
174pub enum NetworkOutboundMode {
175    Unrestricted,
176    Restricted,
177    /// Deny all general outbound TCP; egress is ONLY via loopback proxies
178    /// (the agent's cc-proxy LLM port + the egress proxy). Hostnames are still
179    /// governed by `allow_hosts` (HostGuard) — unlike `Off`, which blocks all.
180    ProxyOnly,
181    Off,
182}
183
184#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
185pub struct ResolveDnsConfig {
186    #[serde(default = "default_dns_mode")]
187    pub mode: String,
188    #[serde(default)]
189    pub servers: Vec<String>,
190}
191impl Default for ResolveDnsConfig {
192    fn default() -> Self {
193        Self {
194            mode: default_dns_mode(),
195            servers: vec![],
196        }
197    }
198}
199fn default_dns_mode() -> String {
200    "system".to_string()
201}
202
203/// Dirs under `<mur_home>` where MUR objects are authored.
204///
205/// The seeded concierge gets read+write on these; without them the one agent a
206/// fresh host has can describe a skill or workflow but cannot create one, and
207/// every answer ends in "run this command yourself".
208///
209/// Deliberately excludes `agents/`: `self_protected()` only covers an agent's
210/// OWN `profile.yaml` + `identity.key`, so write access there would let an
211/// agent author a sibling with unrestricted entitlements and start it, and
212/// read access would expose every other agent's Ed25519 signing key.
213///
214/// Deliberately excludes [`crate::paths::FLEETS`] for the same reason one
215/// level up: `fleet.yaml` names a fleet's members, limits and HITL
216/// pre-approvals, and `.stopped` is the operator's kill-switch. An agent that
217/// can write there can widen what a `fleet_run` it triggers is allowed to do,
218/// or clear the stop on it. Fleets are created with `mur fleet create`; the
219/// runtime already reads `fleets/` on its own (sandbox policy), so dropping
220/// the grant costs the concierge nothing it needs to *use* a fleet.
221pub const AUTHORING_DIRS: [&str; 3] = ["skills", "workflows", "artifacts"];
222
223/// The user's own credential directories, denied in every profile MUR writes.
224///
225/// SSH keys, cloud credentials and the GPG keyring: an agent has no reason to
226/// read any of them, and holding one is acting as the user on every host it
227/// unlocks. The agent wizard presets and the seeded concierge template both
228/// start from this list, so a new agent never ships with an empty deny.
229///
230/// `~`-relative on purpose — the CLI expands it at write time, and this list
231/// must mean the same thing on every install.
232pub const DEFAULT_DENY_PATHS: [&str; 3] = ["~/.ssh", "~/.aws", "~/.gnupg"];
233
234#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
235pub struct FilesystemEntitlement {
236    #[serde(default)]
237    pub read: Vec<String>,
238    #[serde(default)]
239    pub write: Vec<String>,
240    #[serde(default)]
241    pub deny: Vec<String>,
242}
243
244#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
245pub struct ProcessesEntitlement {
246    pub spawn: SpawnEntitlement,
247}
248
249#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
250pub struct SpawnEntitlement {
251    pub mode: SpawnMode,
252    #[serde(default)]
253    pub allowed: Vec<String>,
254    /// Directories whose entire subtree may be exec'd — the "build lane".
255    ///
256    /// `allowed` cannot express a toolchain that compiles its own
257    /// executables: a Rust build execs `target/debug/build/<crate>-<hash>/
258    /// build-script-build`, proc-macro shims, and freshly linked test
259    /// binaries, all at paths that do not exist until the build creates them
260    /// and change on every dependency bump. Without this an agent granted
261    /// `cargo` could compile nothing and could never verify its own work.
262    ///
263    /// Grant narrowly — a build-output directory, not a source tree or a
264    /// home directory. Everything under it becomes exec'able, so the tree
265    /// should be one the agent already has write access to and nothing else
266    /// depends on. Filesystem and network entitlements still bound what the
267    /// executed code can reach.
268    #[serde(default)]
269    pub allowed_dirs: Vec<String>,
270}
271
272#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
273#[serde(rename_all = "lowercase")]
274pub enum SpawnMode {
275    Allowlist,
276    Any,
277    None,
278    /// Shell-only: fences the system exec paths (`/bin`, `/usr/bin`,
279    /// `/usr/lib`) that `Allowlist` mode exempts by default, so only the
280    /// resolved shell binary the `bash` tool itself spawns plus the
281    /// profile's own `spawn_allowed_paths`/`spawn_allowed_prefixes` may be
282    /// exec'd -- no other system binary (coreutils, `git`, etc.) is implied.
283    Strict,
284}
285
286#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
287pub struct SyscallsEntitlement {
288    #[serde(default = "default_syscalls_mode")]
289    pub mode: String,
290    #[serde(default)]
291    pub extra_deny: Vec<String>,
292}
293fn default_syscalls_mode() -> String {
294    "default".to_string()
295}
296
297#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
298pub struct LimitsEntitlement {
299    #[serde(default)]
300    pub cpu_seconds: Option<u64>,
301    #[serde(default = "default_memory_mb")]
302    pub memory_mb: u64,
303    #[serde(default = "default_fds")]
304    pub file_descriptors: u32,
305    #[serde(default = "default_procs")]
306    pub processes: u32,
307}
308fn default_memory_mb() -> u64 {
309    512
310}
311fn default_fds() -> u32 {
312    1024
313}
314fn default_procs() -> u32 {
315    32
316}
317
318#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
319#[serde(rename_all = "lowercase")]
320pub enum ToolPolicy {
321    Allow,
322    #[default]
323    Ask,
324    Deny,
325}
326
327#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
328pub struct ToolRule {
329    pub pattern: String,
330    pub policy: ToolPolicy,
331    /// Intrinsic risk tier of this tool (v3c). Resolved most-restrictive-wins
332    /// across every matching rule (see [`resolve_tool_risk`]); a tier above
333    /// `Write` turns `policy: allow` into a pre-execution approval (#1600).
334    /// `deny` still wins outright.
335    #[serde(default, skip_serializing_if = "Option::is_none")]
336    pub risk: Option<crate::hitl::RiskTier>,
337    /// #1786: opt this one rule out of the built-in tier floor (acting
338    /// browser tools ask even under a riskless `allow`). Default off; it never
339    /// lowers a declared `risk:` — that field only ever raises. Honored only
340    /// on an exact-name rule; on a glob it is ignored (`perm list-tools` and
341    /// `doctor` say so). The runtime logs every call where it waives a floor.
342    /// #1814: may also name a tier ("waive up to this tier"); on `bash` only
343    /// that form counts — see [`crate::hitl::floor_waiver`].
344    #[serde(
345        default,
346        skip_serializing_if = "crate::hitl::floor_waiver::FloorWaiver::is_off"
347    )]
348    pub bypass_builtin_tier_floor: crate::hitl::floor_waiver::FloorWaiver,
349}
350
351/// Resolve the effective policy for `tool_name` against an ordered rule list.
352///
353/// Precedence: exact-name match > longest-prefix glob (trailing `*`) > default (`Ask`).
354pub fn resolve_tool_policy(rules: &[ToolRule], tool_name: &str) -> ToolPolicy {
355    resolve_tool_policy_opt(rules, tool_name).unwrap_or_default()
356}
357
358/// Like [`resolve_tool_policy`] but distinguishes "no rule matched" (`None`)
359/// from an explicit rule — for tools whose registration is already gated
360/// elsewhere (e.g. `fleet_run`'s config allowlist) and that therefore want a
361/// different default than `Ask` while still honoring explicit rules.
362pub fn resolve_tool_policy_opt(rules: &[ToolRule], tool_name: &str) -> Option<ToolPolicy> {
363    resolve_tool_rule(rules, tool_name).map(|rule| rule.policy)
364}
365
366/// The single rule that decides `tool_name`'s policy (same precedence as
367/// [`resolve_tool_policy_opt`]); `None` = no rule matched. Per-rule switches
368/// such as `bypass_builtin_tier_floor` are read from this rule only.
369pub fn resolve_tool_rule<'a>(rules: &'a [ToolRule], tool_name: &str) -> Option<&'a ToolRule> {
370    for rule in rules {
371        if rule.pattern == tool_name {
372            return Some(rule);
373        }
374    }
375    let mut best: Option<(&ToolRule, usize)> = None;
376    for rule in rules {
377        if let Some(prefix) = rule.pattern.strip_suffix('*')
378            && tool_name.starts_with(prefix)
379        {
380            let len = prefix.len();
381            if best.is_none_or(|(_, best_len)| len > best_len) {
382                best = Some((rule, len));
383            }
384        }
385    }
386    best.map(|(rule, _)| rule)
387}
388
389/// The declared `risk:` that applies to `tool_name` — the STRICTEST across
390/// every matching rule (exact or trailing-`*` glob), so the field comment's
391/// most-restrictive-wins holds even when a narrower rule decided the policy.
392/// `None` = no matching rule declares a risk; the caller's own classification
393/// stands alone.
394pub fn resolve_tool_risk(rules: &[ToolRule], tool_name: &str) -> Option<crate::hitl::RiskTier> {
395    rules
396        .iter()
397        .filter(|rule| {
398            rule.pattern == tool_name
399                || rule
400                    .pattern
401                    .strip_suffix('*')
402                    .is_some_and(|prefix| tool_name.starts_with(prefix))
403        })
404        .filter_map(|rule| rule.risk)
405        .max()
406}
407
408#[cfg(test)]
409mod tool_policy_tests {
410    use super::*;
411
412    fn rules() -> Vec<ToolRule> {
413        vec![
414            ToolRule {
415                pattern: "mcp__github__merge_pr".into(),
416                policy: ToolPolicy::Ask,
417                risk: None,
418                bypass_builtin_tier_floor: Default::default(),
419            },
420            ToolRule {
421                pattern: "mcp__github__*".into(),
422                policy: ToolPolicy::Allow,
423                risk: None,
424                bypass_builtin_tier_floor: Default::default(),
425            },
426            ToolRule {
427                pattern: "mcp__*".into(),
428                policy: ToolPolicy::Deny,
429                risk: None,
430                bypass_builtin_tier_floor: Default::default(),
431            },
432            ToolRule {
433                pattern: "bash".into(),
434                policy: ToolPolicy::Allow,
435                risk: None,
436                bypass_builtin_tier_floor: Default::default(),
437            },
438        ]
439    }
440
441    fn risky(pattern: &str, policy: ToolPolicy, risk: RiskTier) -> ToolRule {
442        ToolRule {
443            pattern: pattern.into(),
444            policy,
445            risk: Some(risk),
446            bypass_builtin_tier_floor: Default::default(),
447        }
448    }
449
450    use crate::hitl::RiskTier;
451
452    /// #1600: most-restrictive-wins across EVERY matching rule, not just the
453    /// one whose policy won — a narrow `allow` must not shed a broad rule's
454    /// `destructive`.
455    #[test]
456    fn tool_risk_is_the_strictest_matching_rule() {
457        let rules = vec![
458            risky("mcp__browser__*", ToolPolicy::Allow, RiskTier::Destructive),
459            risky("mcp__browser__click", ToolPolicy::Allow, RiskTier::Write),
460            risky("mcp__other__*", ToolPolicy::Allow, RiskTier::Privileged),
461        ];
462        assert_eq!(
463            resolve_tool_risk(&rules, "mcp__browser__click"),
464            Some(RiskTier::Destructive)
465        );
466        assert_eq!(
467            resolve_tool_risk(&rules, "mcp__browser__navigate"),
468            Some(RiskTier::Destructive)
469        );
470    }
471
472    #[test]
473    fn tool_risk_is_none_without_a_declaring_rule() {
474        assert_eq!(resolve_tool_risk(&rules(), "mcp__github__merge_pr"), None);
475        assert_eq!(resolve_tool_risk(&[], "bash"), None);
476    }
477
478    #[test]
479    fn exact_beats_glob() {
480        assert_eq!(
481            resolve_tool_policy(&rules(), "mcp__github__merge_pr"),
482            ToolPolicy::Ask
483        );
484    }
485
486    #[test]
487    fn longer_glob_wins() {
488        assert_eq!(
489            resolve_tool_policy(&rules(), "mcp__github__create_issue"),
490            ToolPolicy::Allow
491        );
492    }
493
494    #[test]
495    fn shorter_glob_fallback() {
496        assert_eq!(
497            resolve_tool_policy(&rules(), "mcp__slack__send"),
498            ToolPolicy::Deny
499        );
500    }
501
502    #[test]
503    fn exact_bash() {
504        assert_eq!(resolve_tool_policy(&rules(), "bash"), ToolPolicy::Allow);
505    }
506
507    #[test]
508    fn unknown_tool_defaults_ask() {
509        assert_eq!(
510            resolve_tool_policy(&rules(), "unknown_tool"),
511            ToolPolicy::Ask
512        );
513    }
514
515    #[test]
516    fn empty_rules_defaults_ask() {
517        assert_eq!(resolve_tool_policy(&[], "bash"), ToolPolicy::Ask);
518    }
519
520    fn minimal_entitlements_yaml() -> &'static str {
521        "network:\n  inbound: {}\n  outbound:\n    mode: off\nfilesystem: {}\nprocesses:\n  spawn:\n    mode: none\n"
522    }
523
524    #[test]
525    fn entitlements_tools_defaults_empty() {
526        let e: Entitlements = serde_yaml_ng::from_str(minimal_entitlements_yaml()).unwrap();
527        assert!(e.tools.is_empty());
528    }
529
530    #[test]
531    fn entitlements_tools_roundtrip() {
532        let base = minimal_entitlements_yaml();
533        let yaml = format!("{base}tools:\n  - pattern: \"mcp__github__*\"\n    policy: allow\n");
534        let e: Entitlements = serde_yaml_ng::from_str(&yaml).unwrap();
535        assert_eq!(e.tools.len(), 1);
536        assert_eq!(e.tools[0].policy, ToolPolicy::Allow);
537        let y = serde_yaml_ng::to_string(&e).unwrap();
538        let back: Entitlements = serde_yaml_ng::from_str(&y).unwrap();
539        assert_eq!(back.tools.len(), 1);
540        assert_eq!(back.tools[0].policy, ToolPolicy::Allow);
541    }
542    #[test]
543    fn denylist_membership_and_mutation() {
544        let mut list: Vec<String> = vec![];
545        assert!(name_enabled(&list, "a"), "empty denylist => enabled");
546
547        set_denylist(&mut list, "a", false); // disable
548        assert!(!name_enabled(&list, "a"));
549        assert_eq!(list, ["a"]);
550
551        set_denylist(&mut list, "a", false); // idempotent disable
552        assert_eq!(list, ["a"], "no duplicate entries");
553
554        set_denylist(&mut list, "a", true); // enable removes
555        assert!(name_enabled(&list, "a"));
556        assert!(list.is_empty());
557
558        set_denylist(&mut list, "b", true); // enabling an absent name is a no-op
559        assert!(list.is_empty());
560    }
561
562    #[test]
563    fn addon_group_rule_truth_table() {
564        let mut p = crate::agent::AgentProfile::default_for_tests();
565        p.addons.push(AddonRef {
566            id: "grp".into(),
567            source: "claude-local:grp@1.0.0".into(),
568            enabled: false,
569            skills: vec!["g_skill".into()],
570            mcp: vec!["g_mcp".into()],
571            commands: vec!["g_cmd".into()],
572            content_hash: None,
573            fetch_ref: None,
574            fetch_plugin: None,
575        });
576
577        // 1. standalone item, no entry anywhere => enabled (back-compat)
578        assert!(p.skill_enabled("standalone"));
579        assert!(p.mcp_enabled("standalone_mcp"));
580
581        // 2. grouped item, group disabled => off (cannot enable one member of a disabled group)
582        assert!(!p.skill_enabled("g_skill"));
583        assert!(!p.mcp_enabled("g_mcp"));
584
585        // 3. grouped item, group enabled, name not denied => on
586        assert!(p.set_addon_enabled("grp", true));
587        assert!(p.skill_enabled("g_skill"));
588        assert!(p.mcp_enabled("g_mcp"));
589
590        // 4. name in denylist overrides an enabled group => off (silence one member)
591        p.set_skill_enabled("g_skill", false);
592        assert!(!p.skill_enabled("g_skill"));
593
594        // set_addon_enabled on a missing id reports false
595        assert!(!p.set_addon_enabled("nope", true));
596
597        // kill-switch: only flips group flags — no denylist push
598        p.disable_all_addons();
599        assert!(p.addons.iter().all(|g| !g.enabled));
600        assert!(!p.skill_enabled("g_skill"));
601        assert!(!p.skill_enabled("g_cmd"));
602        assert!(!p.mcp_enabled("g_mcp")); // mcp kill-switch asserted
603
604        // re-enable restores members — kill-switch is NOT sticky
605        // (g_skill was individually denied in step 4 above and stays off;
606        //  g_cmd and g_mcp were never individually denied so they come back on)
607        assert!(p.set_addon_enabled("grp", true));
608        assert!(!p.skill_enabled("g_skill")); // still individually denied from step 4
609        assert!(p.skill_enabled("g_cmd")); // restored: never individually denied
610        assert!(p.mcp_enabled("g_mcp")); // restored: never individually denied
611
612        // clearing the individual deny fully restores g_skill too
613        p.set_skill_enabled("g_skill", true);
614        assert!(p.skill_enabled("g_skill"));
615    }
616
617    #[test]
618    fn addon_ref_content_hash_and_fetch_ref_default_none_and_round_trip() {
619        // legacy AddonRef (no new fields) → None
620        let legacy = "id: a\nsource: claude-local:a@1\nenabled: false\n";
621        let r: AddonRef = serde_yaml_ng::from_str(legacy).unwrap();
622        assert_eq!(r.content_hash, None);
623        assert_eq!(r.fetch_ref, None);
624
625        // with the new fields → round-trips
626        let full = "id: a\nsource: claude-local:a@1\nenabled: true\ncontent_hash: abc123\nfetch_ref: owner/repo\n";
627        let r2: AddonRef = serde_yaml_ng::from_str(full).unwrap();
628        assert_eq!(r2.content_hash.as_deref(), Some("abc123"));
629        assert_eq!(r2.fetch_ref.as_deref(), Some("owner/repo"));
630        let back = serde_yaml_ng::to_string(&r2).unwrap();
631        let r3: AddonRef = serde_yaml_ng::from_str(&back).unwrap();
632        assert_eq!(r2, r3);
633    }
634}