Skip to main content

agent_hub_runtime/core/skill_store/
membership.rs

1use super::*;
2
3impl SkillStore {
4    /// Apply an entire membership batch or leave the database unchanged.
5    ///
6    /// Group membership is **exclusive**: each skill belongs to at most one
7    /// group.  When `add` is true the skill is first removed from any other
8    /// group it currently belongs to (within the same transaction) before the
9    /// insert.  The set of displaced scenario-ids is returned so the caller
10    /// can update the corresponding metadata files.
11    pub fn set_scenario_memberships(
12        &self,
13        scenario_id: &str,
14        skill_ids: &[String],
15        add: bool,
16    ) -> Result<Vec<String>> {
17        let conn = self.conn.lock().unwrap();
18        let tx = conn.unchecked_transaction()?;
19        let now = chrono::Utc::now().timestamp_millis();
20        let mut displaced_scenarios: Vec<String> = Vec::new();
21        for skill_id in skill_ids {
22            let exists: bool = tx.query_row(
23                "SELECT EXISTS(SELECT 1 FROM skills WHERE id = ?1)",
24                params![skill_id],
25                |row| row.get(0),
26            )?;
27            if !exists {
28                anyhow::bail!("Skill not found: {skill_id}");
29            }
30            if add {
31                let mut stmt = tx.prepare(
32                    "SELECT scenario_id FROM scenario_skills WHERE skill_id = ?1 AND scenario_id != ?2",
33                )?;
34                let old: Vec<String> = stmt
35                    .query_map(params![skill_id, scenario_id], |row| row.get(0))?
36                    .filter_map(|r| r.ok())
37                    .collect();
38                displaced_scenarios.extend(old);
39                tx.execute(
40                    "DELETE FROM scenario_skills WHERE skill_id = ?1 AND scenario_id != ?2",
41                    params![skill_id, scenario_id],
42                )?;
43                tx.execute(
44                    "INSERT OR IGNORE INTO scenario_skills (scenario_id, skill_id, added_at) VALUES (?1, ?2, ?3)",
45                    params![scenario_id, skill_id, now],
46                )?;
47            } else {
48                tx.execute(
49                    "DELETE FROM scenario_skills WHERE scenario_id = ?1 AND skill_id = ?2",
50                    params![scenario_id, skill_id],
51                )?;
52            }
53        }
54        tx.commit()?;
55        displaced_scenarios.sort_unstable();
56        displaced_scenarios.dedup();
57        Ok(displaced_scenarios)
58    }
59}