Skip to main content

agentmux_srv_core/backend/storage/
skill_optout.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! An agent that opted out of a catalog skill that reaches everyone ("every agent" or "new
5//! agents"). The opt-out only cancels the reach; an explicit bind to that agent still gives it the
6//! skill. Rows live in `db_skill_optout`, in the identity store beside `db_skills`, created on first
7//! use without a schema bump (like `db_skill_reach`).
8
9use rusqlite::params;
10use std::collections::HashSet;
11
12use super::error::StoreError;
13use super::skills::Skill;
14use super::store::Store;
15
16const SCHEMA: &str = "CREATE TABLE IF NOT EXISTS db_skill_optout (
17        skill_id TEXT NOT NULL,
18        agent_id TEXT NOT NULL,
19        PRIMARY KEY (skill_id, agent_id)
20    );";
21
22impl Store {
23    /// Every `(skill_id, agent_id)` pair that opted out. Call on the catalog store.
24    pub fn skill_optout_set_all(&self) -> Result<HashSet<(String, String)>, StoreError> {
25        let conn = self.conn.lock().unwrap();
26        conn.execute_batch(SCHEMA)?;
27        let mut stmt = conn.prepare("SELECT skill_id, agent_id FROM db_skill_optout")?;
28        let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
29        Ok(rows.collect::<Result<HashSet<_>, _>>()?)
30    }
31
32    /// Opt an agent out of a skill's reach, or back in. Idempotent. Call on the catalog store.
33    pub fn skill_optout_put(&self, skill_id: &str, agent_id: &str, opted_out: bool) -> Result<(), StoreError> {
34        let conn = self.conn.lock().unwrap();
35        conn.execute_batch(SCHEMA)?;
36        if opted_out {
37            conn.execute("INSERT OR IGNORE INTO db_skill_optout (skill_id, agent_id) VALUES (?1, ?2)", params![skill_id, agent_id])?;
38        } else {
39            conn.execute("DELETE FROM db_skill_optout WHERE skill_id = ?1 AND agent_id = ?2", params![skill_id, agent_id])?;
40        }
41        Ok(())
42    }
43
44    /// Ids of the skills the agent's bundles hold. A bundle's skill is not the agent's reach, so an
45    /// opt-out does not cancel it. Call on the store that holds the agent.
46    pub fn skill_ids_via_bundles(&self, catalog: &Store, agent_id: &str) -> HashSet<String> {
47        let mut held: Vec<Skill> = Vec::new();
48        self.managed_union_bundle_refs(catalog, agent_id, &mut held);
49        held.into_iter().map(|s| s.id).collect()
50    }
51
52    /// Drop a deleted skill's opt-outs. Call on the catalog store.
53    pub fn skill_optout_forget(&self, skill_id: &str) -> Result<(), StoreError> {
54        let conn = self.conn.lock().unwrap();
55        conn.execute_batch(SCHEMA)?;
56        conn.execute("DELETE FROM db_skill_optout WHERE skill_id = ?1", params![skill_id])?;
57        Ok(())
58    }
59}
60
61#[cfg(test)]
62mod optout_tests {
63    use super::*;
64    use crate::backend::storage::skills::Skill;
65
66    fn stores() -> (Store, Store) {
67        let mstore = Store::open_in_memory().unwrap();
68        let catalog = Store::open_in_memory().unwrap();
69        catalog.apply_identity_schema_for_tests().unwrap();
70        (mstore, catalog)
71    }
72
73    fn global_skill(id: &str) -> Skill {
74        Skill {
75            id: id.to_string(),
76            name: format!("Skill {id}"),
77            trigger: String::new(),
78            skill_type: "agent-skill".to_string(),
79            description: "d".to_string(),
80            content: "c".to_string(),
81            is_global: true,
82            created_at: 1,
83            updated_at: 1,
84        }
85    }
86
87    fn agent(store: &Store, id: &str) {
88        store
89            .conn()
90            .lock()
91            .unwrap()
92            .execute("INSERT INTO db_agents (id, name, provider, created_at) VALUES (?1, ?1, 'claude', 1)", params![id])
93            .unwrap();
94    }
95
96    fn names(m: &Store, c: &Store, agent: &str) -> Vec<String> {
97        let mut v: Vec<String> = m.effective_skills(c, agent).into_iter().map(|s| s.name).collect();
98        v.sort();
99        v
100    }
101
102    #[test]
103    fn an_opt_out_cancels_the_reach_for_that_agent_only_and_a_bind_still_wins() {
104        let (m, c) = stores();
105        c.skill_upsert_unique_global(&global_skill("s1")).unwrap();
106        agent(&m, "a1");
107        agent(&m, "a2");
108        c.skill_set_reach("s1", true, false, 5).unwrap();
109        assert_eq!(names(&m, &c, "a1"), ["Skill s1"]);
110        assert_eq!(names(&m, &c, "a2"), ["Skill s1"]);
111
112        c.skill_optout_put("s1", "a1", true).unwrap();
113        assert!(names(&m, &c, "a1").is_empty(), "opted out of what reaches everyone");
114        assert_eq!(names(&m, &c, "a2"), ["Skill s1"], "the others still get it");
115        // The list the matrix reads says why.
116        let item = m.skill_list_global_for_agent(&c, "a1").unwrap().into_iter().find(|i| i.skill.id == "s1").unwrap();
117        assert!(!item.reached && item.opted_out && !item.bound_to_agent);
118
119        // An explicit bind is the person asking for it, so it wins over the opt-out.
120        m.skill_bind(&c, "a1", "s1").unwrap();
121        assert_eq!(names(&m, &c, "a1"), ["Skill s1"]);
122
123        c.skill_optout_put("s1", "a1", false).unwrap();
124        c.skill_optout_put("s1", "a1", false).unwrap(); // idempotent
125        assert!(c.skill_optout_set_all().unwrap().is_empty());
126    }
127
128    #[test]
129    fn a_skill_in_the_agents_bundle_is_given_whatever_the_opt_out_says_and_the_list_says_so() {
130        let (m, c) = stores();
131        c.skill_upsert_unique_global(&global_skill("s1")).unwrap();
132        agent(&m, "a1");
133        m.bundle_upsert(&crate::backend::storage::bundles::Bundle {
134            id: "b1".to_string(),
135            name: "Bundle b1".to_string(),
136            description: String::new(),
137            is_blank: false,
138            is_global: false,
139            provider: "claude".to_string(),
140            model: "anthropic".to_string(),
141            instructions: String::new(),
142            instructions_by_provider: "{}".to_string(),
143            context_files: "[]".to_string(),
144            mcp_servers: "[]".to_string(),
145            skills: "[]".to_string(),
146            sort_order: 0,
147            created_at: 1,
148            updated_at: 1,
149            is_system: false,
150        })
151        .unwrap();
152        m.agent_bundles_set("a1", &["b1".to_string()]).unwrap();
153        m.bundle_skill_bind(&c, &m, "b1", "s1").unwrap();
154        c.skill_set_reach("s1", true, false, 5).unwrap();
155        c.skill_optout_put("s1", "a1", true).unwrap();
156
157        assert_eq!(names(&m, &c, "a1"), ["Skill s1"], "the bundle still gives it");
158        let item = m.skill_list_global_for_agent(&c, "a1").unwrap().into_iter().find(|i| i.skill.id == "s1").unwrap();
159        assert!(item.via_bundle && !item.bound_to_agent);
160    }
161
162    #[test]
163    fn deleting_a_skill_drops_its_opt_outs() {
164        let (m, c) = stores();
165        c.skill_upsert_unique_global(&global_skill("s1")).unwrap();
166        c.skill_optout_put("s1", "a1", true).unwrap();
167        c.skill_optout_put("s2", "a1", true).unwrap();
168        m.skill_delete(&c, "s1").unwrap();
169        let left = c.skill_optout_set_all().unwrap();
170        assert_eq!(left.len(), 1);
171        assert!(left.contains(&("s2".to_string(), "a1".to_string())));
172    }
173}