1use rusqlite::params;
15use serde::{Deserialize, Serialize};
16
17use super::error::StoreError;
18use super::managed::{ManagedResource, Owner};
19use super::store::Store;
20
21#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
23#[ts(export, export_to = "../../../frontend/types/rpc/")]
24pub struct AgentSkill {
25 pub id: String,
26 pub agent_id: String,
27 pub name: String,
28 pub trigger: String,
29 pub skill_type: String,
33 pub description: String,
34 pub content: String,
35 #[ts(type = "number")]
36 pub created_at: i64,
37}
38
39impl Store {
40 pub(super) fn agent_skill_list_local(
45 &self,
46 agent_id: &str,
47 ) -> Result<Vec<AgentSkill>, StoreError> {
48 let conn = self.conn.lock().unwrap();
49 let mut stmt = conn.prepare(
50 "SELECT id, agent_id, name, trigger, skill_type, description, content, created_at
51 FROM db_agent_skills WHERE agent_id=?1 ORDER BY created_at ASC",
52 )?;
53 let rows = stmt.query_map(params![agent_id], |row| {
54 Ok(AgentSkill {
55 id: row.get(0)?,
56 agent_id: row.get(1)?,
57 name: row.get(2)?,
58 trigger: row.get(3)?,
59 skill_type: row.get(4)?,
60 description: row.get(5)?,
61 content: row.get(6)?,
62 created_at: row.get(7)?,
63 })
64 })?;
65 let mut skills = Vec::new();
66 for row in rows {
67 skills.push(row?);
68 }
69 Ok(skills)
70 }
71
72 pub fn agent_skill_list(&self, agent_id: &str) -> Result<Vec<AgentSkill>, StoreError> {
73 let local = self.agent_skill_list_local(agent_id)?;
74 if !local.is_empty() {
75 return Ok(local);
76 }
77 if self.agent_def_exists_local(agent_id)? {
81 return Ok(local);
82 }
83 if let Some(reg) = self.shared_def_registry() {
84 if let Ok(Some(rec)) = reg.get(agent_id) {
85 return Ok(rec
86 .data
87 .skills
88 .iter()
89 .map(|s| AgentSkill {
90 id: s.id.clone(),
91 agent_id: agent_id.to_string(),
92 name: s.name.clone(),
93 trigger: s.trigger.clone(),
94 skill_type: s.skill_type.clone(),
95 description: s.description.clone(),
96 content: s.content.clone(),
97 created_at: rec.data.created_at,
98 })
99 .collect());
100 }
101 }
102 Ok(local)
103 }
104
105 pub fn agent_skill_get(&self, id: &str) -> Result<Option<AgentSkill>, StoreError> {
107 let conn = self.conn.lock().unwrap();
108 let mut stmt = conn.prepare(
109 "SELECT id, agent_id, name, trigger, skill_type, description, content, created_at
110 FROM db_agent_skills WHERE id=?1",
111 )?;
112 let result = stmt.query_row(params![id], |row| {
113 Ok(AgentSkill {
114 id: row.get(0)?,
115 agent_id: row.get(1)?,
116 name: row.get(2)?,
117 trigger: row.get(3)?,
118 skill_type: row.get(4)?,
119 description: row.get(5)?,
120 content: row.get(6)?,
121 created_at: row.get(7)?,
122 })
123 });
124 match result {
125 Ok(skill) => Ok(Some(skill)),
126 Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
127 Err(e) => Err(StoreError::Sqlite(e)),
128 }
129 }
130
131 pub fn agent_skill_insert(&self, skill: &AgentSkill) -> Result<(), StoreError> {
133 {
134 let conn = self.conn.lock().unwrap();
135 conn.execute(
136 "INSERT INTO db_agent_skills (id, agent_id, name, trigger, skill_type, description, content, created_at)
137 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
138 params![
139 skill.id,
140 skill.agent_id,
141 skill.name,
142 skill.trigger,
143 skill.skill_type,
144 skill.description,
145 skill.content,
146 skill.created_at
147 ],
148 )?;
149 }
150 self.registry_def_refresh_if_mirrored(&skill.agent_id);
155 Ok(())
156 }
157
158 pub fn agent_skill_update(&self, skill: &AgentSkill) -> Result<bool, StoreError> {
160 let rows = {
161 let conn = self.conn.lock().unwrap();
162 conn.execute(
163 "UPDATE db_agent_skills SET name=?1, trigger=?2, skill_type=?3, description=?4, content=?5
164 WHERE id=?6",
165 params![
166 skill.name,
167 skill.trigger,
168 skill.skill_type,
169 skill.description,
170 skill.content,
171 skill.id
172 ],
173 )?
174 };
175 if rows > 0 {
179 self.registry_def_refresh_if_mirrored(&skill.agent_id);
180 }
181 Ok(rows > 0)
182 }
183
184 pub fn agent_skill_delete(&self, id: &str) -> Result<bool, StoreError> {
186 let (rows, agent_id) = {
187 let conn = self.conn.lock().unwrap();
188 let agent_id: Option<String> = match conn.query_row(
191 "SELECT agent_id FROM db_agent_skills WHERE id=?1",
192 params![id],
193 |row| row.get(0),
194 ) {
195 Ok(v) => Some(v),
196 Err(rusqlite::Error::QueryReturnedNoRows) => None,
197 Err(e) => return Err(StoreError::Sqlite(e)),
198 };
199 let rows = conn.execute("DELETE FROM db_agent_skills WHERE id=?1", params![id])?;
200 (rows, agent_id)
201 };
202 if rows > 0 {
206 if let Some(aid) = agent_id {
207 self.registry_def_refresh_if_mirrored(&aid);
208 }
209 }
210 Ok(rows > 0)
211 }
212}
213
214#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
221#[ts(export, export_to = "../../../frontend/types/rpc/")]
222pub struct Skill {
223 pub id: String,
224 pub name: String,
225 pub trigger: String,
226 pub skill_type: String,
227 pub description: String,
228 pub content: String,
229 pub is_global: bool,
230 #[ts(type = "number")]
231 pub created_at: i64,
232 #[ts(type = "number")]
233 pub updated_at: i64,
234}
235
236impl ManagedResource for Skill {
237 const TABLE: &'static str = "db_skills";
238 const REF_COL: &'static str = "skill_id";
239 const AGENT_REF_TABLE: &'static str = "db_agent_skills_ref";
240 const BUNDLE_REF_TABLE: &'static str = "db_bundle_skills_ref";
241 const COLUMNS: &'static [&'static str] = &[
242 "id", "name", "trigger", "skill_type", "description", "content", "is_global", "created_at", "updated_at",
243 ];
244 const UPDATE_COLUMNS: &'static [&'static str] =
245 &["name", "trigger", "skill_type", "description", "content", "updated_at"];
246 const NAME_NOUN: &'static str = "skill";
247 const ARTICLE_NOUN: &'static str = "a skill";
248 const KIND: &'static str = "skill";
249
250 fn from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Self> {
251 Ok(Skill {
252 id: row.get(0)?,
253 name: row.get(1)?,
254 trigger: row.get(2)?,
255 skill_type: row.get(3)?,
256 description: row.get(4)?,
257 content: row.get(5)?,
258 is_global: row.get::<_, i64>(6)? != 0,
259 created_at: row.get(7)?,
260 updated_at: row.get(8)?,
261 })
262 }
263 fn values(&self) -> Vec<rusqlite::types::Value> {
264 use rusqlite::types::Value;
265 vec![
266 Value::Text(self.id.clone()),
267 Value::Text(self.name.clone()),
268 Value::Text(self.trigger.clone()),
269 Value::Text(self.skill_type.clone()),
270 Value::Text(self.description.clone()),
271 Value::Text(self.content.clone()),
272 Value::Integer(if self.is_global { 1 } else { 0 }),
273 Value::Integer(self.created_at),
274 Value::Integer(self.updated_at),
275 ]
276 }
277 fn id(&self) -> &str {
278 &self.id
279 }
280 fn name(&self) -> &str {
281 &self.name
282 }
283 fn is_global(&self) -> bool {
284 self.is_global
285 }
286 fn updated_at(&self) -> i64 {
287 self.updated_at
288 }
289}
290
291#[derive(Debug, Clone, Serialize, ts_rs::TS)]
296#[ts(export, export_to = "../../../frontend/types/rpc/")]
297pub struct SkillListItem {
298 #[serde(flatten)]
299 pub skill: Skill,
300 pub bound_to_agent: bool,
301 #[serde(default)]
303 pub reached: bool,
304 pub opted_out: bool,
306 pub via_bundle: bool,
308}
309
310#[derive(Debug, Clone, Serialize, ts_rs::TS)]
314#[ts(export, export_to = "../../../frontend/types/rpc/")]
315pub struct SkillCatalogItem {
316 #[serde(flatten)]
317 pub skill: Skill,
318 #[ts(type = "number")]
319 pub bound_count: i64,
320 pub all_agents: bool,
322 pub new_agents: bool,
324 pub source: Option<super::skill_source::SkillSource>,
326 pub app: Option<super::skill_app::SkillApp>,
328}
329
330#[derive(Debug, Clone, Serialize, ts_rs::TS)]
335#[ts(export, export_to = "../../../frontend/types/rpc/")]
336pub struct SkillBundleListItem {
337 #[serde(flatten)]
338 pub skill: Skill,
339 pub bound_to_bundle: bool,
340}
341
342impl Store {
343 pub fn skill_list(&self, catalog: &Store, agent_id: &str) -> Result<Vec<SkillListItem>, StoreError> {
348 Ok(self
349 .managed_list::<Skill>(catalog, Owner::Agent, agent_id)?
350 .into_iter()
351 .map(|(skill, bound_to_agent)| SkillListItem { skill, bound_to_agent, reached: false, opted_out: false, via_bundle: false })
352 .collect())
353 }
354
355 pub fn effective_skills(&self, catalog: &Store, agent_id: &str) -> Vec<AgentSkill> {
378 let legacy_skills = self.agent_skill_list(agent_id).unwrap_or_default();
379 let (reach, optout) = (catalog.skill_reach_map().unwrap_or_default(), catalog.skill_optout_set_all().unwrap_or_default());
380 let agent_created_at = self.agent_def_get(agent_id).ok().flatten().map_or(0, |d| d.created_at);
381 let mut visible_skills: Vec<Skill> = self
382 .skill_list(catalog, agent_id)
383 .unwrap_or_default()
384 .into_iter()
385 .filter(|item| {
386 item.bound_to_agent
387 || !item.skill.is_global
388 || (reach.get(&item.skill.id).is_some_and(|r| r.reaches(agent_created_at))
389 && !optout.contains(&(item.skill.id.clone(), agent_id.to_string())))
390 })
391 .map(|item| item.skill)
392 .collect();
393 let has_own_skill_refs = visible_skills.iter().any(|s| !s.is_global);
403 self.managed_union_bundle_refs(catalog, agent_id, &mut visible_skills);
413 if has_own_skill_refs {
414 crate::backend::agent_config::skills_to_agent_skills(&visible_skills, agent_id)
415 } else {
416 let mut merged = legacy_skills;
417 merged.extend(crate::backend::agent_config::skills_to_agent_skills(&visible_skills, agent_id));
418 merged
419 }
420 }
421
422 pub fn skill_list_global(&self, catalog: &Store) -> Result<Vec<SkillCatalogItem>, StoreError> {
431 let (reach, sources, apps) = (catalog.skill_reach_map()?, catalog.skill_source_map()?, catalog.skill_app_map()?);
432 Ok(self
433 .managed_list_global::<Skill>(catalog)?
434 .into_iter()
435 .map(|(skill, bound_count)| {
436 let r = reach.get(&skill.id).copied().unwrap_or_default();
437 let (source, app) = (sources.get(&skill.id).cloned(), apps.get(&skill.id).cloned());
438 SkillCatalogItem { skill, bound_count, all_agents: r.all_agents, new_agents: r.new_agents_since > 0, source, app }
439 })
440 .collect())
441 }
442
443 pub fn skill_list_global_for_agent(&self, catalog: &Store, agent_id: &str) -> Result<Vec<SkillListItem>, StoreError> {
455 let (reach, optout, via) = (catalog.skill_reach_map()?, catalog.skill_optout_set_all()?, self.skill_ids_via_bundles(catalog, agent_id));
456 let agent_created_at = self.agent_def_get(agent_id).ok().flatten().map_or(0, |d| d.created_at);
457 Ok(self
458 .managed_list_global_for_agent::<Skill>(catalog, agent_id)?
459 .into_iter()
460 .map(|(skill, bound_to_agent)| {
461 let reaches = reach.get(&skill.id).is_some_and(|r| r.reaches(agent_created_at));
462 let opted_out = reaches && optout.contains(&(skill.id.clone(), agent_id.to_string()));
463 SkillListItem { via_bundle: via.contains(&skill.id), skill, bound_to_agent, reached: reaches && !opted_out, opted_out }
464 })
465 .collect())
466 }
467
468 pub fn skill_get(&self, id: &str) -> Result<Option<Skill>, StoreError> {
470 self.managed_get::<Skill>(id)
471 }
472
473 pub fn skill_delete(&self, catalog: &Store, id: &str) -> Result<bool, StoreError> {
476 let deleted = self.managed_delete::<Skill>(catalog, id)?;
477 catalog.skill_catalog_forget(id)?;
479 Ok(deleted)
480 }
481
482 pub fn skill_bind(&self, catalog: &Store, agent_id: &str, skill_id: &str) -> Result<(), StoreError> {
497 self.managed_bind_agent::<Skill>(catalog, agent_id, skill_id)
498 }
499
500 pub fn skill_unbind(&self, agent_id: &str, skill_id: &str) -> Result<bool, StoreError> {
502 self.managed_unbind::<Skill>(Owner::Agent, agent_id, skill_id)
503 }
504
505 pub fn skill_upsert_unique(
512 &self,
513 catalog: &Store,
514 agent_id: &str,
515 skill: &Skill,
516 bind_new: bool,
517 ) -> Result<(), StoreError> {
518 self.managed_upsert_unique(catalog, Owner::Agent, agent_id, skill, bind_new, None)
519 }
520
521 pub fn skill_upsert_unique_global(&self, skill: &Skill) -> Result<(), StoreError> {
530 self.managed_upsert_unique_global(skill)
531 }
532
533 pub(crate) fn skill_list_all_raw(&self) -> Result<Vec<Skill>, StoreError> {
546 let conn = self.conn.lock().unwrap();
547 let mut stmt = conn.prepare(
548 "SELECT id, name, trigger, skill_type, description, content, is_global, created_at, updated_at
549 FROM db_skills",
550 )?;
551 let rows = stmt.query_map([], |row| {
552 Ok(Skill {
553 id: row.get(0)?,
554 name: row.get(1)?,
555 trigger: row.get(2)?,
556 skill_type: row.get(3)?,
557 description: row.get(4)?,
558 content: row.get(5)?,
559 is_global: row.get::<_, i64>(6)? != 0,
560 created_at: row.get(7)?,
561 updated_at: row.get(8)?,
562 })
563 })?;
564 let mut out = Vec::new();
565 for r in rows {
566 out.push(r?);
567 }
568 Ok(out)
569 }
570
571 pub(crate) fn skill_insert_raw(&self, skill: &Skill) -> Result<usize, StoreError> {
579 let conn = self.conn.lock().unwrap();
580 let rows = conn.execute(
581 "INSERT OR IGNORE INTO db_skills
582 (id, name, trigger, skill_type, description, content, is_global, created_at, updated_at)
583 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
584 params![
585 skill.id,
586 skill.name,
587 skill.trigger,
588 skill.skill_type,
589 skill.description,
590 skill.content,
591 skill.is_global as i64,
592 skill.created_at,
593 skill.updated_at,
594 ],
595 )?;
596 Ok(rows)
597 }
598
599 pub(crate) fn skill_find_global_by_name(&self, name: &str) -> Result<Option<Skill>, StoreError> {
616 let conn = self.conn.lock().unwrap();
617 let mut stmt = conn.prepare(
618 "SELECT id, name, trigger, skill_type, description, content, is_global, created_at, updated_at
619 FROM db_skills
620 WHERE is_global = 1 AND name = ?1
621 LIMIT 1",
622 )?;
623 let result = stmt.query_row(params![name], |row| {
624 Ok(Skill {
625 id: row.get(0)?,
626 name: row.get(1)?,
627 trigger: row.get(2)?,
628 skill_type: row.get(3)?,
629 description: row.get(4)?,
630 content: row.get(5)?,
631 is_global: row.get::<_, i64>(6)? != 0,
632 created_at: row.get(7)?,
633 updated_at: row.get(8)?,
634 })
635 });
636 match result {
637 Ok(s) => Ok(Some(s)),
638 Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
639 Err(e) => Err(e.into()),
640 }
641 }
642
643 pub(crate) fn skill_rewrite_ref_id(&self, old_id: &str, new_id: &str) -> Result<usize, StoreError> {
672 if old_id == new_id {
673 return Ok(0);
674 }
675 let conn = self.conn.lock().unwrap();
676 conn.execute(
677 "INSERT OR IGNORE INTO db_agent_skills_ref (agent_id, skill_id)
678 SELECT agent_id, ?2 FROM db_agent_skills_ref WHERE skill_id = ?1",
679 params![old_id, new_id],
680 )?;
681 let agent = conn.execute("DELETE FROM db_agent_skills_ref WHERE skill_id = ?1", params![old_id])?;
682 conn.execute(
683 "INSERT OR IGNORE INTO db_bundle_skills_ref (bundle_id, skill_id)
684 SELECT bundle_id, ?2 FROM db_bundle_skills_ref WHERE skill_id = ?1",
685 params![old_id, new_id],
686 )?;
687 let bundle = conn.execute("DELETE FROM db_bundle_skills_ref WHERE skill_id = ?1", params![old_id])?;
688 Ok(agent + bundle)
689 }
690
691 pub fn skill_is_accessible_to(&self, catalog: &Store, agent_id: &str, skill_id: &str) -> Result<bool, StoreError> {
694 self.managed_is_accessible_to::<Skill>(catalog, Owner::Agent, agent_id, skill_id)
695 }
696
697 pub fn skill_is_bound_to(&self, agent_id: &str, skill_id: &str) -> Result<bool, StoreError> {
700 self.managed_is_bound_to::<Skill>(Owner::Agent, agent_id, skill_id)
701 }
702
703 pub fn bundle_skill_list(&self, catalog: &Store, bundle_id: &str) -> Result<Vec<SkillBundleListItem>, StoreError> {
712 Ok(self
713 .managed_list::<Skill>(catalog, Owner::Bundle, bundle_id)?
714 .into_iter()
715 .map(|(skill, bound_to_bundle)| SkillBundleListItem { skill, bound_to_bundle })
716 .collect())
717 }
718
719 pub fn bundle_skill_bind(&self, catalog: &Store, id_store: &Store, bundle_id: &str, skill_id: &str) -> Result<(), StoreError> {
730 self.managed_bind_bundle::<Skill>(catalog, id_store, bundle_id, skill_id)
731 }
732
733 pub fn bundle_skill_upsert_unique(
740 &self,
741 catalog: &Store,
742 id_store: &Store,
743 bundle_id: &str,
744 skill: &Skill,
745 bind_new: bool,
746 ) -> Result<(), StoreError> {
747 self.managed_upsert_unique_for_bundle(catalog, id_store, bundle_id, skill, bind_new)
748 }
749
750 pub fn bundle_skill_unbind(&self, bundle_id: &str, skill_id: &str) -> Result<bool, StoreError> {
752 self.managed_unbind::<Skill>(Owner::Bundle, bundle_id, skill_id)
753 }
754
755 pub fn bundle_skill_is_accessible_to(&self, catalog: &Store, bundle_id: &str, skill_id: &str) -> Result<bool, StoreError> {
758 self.managed_is_accessible_to::<Skill>(catalog, Owner::Bundle, bundle_id, skill_id)
759 }
760
761 pub fn bundle_skill_is_bound_to(&self, bundle_id: &str, skill_id: &str) -> Result<bool, StoreError> {
766 self.managed_is_bound_to::<Skill>(Owner::Bundle, bundle_id, skill_id)
767 }
768}
769
770#[cfg(test)]
771mod effective_skills_tests {
772 use super::*;
773 use crate::backend::storage::store::AgentDefinition;
774
775 pub(super) fn make_store() -> Store {
776 Store::open_in_memory().unwrap()
777 }
778
779 fn insert_agent(store: &Store, id: &str) {
780 let mut def = AgentDefinition {
781 slug: String::new(),
782 ..crate::backend::storage::agents::test_agent_def(id, "Test Agent", "claude", "host", 1_700_000_000_000, "")
783 };
784 store.agent_def_insert(&mut def).unwrap();
785 }
786
787 pub(super) fn global_skill(id: &str, name: &str) -> Skill {
788 Skill {
789 id: id.to_string(),
790 name: name.to_string(),
791 trigger: String::new(),
792 skill_type: "prompt".to_string(),
793 description: format!("{name} description"),
794 content: format!("{name} content"),
795 is_global: true,
796 created_at: 1_700_000_000_000,
797 updated_at: 1_700_000_000_000,
798 }
799 }
800
801 #[test]
802 fn falls_back_to_legacy_plus_globals_when_agent_has_no_own_refs() {
803 let store = make_store();
804 insert_agent(&store, "agent-1");
805
806 store.agent_skill_insert(&AgentSkill {
807 id: "legacy-1".to_string(),
808 agent_id: "agent-1".to_string(),
809 name: "Legacy Skill".to_string(),
810 trigger: "legacy".to_string(),
811 skill_type: "prompt".to_string(),
812 description: "legacy description".to_string(),
813 content: "legacy content".to_string(),
814 created_at: 1_700_000_000_000,
815 }).unwrap();
816
817 store.skill_upsert_unique_global(&global_skill("global-1", "Global Skill")).unwrap();
818 store.skill_bind(&store, "agent-1", "global-1").unwrap();
819 let effective = store.effective_skills(&store, "agent-1");
822 let names: Vec<&str> = effective.iter().map(|s| s.name.as_str()).collect();
823 assert_eq!(names.len(), 2, "expected legacy + global, got: {names:?}");
824 assert!(names.contains(&"Legacy Skill"));
825 assert!(names.contains(&"Global Skill"));
826 }
827
828 #[test]
829 fn own_refs_take_over_entirely_and_discard_legacy_skills() {
830 let store = make_store();
831 insert_agent(&store, "agent-1");
832
833 store.agent_skill_insert(&AgentSkill {
834 id: "legacy-1".to_string(),
835 agent_id: "agent-1".to_string(),
836 name: "Legacy Skill".to_string(),
837 trigger: "legacy".to_string(),
838 skill_type: "prompt".to_string(),
839 description: "legacy description".to_string(),
840 content: "legacy content".to_string(),
841 created_at: 1_700_000_000_000,
842 }).unwrap();
843
844 store.skill_upsert_unique_global(&global_skill("global-1", "Global Skill")).unwrap();
845 store.skill_bind(&store, "agent-1", "global-1").unwrap();
846
847 let own_skill = Skill {
850 id: "own-1".to_string(),
851 name: "Own Skill".to_string(),
852 trigger: String::new(),
853 skill_type: "agent-skill".to_string(),
854 description: "own description".to_string(),
855 content: "own content".to_string(),
856 is_global: false,
857 created_at: 1_700_000_000_000,
858 updated_at: 1_700_000_000_000,
859 };
860 store.skill_upsert_unique(&store, "agent-1", &own_skill, true).unwrap();
861
862 let effective = store.effective_skills(&store, "agent-1");
863 let names: Vec<&str> = effective.iter().map(|s| s.name.as_str()).collect();
864 assert_eq!(names.len(), 2, "expected own + global, legacy discarded, got: {names:?}");
865 assert!(names.contains(&"Own Skill"));
866 assert!(names.contains(&"Global Skill"));
867 assert!(!names.contains(&"Legacy Skill"), "legacy skill must be discarded once own refs exist");
868 }
869
870 #[test]
871 fn agent_skill_format_survives_the_merge_with_correct_skill_type() {
872 let store = make_store();
877 insert_agent(&store, "agent-1");
878
879 let own_skill = Skill {
880 id: "own-1".to_string(),
881 name: "Deploy Checklist".to_string(),
882 trigger: String::new(),
883 skill_type: "agent-skill".to_string(),
884 description: "checklist".to_string(),
885 content: "1. test\n2. deploy".to_string(),
886 is_global: false,
887 created_at: 1_700_000_000_000,
888 updated_at: 1_700_000_000_000,
889 };
890 store.skill_upsert_unique(&store, "agent-1", &own_skill, true).unwrap();
891
892 let effective = store.effective_skills(&store, "agent-1");
893 assert_eq!(effective.len(), 1);
894 assert_eq!(effective[0].skill_type, "agent-skill");
895 }
896
897 pub(super) fn insert_agent_with_bundle(store: &Store, id: &str, memory_id: &str) {
898 let mut def = AgentDefinition {
899 slug: String::new(),
900 ..crate::backend::storage::agents::test_agent_def(id, "Test Agent", "claude", "host", 1_700_000_000_000, "")
901 };
902 store.agent_def_insert(&mut def).unwrap();
903 store.agent_bundles_set(id, &[memory_id.to_string()]).unwrap();
904 }
905
906 pub(super) fn insert_test_bundle(store: &Store, id: &str) {
907 store
908 .bundle_upsert(&crate::backend::storage::bundles::Bundle {
909 id: id.to_string(),
910 name: format!("Bundle {id}"),
911 description: String::new(),
912 is_blank: false,
913 is_global: false,
914 provider: "claude".to_string(),
915 model: "anthropic".to_string(),
916 instructions: String::new(),
917 instructions_by_provider: "{}".to_string(),
918 context_files: "[]".to_string(),
919 mcp_servers: "[]".to_string(),
920 skills: "[]".to_string(),
921 sort_order: 0,
922 created_at: 1_700_000_000_000,
923 updated_at: 1_700_000_000_000,
924 is_system: false,
925 })
926 .unwrap();
927 }
928
929 #[test]
937 fn effective_skills_includes_the_bound_bundles_referenced_skills() {
938 let store = make_store();
939 insert_test_bundle(&store, "bundle-1");
940 insert_agent_with_bundle(&store, "agent-1", "bundle-1");
941
942 let bundle_skill = Skill {
943 id: "bundle-skill-1".to_string(),
944 name: "Bundle Skill".to_string(),
945 trigger: String::new(),
946 skill_type: "prompt".to_string(),
947 description: String::new(),
948 content: "content".to_string(),
949 is_global: false,
950 created_at: 1_700_000_000_000,
951 updated_at: 1_700_000_000_000,
952 };
953 store.skill_upsert_unique(&store, "some-other-context", &bundle_skill, false).unwrap();
957 store.bundle_skill_bind(&store, &store, "bundle-1", "bundle-skill-1").unwrap();
958
959 let effective = store.effective_skills(&store, "agent-1");
960 let names: Vec<&str> = effective.iter().map(|s| s.name.as_str()).collect();
961 assert!(
962 names.contains(&"Bundle Skill"),
963 "a skill referenced only by the agent's bound bundle must still be effective: {names:?}"
964 );
965 }
966
967 #[test]
972 fn effective_skills_includes_a_bundle_owned_private_skill_created_via_upsert_unique() {
973 let store = make_store();
974 insert_test_bundle(&store, "bundle-1");
975 insert_agent_with_bundle(&store, "agent-1", "bundle-1");
976
977 let bundle_skill = Skill {
978 id: "bundle-own-skill".to_string(),
979 name: "Bundle-Owned Skill".to_string(),
980 trigger: String::new(),
981 skill_type: "prompt".to_string(),
982 description: String::new(),
983 content: "content".to_string(),
984 is_global: true, created_at: 1_700_000_000_000,
986 updated_at: 1_700_000_000_000,
987 };
988 store.bundle_skill_upsert_unique(&store, &store, "bundle-1", &bundle_skill, true).unwrap();
989
990 let effective = store.effective_skills(&store, "agent-1");
991 let names: Vec<&str> = effective.iter().map(|s| s.name.as_str()).collect();
992 assert!(
993 names.contains(&"Bundle-Owned Skill"),
994 "a bundle-owned private skill created via bundle_skill_upsert_unique must reach the agent's effective skills: {names:?}"
995 );
996 }
997
998 #[test]
1009 fn a_bundle_referenced_private_skill_does_not_discard_the_agents_own_legacy_skills() {
1010 let store = make_store();
1011 insert_test_bundle(&store, "bundle-1");
1012 insert_agent_with_bundle(&store, "agent-1", "bundle-1");
1013
1014 store.agent_skill_insert(&AgentSkill {
1015 id: "legacy-1".to_string(),
1016 agent_id: "agent-1".to_string(),
1017 name: "Legacy Skill".to_string(),
1018 trigger: "legacy".to_string(),
1019 skill_type: "prompt".to_string(),
1020 description: "legacy description".to_string(),
1021 content: "legacy content".to_string(),
1022 created_at: 1_700_000_000_000,
1023 }).unwrap();
1024
1025 let bundle_private_skill = Skill {
1026 id: "bundle-private-1".to_string(),
1027 name: "Bundle Private Skill".to_string(),
1028 trigger: String::new(),
1029 skill_type: "prompt".to_string(),
1030 description: String::new(),
1031 content: "content".to_string(),
1032 is_global: false,
1033 created_at: 1_700_000_000_000,
1034 updated_at: 1_700_000_000_000,
1035 };
1036 store.skill_upsert_unique(&store, "some-other-context", &bundle_private_skill, false).unwrap();
1037 store.bundle_skill_bind(&store, &store, "bundle-1", "bundle-private-1").unwrap();
1038 let effective = store.effective_skills(&store, "agent-1");
1041 let names: Vec<&str> = effective.iter().map(|s| s.name.as_str()).collect();
1042 assert!(
1043 names.contains(&"Legacy Skill"),
1044 "a bundle-referenced private skill must not silently discard the agent's own legacy skills: {names:?}"
1045 );
1046 assert!(
1047 names.contains(&"Bundle Private Skill"),
1048 "the bundle-referenced skill must still be included, just not treated as agent-authoritative: {names:?}"
1049 );
1050 }
1051
1052 #[test]
1053 fn effective_skills_does_not_duplicate_a_global_skill_visible_via_both_agent_and_bundle() {
1054 let store = make_store();
1055 insert_test_bundle(&store, "bundle-1");
1056 insert_agent_with_bundle(&store, "agent-1", "bundle-1");
1057 store.skill_upsert_unique_global(&global_skill("global-1", "Global Skill")).unwrap();
1058 store.skill_bind(&store, "agent-1", "global-1").unwrap();
1059 store.bundle_skill_bind(&store, &store, "bundle-1", "global-1").unwrap();
1060
1061 let effective = store.effective_skills(&store, "agent-1");
1062 let matches: Vec<_> = effective.iter().filter(|s| s.name == "Global Skill").collect();
1063 assert_eq!(matches.len(), 1, "a global skill visible via both the agent and its bundle must not be duplicated: {effective:?}");
1064 }
1065}
1066
1067#[cfg(test)]
1068mod bundle_ref_tests {
1069 use super::*;
1070 use crate::backend::storage::bundles::Bundle;
1071
1072 fn make_store() -> Store {
1073 Store::open_in_memory().unwrap()
1074 }
1075
1076 fn insert_bundle(store: &Store, id: &str) {
1077 store
1078 .bundle_upsert(&Bundle {
1079 id: id.to_string(),
1080 name: format!("Bundle {id}"),
1081 description: String::new(),
1082 is_blank: false,
1083 is_global: false,
1084 provider: "claude".to_string(),
1085 model: "anthropic".to_string(),
1086 instructions: String::new(),
1087 instructions_by_provider: "{}".to_string(),
1088 context_files: "[]".to_string(),
1089 mcp_servers: "[]".to_string(),
1090 skills: "[]".to_string(),
1091 sort_order: 0,
1092 created_at: 1_700_000_000_000,
1093 updated_at: 1_700_000_000_000,
1094 is_system: false,
1095 })
1096 .unwrap();
1097 }
1098
1099 fn skill(id: &str, name: &str, is_global: bool) -> Skill {
1100 Skill {
1101 id: id.to_string(),
1102 name: name.to_string(),
1103 trigger: String::new(),
1104 skill_type: "prompt".to_string(),
1105 description: String::new(),
1106 content: "content".to_string(),
1107 is_global,
1108 created_at: 1_700_000_000_000,
1109 updated_at: 1_700_000_000_000,
1110 }
1111 }
1112
1113 #[test]
1114 fn bind_makes_a_private_skill_visible_in_bundle_skill_list() {
1115 let store = make_store();
1116 insert_bundle(&store, "bundle-1");
1117 store.skill_upsert_unique_global(&skill("skill-global", "Global", true)).unwrap();
1118 store
1119 .skill_upsert_unique(&store, "some-other-agent-context", &skill("skill-private", "Private", false), false)
1120 .unwrap_or(());
1121
1122 let before = store.bundle_skill_list(&store, "bundle-1").unwrap();
1123 assert_eq!(before.len(), 1, "only the global skill should be visible before any bind: {before:?}");
1124
1125 store.bundle_skill_bind(&store, &store, "bundle-1", "skill-private").unwrap();
1126 let after = store.bundle_skill_list(&store, "bundle-1").unwrap();
1127 assert_eq!(after.len(), 2, "private skill must now be visible after binding: {after:?}");
1128 let private_item = after.iter().find(|i| i.skill.id == "skill-private").expect("private skill present");
1129 assert!(private_item.bound_to_bundle);
1130 }
1131
1132 #[test]
1133 fn bind_is_not_visible_to_a_different_bundle() {
1134 let store = make_store();
1135 insert_bundle(&store, "bundle-1");
1136 insert_bundle(&store, "bundle-2");
1137 store
1138 .skill_upsert_unique(&store, "ctx", &skill("skill-private", "Private", false), false)
1139 .unwrap_or(());
1140 store.bundle_skill_bind(&store, &store, "bundle-1", "skill-private").unwrap();
1141
1142 let bundle2_list = store.bundle_skill_list(&store, "bundle-2").unwrap();
1143 assert!(
1144 bundle2_list.is_empty(),
1145 "a private skill bound to bundle-1 must not leak into bundle-2's list: {bundle2_list:?}"
1146 );
1147 }
1148
1149 #[test]
1150 fn bind_errors_when_the_bundle_does_not_exist() {
1151 let store = make_store();
1152 store.skill_upsert_unique_global(&skill("skill-1", "S", true)).unwrap();
1153 let result = store.bundle_skill_bind(&store, &store, "no-such-bundle", "skill-1");
1154 assert!(result.is_err(), "binding to a nonexistent bundle must error, not silently no-op");
1155 }
1156
1157 #[test]
1158 fn unbind_removes_the_ref_and_is_idempotent() {
1159 let store = make_store();
1160 insert_bundle(&store, "bundle-1");
1161 store
1162 .skill_upsert_unique(&store, "ctx", &skill("skill-private", "Private", false), false)
1163 .unwrap_or(());
1164 store.bundle_skill_bind(&store, &store, "bundle-1", "skill-private").unwrap();
1165
1166 let removed = store.bundle_skill_unbind("bundle-1", "skill-private").unwrap();
1167 assert!(removed);
1168 assert!(store.bundle_skill_list(&store, "bundle-1").unwrap().is_empty());
1169
1170 let removed_again = store.bundle_skill_unbind("bundle-1", "skill-private").unwrap();
1171 assert!(!removed_again, "unbinding an already-unbound pair returns false, not an error");
1172 }
1173
1174 #[test]
1175 fn deleting_a_skill_purges_its_bundle_ref_too() {
1176 let store = make_store();
1177 insert_bundle(&store, "bundle-1");
1178 store
1179 .skill_upsert_unique(&store, "ctx", &skill("skill-private", "Private", false), false)
1180 .unwrap_or(());
1181 store.bundle_skill_bind(&store, &store, "bundle-1", "skill-private").unwrap();
1182 assert_eq!(store.bundle_skill_list(&store, "bundle-1").unwrap().len(), 1);
1183
1184 store.skill_delete(&store, "skill-private").unwrap();
1185 assert!(
1186 store.bundle_skill_list(&store, "bundle-1").unwrap().is_empty(),
1187 "the bundle ref row must be purged when the underlying skill is deleted"
1188 );
1189 }
1190
1191 #[test]
1195 fn bind_checks_bundle_existence_in_id_store_not_self() {
1196 let mstore = make_store();
1197 let id_store = make_store();
1198 insert_bundle(&id_store, "bundle-1");
1199 mstore.skill_upsert_unique_global(&skill("skill-1", "S", true)).unwrap();
1200
1201 let result = mstore.bundle_skill_bind(&mstore, &id_store, "bundle-1", "skill-1");
1202 assert!(result.is_ok(), "must check bundle existence against id_store, not self: {result:?}");
1203 }
1204
1205 #[test]
1206 fn bind_fails_when_bundle_exists_only_in_self_not_id_store() {
1207 let mstore = make_store();
1208 let id_store = make_store();
1209 insert_bundle(&mstore, "bundle-1");
1210 mstore.skill_upsert_unique_global(&skill("skill-1", "S", true)).unwrap();
1211
1212 let result = mstore.bundle_skill_bind(&mstore, &id_store, "bundle-1", "skill-1");
1213 assert!(
1214 result.is_err(),
1215 "a bundle only present in self's non-authoritative copy must not satisfy the id_store check: {result:?}"
1216 );
1217 }
1218
1219 #[test]
1222 fn upsert_unique_creates_a_new_private_skill_bound_to_the_bundle() {
1223 let store = make_store();
1224 insert_bundle(&store, "bundle-1");
1225
1226 store
1227 .bundle_skill_upsert_unique(&store, &store, "bundle-1", &skill("new-skill", "Bundle-Only Skill", true), true)
1228 .unwrap();
1229
1230 let list = store.bundle_skill_list(&store, "bundle-1").unwrap();
1231 let item = list.iter().find(|i| i.skill.id == "new-skill").expect("newly created skill present");
1232 assert!(item.bound_to_bundle);
1233 assert!(!item.skill.is_global, "upsert_unique must force is_global=false regardless of the input struct");
1234 }
1235
1236 #[test]
1237 fn upsert_unique_rejects_a_duplicate_name_already_bound_to_the_bundle() {
1238 let store = make_store();
1239 insert_bundle(&store, "bundle-1");
1240 store.bundle_skill_upsert_unique(&store, &store, "bundle-1", &skill("skill-a", "Dup Name", true), true).unwrap();
1241
1242 let result = store.bundle_skill_upsert_unique(&store, &store, "bundle-1", &skill("skill-b", "Dup Name", true), true);
1243 assert!(result.is_err(), "a second skill with the same name bound to the same bundle must be rejected");
1244 }
1245
1246 #[test]
1247 fn is_accessible_to_reflects_global_and_bound_state() {
1248 let store = make_store();
1249 insert_bundle(&store, "bundle-1");
1250 store.skill_upsert_unique_global(&skill("skill-global", "Global", true)).unwrap();
1251 store
1252 .skill_upsert_unique(&store, "ctx", &skill("skill-private", "Private", false), false)
1253 .unwrap_or(());
1254
1255 assert!(store.bundle_skill_is_accessible_to(&store, "bundle-1", "skill-global").unwrap());
1256 assert!(!store.bundle_skill_is_accessible_to(&store, "bundle-1", "skill-private").unwrap());
1257 store.bundle_skill_bind(&store, &store, "bundle-1", "skill-private").unwrap();
1258 assert!(store.bundle_skill_is_accessible_to(&store, "bundle-1", "skill-private").unwrap());
1259 }
1260}
1261
1262#[cfg(test)]
1263mod rewrite_ref_id_and_delete_ordering_tests {
1264 use super::*;
1265 use crate::backend::storage::bundles::Bundle;
1266
1267 fn make_store() -> Store {
1268 Store::open_in_memory().unwrap()
1269 }
1270
1271 fn skill(id: &str, name: &str, is_global: bool) -> Skill {
1272 Skill {
1273 id: id.to_string(),
1274 name: name.to_string(),
1275 trigger: String::new(),
1276 skill_type: "prompt".to_string(),
1277 description: String::new(),
1278 content: "content".to_string(),
1279 is_global,
1280 created_at: 1_700_000_000_000,
1281 updated_at: 1_700_000_000_000,
1282 }
1283 }
1284
1285 fn insert_agent(store: &Store, id: &str) {
1286 store
1287 .conn()
1288 .lock()
1289 .unwrap()
1290 .execute("INSERT INTO db_agents (id, name, provider) VALUES (?1, 'A', 'claude')", params![id])
1291 .unwrap();
1292 }
1293
1294 fn insert_bundle(store: &Store, id: &str) {
1295 store
1296 .bundle_upsert(&Bundle {
1297 id: id.to_string(),
1298 name: format!("Bundle {id}"),
1299 description: String::new(),
1300 is_blank: false,
1301 is_global: false,
1302 provider: "claude".to_string(),
1303 model: "anthropic".to_string(),
1304 instructions: String::new(),
1305 instructions_by_provider: "{}".to_string(),
1306 context_files: "[]".to_string(),
1307 mcp_servers: "[]".to_string(),
1308 skills: "[]".to_string(),
1309 sort_order: 0,
1310 created_at: 1_700_000_000_000,
1311 updated_at: 1_700_000_000_000,
1312 is_system: false,
1313 })
1314 .unwrap();
1315 }
1316
1317 fn raw_bind_agent(store: &Store, agent_id: &str, skill_id: &str) {
1318 store
1319 .conn()
1320 .lock()
1321 .unwrap()
1322 .execute(
1323 "INSERT INTO db_agent_skills_ref (agent_id, skill_id) VALUES (?1, ?2)",
1324 params![agent_id, skill_id],
1325 )
1326 .unwrap();
1327 }
1328
1329 fn raw_bind_bundle(store: &Store, bundle_id: &str, skill_id: &str) {
1330 store
1331 .conn()
1332 .lock()
1333 .unwrap()
1334 .execute(
1335 "INSERT INTO db_bundle_skills_ref (bundle_id, skill_id) VALUES (?1, ?2)",
1336 params![bundle_id, skill_id],
1337 )
1338 .unwrap();
1339 }
1340
1341 #[test]
1350 fn rewrite_resolves_a_ref_row_even_when_the_owner_already_holds_the_survivor_too() {
1351 let store = make_store();
1352 insert_agent(&store, "agent-1");
1353 raw_bind_agent(&store, "agent-1", "loser-id");
1354 raw_bind_agent(&store, "agent-1", "survivor-id");
1355
1356 let rewritten = store.skill_rewrite_ref_id("loser-id", "survivor-id").unwrap();
1357 assert_eq!(rewritten, 1, "the loser ref row must be resolved (deleted, since the survivor was already bound)");
1358
1359 assert!(store.skill_is_bound_to("agent-1", "survivor-id").unwrap());
1360 assert!(
1361 !store.skill_is_bound_to("agent-1", "loser-id").unwrap(),
1362 "no ref may still name the loser id after the rewrite — that id is about to be deleted from the catalog"
1363 );
1364 }
1365
1366 #[test]
1368 fn rewrite_resolves_a_bundle_ref_row_even_when_the_bundle_already_holds_the_survivor_too() {
1369 let store = make_store();
1370 insert_bundle(&store, "bundle-1");
1371 raw_bind_bundle(&store, "bundle-1", "loser-id");
1372 raw_bind_bundle(&store, "bundle-1", "survivor-id");
1373
1374 let rewritten = store.skill_rewrite_ref_id("loser-id", "survivor-id").unwrap();
1375 assert_eq!(rewritten, 1);
1376
1377 assert!(store.bundle_skill_is_bound_to("bundle-1", "survivor-id").unwrap());
1378 assert!(!store.bundle_skill_is_bound_to("bundle-1", "loser-id").unwrap());
1379 }
1380
1381 #[test]
1384 fn rewrite_behaves_like_a_plain_rename_when_the_owner_has_no_prior_survivor_ref() {
1385 let store = make_store();
1386 insert_agent(&store, "agent-1");
1387 raw_bind_agent(&store, "agent-1", "old-id");
1388
1389 let rewritten = store.skill_rewrite_ref_id("old-id", "new-id").unwrap();
1390 assert_eq!(rewritten, 1);
1391 assert!(store.skill_is_bound_to("agent-1", "new-id").unwrap());
1392 assert!(!store.skill_is_bound_to("agent-1", "old-id").unwrap());
1393 }
1394
1395 #[test]
1405 fn skill_delete_leaves_refs_intact_when_the_catalog_delete_itself_fails() {
1406 let store = make_store();
1407 insert_agent(&store, "agent-1");
1408 store
1409 .skill_upsert_unique(&store, "agent-1", &skill("private-1", "Deploy", false), true)
1410 .unwrap();
1411 assert!(store.skill_is_bound_to("agent-1", "private-1").unwrap());
1412
1413 store.conn().lock().unwrap().execute_batch("DROP TABLE db_skills;").unwrap();
1414
1415 let result = store.skill_delete(&store, "private-1");
1416 assert!(result.is_err(), "the catalog delete must fail now that its table is gone");
1417
1418 store
1423 .conn()
1424 .lock()
1425 .unwrap()
1426 .execute_batch(
1427 "CREATE TABLE db_skills (
1428 id TEXT PRIMARY KEY, name TEXT NOT NULL, trigger TEXT NOT NULL DEFAULT '',
1429 skill_type TEXT NOT NULL DEFAULT 'prompt', description TEXT NOT NULL DEFAULT '',
1430 content TEXT NOT NULL DEFAULT '', is_global INTEGER NOT NULL DEFAULT 0,
1431 created_at INTEGER NOT NULL DEFAULT 0, updated_at INTEGER NOT NULL DEFAULT 0
1432 );",
1433 )
1434 .unwrap();
1435 assert!(
1436 store.skill_is_bound_to("agent-1", "private-1").unwrap(),
1437 "the ref row must still exist — a failed catalog delete must never strand a row with its bindings already purged"
1438 );
1439 }
1440}
1441
1442#[cfg(test)]
1443#[path = "skills_scope_tests.rs"]
1444mod skills_scope_tests;