Skip to main content

agentmux_srv_core/backend/storage/
skill_reach.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Who a catalog (global) skill reaches beyond the agents it is bound to: every agent, and/or every
5//! agent created from a given time. The switches live in `db_skill_reach`, in the identity store
6//! beside `db_skills`, so they survive an upgrade (like `db_mcp_server_reach`). Read when an
7//! agent's files are written (`Store::effective_skills`), so no hook on agent creation is needed.
8
9use rusqlite::params;
10use std::collections::HashMap;
11
12use super::error::StoreError;
13use super::store::Store;
14
15/// The table, created on first use in the store that holds the catalog: it is added without a
16/// schema version bump, like `db_mcp_server_reach` (an older build ignores it, a newer one
17/// creates it), and no migration file grows for it.
18const SCHEMA: &str = "CREATE TABLE IF NOT EXISTS db_skill_reach (
19        skill_id         TEXT PRIMARY KEY,
20        all_agents       INTEGER NOT NULL DEFAULT 0,
21        new_agents_since INTEGER NOT NULL DEFAULT 0,
22        updated_at       INTEGER NOT NULL DEFAULT 0
23    );";
24
25/// Who a catalog (global) skill reaches beyond its binds, from `db_skill_reach`. The default, no
26/// row, is "only the agents it is bound to". Same shape as an MCP server's reach
27/// (`McpServerReach`), with a second switch for the agents to come.
28#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
29pub struct SkillReach {
30    /// Every agent, the existing ones and those created later.
31    pub all_agents: bool,
32    /// Every agent created at or after this time (unix ms), when "new agents get it" was switched
33    /// on. 0: off. Read when the agent's files are written, so no hook on agent creation is needed.
34    pub new_agents_since: i64,
35}
36
37impl SkillReach {
38    /// Whether an agent created at `agent_created_at` gets the skill without a bind.
39    pub fn reaches(&self, agent_created_at: i64) -> bool {
40        self.all_agents || (self.new_agents_since > 0 && agent_created_at >= self.new_agents_since)
41    }
42}
43
44impl Store {
45    /// Every catalog skill's reach, by skill id. Call on the catalog store (the identity store),
46    /// where `db_skill_reach` sits beside `db_skills`.
47    pub fn skill_reach_map(&self) -> Result<HashMap<String, SkillReach>, StoreError> {
48        let conn = self.conn.lock().unwrap();
49        conn.execute_batch(SCHEMA)?;
50        let mut stmt = conn.prepare("SELECT skill_id, all_agents, new_agents_since FROM db_skill_reach")?;
51        let rows = stmt.query_map([], |row| {
52            Ok((
53                row.get::<_, String>(0)?,
54                SkillReach { all_agents: row.get::<_, i64>(1)? != 0, new_agents_since: row.get::<_, i64>(2)? },
55            ))
56        })?;
57        Ok(rows.collect::<Result<HashMap<_, _>, _>>()?)
58    }
59
60    /// Set who a catalog skill reaches. Call on the catalog store; the caller checks the skill is a
61    /// global row. Switching "new agents" on starts at `now_ms` and keeps its start when it is
62    /// already on, so setting `all_agents` later does not make older agents count as new.
63    pub fn skill_set_reach(&self, skill_id: &str, all_agents: bool, new_agents: bool, now_ms: i64) -> Result<(), StoreError> {
64        let conn = self.conn.lock().unwrap();
65        conn.execute_batch(SCHEMA)?;
66        conn.execute(
67            "INSERT INTO db_skill_reach (skill_id, all_agents, new_agents_since, updated_at)
68             VALUES (?1, ?2, CASE WHEN ?3 THEN ?4 ELSE 0 END, ?4)
69             ON CONFLICT(skill_id) DO UPDATE SET
70                all_agents = excluded.all_agents,
71                new_agents_since = CASE WHEN ?3 = 0 THEN 0
72                                        WHEN db_skill_reach.new_agents_since > 0 THEN db_skill_reach.new_agents_since
73                                        ELSE ?4 END,
74                updated_at = excluded.updated_at",
75            params![skill_id, all_agents as i64, new_agents as i64, now_ms],
76        )?;
77        Ok(())
78    }
79
80    /// A new catalog skill reaches the agents created after it, unless it already has a reach: the
81    /// default is that new agents get the global skills, with a per-skill opt-out. Call on the catalog store.
82    pub fn skill_reach_default_for_new(&self, skill_id: &str, now_ms: i64) -> Result<(), StoreError> {
83        if !self.skill_reach_map()?.contains_key(skill_id) {
84            self.skill_set_reach(skill_id, false, true, now_ms)?;
85        }
86        Ok(())
87    }
88
89    /// Drop a deleted skill's reach. Call on the catalog store.
90    pub fn skill_reach_forget(&self, skill_id: &str) -> Result<(), StoreError> {
91        let conn = self.conn.lock().unwrap();
92        conn.execute_batch(SCHEMA)?;
93        conn.execute("DELETE FROM db_skill_reach WHERE skill_id = ?1", params![skill_id])?;
94        Ok(())
95    }
96}
97
98#[cfg(test)]
99mod reach_tests {
100    use super::*;
101    use crate::backend::storage::skills::Skill;
102
103    fn stores() -> (Store, Store) {
104        let mstore = Store::open_in_memory().unwrap();
105        let catalog = Store::open_in_memory().unwrap();
106        catalog.apply_identity_schema_for_tests().unwrap();
107        (mstore, catalog)
108    }
109
110    fn global_skill(id: &str) -> Skill {
111        Skill {
112            id: id.to_string(),
113            name: format!("Skill {id}"),
114            trigger: String::new(),
115            skill_type: "agent-skill".to_string(),
116            description: "d".to_string(),
117            content: "c".to_string(),
118            is_global: true,
119            created_at: 1,
120            updated_at: 1,
121        }
122    }
123
124    fn agent_created_at(store: &Store, id: &str, created_at: i64) {
125        store
126            .conn()
127            .lock()
128            .unwrap()
129            .execute("INSERT INTO db_agents (id, name, provider, created_at) VALUES (?1, ?1, 'claude', ?2)", params![id, created_at])
130            .unwrap();
131    }
132
133    fn names(m: &Store, c: &Store, agent: &str) -> Vec<String> {
134        let mut v: Vec<String> = m.effective_skills(c, agent).into_iter().map(|s| s.name).collect();
135        v.sort();
136        v
137    }
138
139    #[test]
140    fn a_catalog_skill_reaches_only_its_bound_agents_until_switched_on_for_all() {
141        let (m, c) = stores();
142        agent_created_at(&m, "a1", 100);
143        agent_created_at(&m, "a2", 200);
144        c.skill_upsert_unique_global(&global_skill("s1")).unwrap();
145        m.skill_bind(&c, "a1", "s1").unwrap();
146        assert_eq!(names(&m, &c, "a1").len(), 1);
147        assert!(names(&m, &c, "a2").is_empty(), "being in the catalog reaches no one");
148        c.skill_set_reach("s1", true, false, 1_000).unwrap();
149        assert_eq!(names(&m, &c, "a2").len(), 1, "every agent, bound or not");
150        c.skill_set_reach("s1", false, false, 2_000).unwrap();
151        assert!(names(&m, &c, "a2").is_empty());
152        assert_eq!(names(&m, &c, "a1").len(), 1, "a bind is kept when the reach goes off");
153    }
154
155    #[test]
156    fn new_agents_get_a_skill_switched_on_for_them_and_older_agents_do_not() {
157        let (m, c) = stores();
158        agent_created_at(&m, "old", 100);
159        c.skill_upsert_unique_global(&global_skill("s1")).unwrap();
160        c.skill_set_reach("s1", false, true, 1_000).unwrap();
161        agent_created_at(&m, "new", 1_500);
162        assert!(names(&m, &c, "old").is_empty(), "an agent from before the switch is not new");
163        assert_eq!(names(&m, &c, "new").len(), 1);
164        // Switching "all agents" on later does not move the start; off again leaves the new ones.
165        c.skill_set_reach("s1", true, true, 5_000).unwrap();
166        c.skill_set_reach("s1", false, true, 6_000).unwrap();
167        assert_eq!(c.skill_reach_map().unwrap()["s1"].new_agents_since, 1_000);
168        assert!(names(&m, &c, "old").is_empty());
169        assert_eq!(names(&m, &c, "new").len(), 1);
170        // Opting out stops it for every agent that only had it through "new agents".
171        c.skill_set_reach("s1", false, false, 7_000).unwrap();
172        assert!(names(&m, &c, "new").is_empty());
173    }
174
175    #[test]
176    fn the_catalog_and_the_agents_list_say_how_a_skill_reaches() {
177        let (m, c) = stores();
178        agent_created_at(&m, "a1", 100);
179        c.skill_upsert_unique_global(&global_skill("s1")).unwrap();
180        c.skill_set_reach("s1", true, true, 50).unwrap();
181        let item = m.skill_list_global(&c).unwrap().into_iter().next().unwrap();
182        assert!(item.all_agents && item.new_agents);
183        let for_agent = m.skill_list_global_for_agent(&c, "a1").unwrap().into_iter().next().unwrap();
184        assert!(for_agent.reached && !for_agent.bound_to_agent);
185    }
186
187    #[test]
188    fn deleting_a_skill_drops_its_reach() {
189        let (m, c) = stores();
190        c.skill_upsert_unique_global(&global_skill("s1")).unwrap();
191        c.skill_set_reach("s1", true, true, 50).unwrap();
192        assert!(m.skill_delete(&c, "s1").unwrap());
193        assert!(c.skill_reach_map().unwrap().is_empty());
194    }
195}