Skip to main content

agentmux_srv_core/backend/storage/
skills.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Agent skills — reusable capability records attached to an agent
5//! definition.
6//!
7//! Extracted from `store.rs` in Phase R.4 of the storage
8//! modularization plan
9//! (`docs/specs/SPEC_STORE_MODULARIZATION_2026_05_27.md`). The
10//! method surface is unchanged — `Store::agent_skill_*` still
11//! lives on `Store` via this `impl` block; callers stay on
12//! `storage::store::AgentSkill` thanks to the re-export.
13
14use rusqlite::params;
15use serde::{Deserialize, Serialize};
16
17use super::error::StoreError;
18use super::managed::{ManagedResource, Owner};
19use super::store::Store;
20
21/// A reusable skill/capability attached to a agent definition.
22#[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    /// Free-form rather than an enum: rows written by Memory → Skills and
30    /// by older builds both land here, so a closed set would fail to read
31    /// them back. `createagentskill` defaults it to "prompt".
32    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    /// List all skills for an agent, ordered by created_at ascending.
41    /// LOCAL channel's skills only — NO cross-channel fallback. Used by the
42    /// def-registry mirror (which always operates on a local agent) and by
43    /// `agent_skill_list`.
44    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        // Fall back to the global record ONLY for a cross-channel agent
78        // (absent from local SQLite); a locally-known agent with genuinely no
79        // skills must return empty, not resurrect them. (reagent P1 on #1385.)
80        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    /// Get a single skill by id.
106    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    /// Insert a new skill.
132    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        // Re-mirror the owning definition — only refreshes an EXISTING
151        // mirror; never creates one for a bare template-launch row (reagent
152        // P1 on #3092; see registry_def_refresh_if_mirrored's doc comment).
153        // No-op for seeded templates too. (P0.2b.)
154        self.registry_def_refresh_if_mirrored(&skill.agent_id);
155        Ok(())
156    }
157
158    /// Update an existing skill (all fields except id, agent_id, created_at).
159    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        // conn dropped — re-mirror the definition (no-op for seeded, and
176        // for a bare template-launch row — see registry_def_refresh_if_mirrored).
177        // (P0.2b.)
178        if rows > 0 {
179            self.registry_def_refresh_if_mirrored(&skill.agent_id);
180        }
181        Ok(rows > 0)
182    }
183
184    /// Delete a legacy skill by id. Returns true if a row was deleted.
185    pub fn agent_skill_delete(&self, id: &str) -> Result<bool, StoreError> {
186        let (rows, agent_id) = {
187            let conn = self.conn.lock().unwrap();
188            // Capture the owning agent_id before the delete so we can
189            // re-mirror its definition afterwards.
190            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        // conn dropped — re-mirror the definition so the global record drops
203        // the removed skill (no-op for seeded templates, and for a bare
204        // template-launch row — see registry_def_refresh_if_mirrored). (P0.2b.)
205        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// ---------------------------------------------------------------------------
215// v1 standalone Skill primitive
216// ---------------------------------------------------------------------------
217
218/// Standalone skill primitive (v1 composable model).
219/// Not bound to a specific agent at rest — agents reference via db_agent_skills_ref.
220#[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/// `skill_list`'s response shape: the skill plus whether the requesting agent
292/// specifically holds a `db_agent_skills_ref` row for it. Mirrors
293/// `McpServerListItem` — see its doc comment for why `is_global` alone isn't
294/// enough to render bind/unbind as a stateful toggle (tracked in #1960).
295#[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    /// Gets the skill through its reach (`skill_reach`), not a bind; only `skill_list_global_for_agent` says so.
302    #[serde(default)]
303    pub reached: bool,
304    /// Opted out of the skill's reach (`skill_optout`), so `reached` is false.
305    pub opted_out: bool,
306    /// One of the agent's bundles holds the skill, so it gets it whatever its reach or opt-out says.
307    pub via_bundle: bool,
308}
309
310/// `skill_list_global`'s response shape: the skill plus how many agents
311/// currently hold a `db_agent_skills_ref` to it — Memory → Skills'
312/// "used by N agents" count (gap #2 of #1960).
313#[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    /// Reaches every agent, not only the bound ones (`skill_reach::SkillReach`).
321    pub all_agents: bool,
322    /// Reaches every agent created from now on (`skill_reach::SkillReach`).
323    pub new_agents: bool,
324    /// Where it was imported from (`skill_source`); `None` for one written by hand.
325    pub source: Option<super::skill_source::SkillSource>,
326    /// The manifest, files and pass records, for a computer-use skill (`skill_app`); `None` for a plain one.
327    pub app: Option<super::skill_app::SkillApp>,
328}
329
330/// `bundle_skill_list`'s response shape — mirrors `SkillListItem`, but
331/// "bound" means a `db_bundle_skills_ref` row for this bundle, not an
332/// agent's `db_agent_skills_ref` row. Composable model v2,
333/// docs/specs/SPEC_BUNDLE_AS_CONTAINER_V2_2026_08_17.md.
334#[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    /// List all skills visible to an agent: own (referenced) + global, each
344    /// annotated with whether this specific agent holds the bind ref.
345    /// `catalog` is where `db_skills` is authoritative — `identity_store` in
346    /// production (Phase 2 of SPEC_DURABLE_BINDINGS_2026_09_10.md §5.4).
347    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    /// Effective skills for an agent at launch/config-materialization time:
356    /// this agent's own private skills take over *entirely* when present,
357    /// otherwise fall back to the legacy `db_agent_skills` table. Either way
358    /// the global skills the agent (or its bundle) holds a bind to are layered
359    /// on top, and no others: an unbound global skill is catalog content only,
360    /// so what is written to the agent matches the count Memory → Skills and
361    /// the agent's Skills tab show. The fallback decision is gated on *own*
362    /// private skills only, so binding a global skill never discards a
363    /// legacy-only agent's skills.
364    ///
365    /// Single source of truth for two call sites that must stay consistent:
366    /// `write_agent_config_files` (the authoritative Rust materialization
367    /// path) and the `listagentskills` RPC handler, which the frontend's
368    /// pre-launch `ListAgentSkillsCommand` call depends on. Before this was extracted, `listagentskills`
369    /// returned only legacy skills — silently hiding every standalone/Memory →
370    /// Skills skill (including any Agent-Skills-format one, see
371    /// SKILL_TYPE_AGENT_SKILL) from the actual "click Launch" flow, since
372    /// that RPC is window-scoped (no `check_s1`) and can't call the
373    /// agent-scoped `skill.list` RPC the way an already-running, authenticated
374    /// agent connection could (reagent P0 on PR #2322 — the launch UI is not
375    /// an authenticated agent connection, so it was never able to reach the
376    /// standalone Skill primitive via the RPC layer at all).
377    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        // reagentx P1 on PR #2639: `has_own_skill_refs` must be decided
394        // BEFORE unioning in the bundle's referenced skills below — it
395        // reflects only the agent's OWN direct binds. Mandatory ABF means
396        // every agent has a bundle, so if a bundle's private skill alone
397        // could flip this flag, a legacy-only agent bound to any bundle
398        // that happens to reference one private skill would silently lose
399        // every `db_agent_skills` entry, with no action taken on the agent
400        // itself. The "own refs are authoritative" path is meant strictly
401        // for the agent's own binds (see `own_refs_take_over_entirely_and_discard_legacy_skills`).
402        let has_own_skill_refs = visible_skills.iter().any(|s| !s.is_global);
403        // Composable model v2 (docs/specs/SPEC_BUNDLE_AS_CONTAINER_V2_2026_08_17.md,
404        // GH issue #2024 item 3): union in the agent's bound bundle's own
405        // referenced skills too — without this, db_bundle_skills_ref would
406        // be exactly as inert at launch as the bundle's old inline `skills`
407        // JSON column always was. Deduped by id since a global skill is
408        // already visible via both `skill_list` above and
409        // `bundle_skill_list` below. Happens AFTER the has_own decision —
410        // bundle-referenced skills still appear in the final list, they
411        // just never trigger the "discard legacy" path on their own.
412        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    /// List every GLOBAL skill — Memory → Skills. Unlike
423    /// `skill_list`, this takes no `agent_id` and never includes an agent's
424    /// private skills; it backs the window-scoped `skill.catalog.*` MuxAPI
425    /// (no `check_s1`, so there is no agent context to scope by). Each row
426    /// carries `bound_count` — how many agents currently hold a
427    /// `db_agent_skills_ref` to it — per
428    /// SPEC_V1_MCP_SKILLS_PRIMITIVES_2026_06_30.md §8 ("used by N agents"),
429    /// tracked as gap #2 of #1960.
430    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    /// Catalog-tier sibling of `skill_list` (above) — same `bound_to_agent` shape, but deliberately GLOBAL ROWS ONLY, unlike `skill_list`'s UNION
444    /// with `agent_id`'s own private skills. Backs `skill.catalog.list_for_agent`,
445    /// which — like every other `skill.catalog.*` command — has no
446    /// `check_s1`, so `agent_id` here is caller-supplied and unverified.
447    /// Returning private skill rows (whose `content`/`description`/`trigger`
448    /// can carry sensitive agent-authored material) for an arbitrary
449    /// caller-chosen `agent_id` would let any window connection read any
450    /// agent's private skills. Global rows carry nothing per-agent-secret —
451    /// they're already fully visible via `skill_list_global` (Memory →
452    /// Skills) — so exposing them alongside a caller-chosen agent's bind
453    /// status is safe. reagentx P0 on PR #2329.
454    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    /// Get a standalone skill by id.
469    pub fn skill_get(&self, id: &str) -> Result<Option<Skill>, StoreError> {
470        self.managed_get::<Skill>(id)
471    }
472
473    /// Delete a standalone skill and purge its ref rows (both agent- and
474    /// bundle-level). Returns true if deleted.
475    pub fn skill_delete(&self, catalog: &Store, id: &str) -> Result<bool, StoreError> {
476        let deleted = self.managed_delete::<Skill>(catalog, id)?;
477        // Its reach, source, computer-use files and opt-outs go with it.
478        catalog.skill_catalog_forget(id)?;
479        Ok(deleted)
480    }
481
482    /// Bind a skill to an agent (insert ref row). Idempotent — binding an
483    /// already-bound pair is a silent no-op success.
484    ///
485    /// Errors if `agent_id` isn't a LOCAL agent:
486    /// `db_agent_skills_ref.agent_id` has an ON-enforced FK to
487    /// `db_agents(id)` (store.rs; was `db_agent_definitions(id)` before
488    /// Phase 3c, #3088), but Memory's agent
489    /// picker (`ListAgentDefinitionsCommand` → `agent_def_list()`) also
490    /// lists cross-channel agents that only exist in another channel's
491    /// local database. Binding one of those would otherwise have the FK
492    /// silently swallow the `INSERT OR IGNORE` — indistinguishable, by
493    /// affected-row-count alone, from the equally-silent "already bound"
494    /// case — reporting success while creating nothing. reagentx P1, PR
495    /// #2315.
496    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    /// Unbind a skill from an agent. Returns true if a row was removed.
501    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    /// Atomically upsert a skill enforcing per-agent name uniqueness, and (when
506    /// `bind_new`) bind it to the agent — all in one transaction so concurrent
507    /// `skill.upsert` calls for the same name can't both pass a separate check
508    /// and insert duplicates (the check+write is not split across lock releases).
509    /// Returns `StoreError::Other` ("… already bound to this agent") if another
510    /// skill visible to the agent (bound or global) already uses the name.
511    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    /// Atomically upsert a GLOBAL skill enforcing catalog-wide name
522    /// uniqueness (no `agent_id` — unlike `skill_upsert_unique`, this checks
523    /// for a duplicate name among *every* global row, not just those visible
524    /// to one agent). Same defense-in-depth as
525    /// `McpServer::mcp_server_upsert_unique_global` (reagent P1 on #1948) —
526    /// two same-named global skills would at minimum produce a confusing
527    /// duplicate bullet in the assembled CLAUDE.md skills index.
528    /// `skill.is_global` must already be `true`; caller's job.
529    pub fn skill_upsert_unique_global(&self, skill: &Skill) -> Result<(), StoreError> {
530        self.managed_upsert_unique_global(skill)
531    }
532
533    // ── Migration-only raw access (Phase 2 of SPEC_DURABLE_BINDINGS_2026_09_10.md) ──
534    // Bypasses the ordinary uniqueness/ownership validation on purpose: the
535    // carry-across migration has already made its own dedup decision (which
536    // survives, which gets a fresh id) before calling these, and re-running
537    // that validation here would both be redundant and, for a private row,
538    // actively wrong — `skill_upsert_unique_global` hardcodes `is_global = 1`,
539    // which a private row must not get. Not for use outside a migration.
540
541    /// Every row in this store's `db_skills`, global and private alike, with
542    /// no accessibility filtering. Ordinary app code never needs this — it is
543    /// always scoped by agent/bundle accessibility — which is exactly why no
544    /// such method existed before the carry-across migration needed one.
545    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    /// Insert `skill` verbatim — including its `is_global` flag, which
572    /// `skill_upsert_unique_global` would otherwise force to `true`. `INSERT
573    /// OR IGNORE`: idempotent against a re-run migrating the same row twice
574    /// (by id), never overwrites an existing row.
575    /// Returns 1 if a row was actually inserted, 0 if `OR IGNORE` found one
576    /// already there under this id — the caller's signal for whether this
577    /// was a genuinely new carry or an idempotent re-run no-op.
578    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    /// The first existing GLOBAL row matching `name` alone, for the
600    /// migration's first-wins dedup among global skills that aren't a
601    /// recognized starter (those converged on a fixed id derived from their
602    /// trigger instead — see `0031_carry_skills_and_mcp_servers_to_identity_store`).
603    ///
604    /// Name-only, not `(name, skill_type)` — matching `idx_ids_skills_global_name`
605    /// (`IDENTITY_STORE_SCHEMA_VERSION` v8, `SPEC_DURABLE_BINDINGS_2026_09_10.md`
606    /// §5.4, Codex P1 on PR #3183): a `(name, skill_type)`-scoped re-query
607    /// would miss the actual winner whenever two channels' carries collide on
608    /// name but not type — the insert that failed did so because of the
609    /// name-only constraint, so the re-query must match the constraint that
610    /// actually fired, or it finds nothing, falls through to the
611    /// unrelated-PK-collision branch, and mints a fresh id whose insert
612    /// SILENTLY no-ops against the same name constraint (`INSERT OR IGNORE`),
613    /// leaving a local ref rewritten to an id the identity store never
614    /// actually holds — the skill vanishes the moment reads redirect there.
615    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    /// Repoint every ref row (agent- and bundle-level) naming `old_id` to
644    /// `new_id` instead, on THIS store only. Called by the carry-across
645    /// migration after it decides a skill's row must live under a different
646    /// id in the identity store than it does locally — without this, the ref
647    /// row would name an id that no longer resolves anywhere once catalog
648    /// reads redirect to the identity store (Phase 2's whole point).
649    ///
650    /// INSERT-survivor-then-DELETE-old, not a blind `UPDATE`: the PK
651    /// `(agent_id, skill_id)`/`(bundle_id, skill_id)` collides whenever this
652    /// exact owner already independently held a ref to `new_id` too — not
653    /// vanishingly unlikely once two DIFFERENT catalog rows (not just two
654    /// copies of the same one) can converge onto one survivor, which is
655    /// exactly what `m0033_narrow_skill_global_uniqueness_index`'s dedup
656    /// does (an owner can easily have bound BOTH of two same-name,
657    /// different-`skill_type` skills before the collision was discovered).
658    /// A plain `UPDATE OR IGNORE` left that case's old-id row untouched
659    /// (documented at the time as an acceptable no-op — ReAgent P1, PR
660    /// #3181, round 2) — but a caller that then deletes the OLD catalog row
661    /// (as `m0033` does, right after this rewrite) turns that "no-op" into a
662    /// permanently dangling ref pointing at an id nothing resolves anymore,
663    /// even within the current channel (Codex P2, PR #3183). Insert-then-
664    /// delete instead: `INSERT OR IGNORE` the survivor binding for every
665    /// owner who held `old_id` (already-bound owners no-op harmlessly, same
666    /// as before), then unconditionally `DELETE` every `old_id` row — so the
667    /// owner ends up bound to the survivor either way, never left pointing
668    /// at a name that's about to stop existing. Returns the number of
669    /// `old_id` ref rows resolved (0 if none named `old_id`, distinct from
670    /// "the call itself no-oped").
671    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    /// Return true if the given skill is accessible to the agent (global or bound).
692    /// Used for read and delete access checks.
693    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    /// Return true if the agent has a direct ref binding to this skill (for delete/mutation).
698    /// Global skills are excluded — use the is_global guard separately.
699    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    // ── Bundle-level references (composable model v2) ──────────────────
704    // docs/specs/SPEC_BUNDLE_AS_CONTAINER_V2_2026_08_17.md, GH issue #2024
705    // item 3. Mirror the agent-level methods above exactly, keyed by
706    // bundle_id via db_bundle_skills_ref instead of agent_id/db_agent_skills_ref.
707
708    /// Bundle-level sibling of `skill_list` — this bundle's own (referenced)
709    /// and global skills, each annotated with whether this specific bundle
710    /// holds the `db_bundle_skills_ref` row.
711    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    /// Bind a skill to a bundle (insert ref row). Idempotent.
720    ///
721    /// `id_store` (NOT `self`) is where bundle existence is checked: bundles
722    /// are written through the shared store, and `self`'s own `db_bundles`
723    /// copy is essentially always empty in production, so checking there made
724    /// "bundle not found" fire for every real bundle (PR #2639). `catalog` is where
725    /// `db_skills` is authoritative — see `managed_bind_bundle`'s doc
726    /// comment for why it now ALSO checks skill existence there (Part A of
727    /// SPEC_DURABLE_BINDINGS_2026_09_10.md §5.4 dropped this table's
728    /// `skill_id` FK).
729    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    /// Atomically create a NEW, PRIVATE (never global) skill scoped and
734    /// bound directly to a bundle, enforcing bundle-scoped name uniqueness
735    /// — the bundle-level analog of `skill_upsert_unique`. Binding can only
736    /// reference global skills (binding another entity's private one would
737    /// hand this bundle read access to it); a bundle can bind a global skill,
738    /// or hold a private skill of its own (PR #2639).
739    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    /// Unbind a skill from a bundle. Returns true if a row was removed.
751    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    /// Return true if the given skill is accessible to the bundle (global or
756    /// bundle-bound). Mirrors `skill_is_accessible_to`.
757    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    /// Return true if the bundle has a direct ref binding to this skill
762    /// (global excluded). Mirrors `skill_is_bound_to` — used for
763    /// edit/delete-ownership checks, as opposed to
764    /// `bundle_skill_is_accessible_to`'s broader read-access check.
765    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        // A bound global is not an own skill -- has_own_skill_refs must stay false.
820
821        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        // Bind a NEW (non-global) skill to agent-1 -- this must flip
848        // has_own_skill_refs to true and discard the legacy skill entirely.
849        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        // Regression for PR #2322: an agent-skill-format skill materialized
873        // via effective_skills must retain skill_type == "agent-skill" so
874        // build_config_files still branches it to SKILL.md, not a slash
875        // command.
876        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    /// Composable model v2 (docs/specs/SPEC_BUNDLE_AS_CONTAINER_V2_2026_08_17.md,
930    /// GH issue #2024 item 3): a skill referenced by the agent's OWN bound
931    /// bundle (not the agent itself) must show up in effective_skills —
932    /// otherwise the new bundle-level ref tables are inert at launch, same
933    /// as the bug this whole feature exists to fix (see
934    /// `write_agent_config_files`'s doc comment on why this must be a
935    /// single source of truth shared with the RPC handler).
936    #[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        // Upserted under an unrelated agent context, then bound to the
954        // BUNDLE (not to agent-1 directly) — simulates a skill added via
955        // the bundle editor, not the agent's own Stash.
956        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    /// End-to-end proof of the reagentx P1 fix, mirrored from
968    /// mcp_servers.rs's identical test: a skill created via
969    /// `bundle_skill_upsert_unique` reaches a spawned agent's effective
970    /// skill list.
971    #[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, // ignored — upsert_unique forces is_global=false
985            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    /// reagentx P1 on PR #2639: `has_own_skill_refs` must reflect ONLY the
999    /// agent's own direct binds, never a bundle-referenced skill — mandatory
1000    /// ABF means every agent has a bundle, so if a bundle's private skill
1001    /// alone could flip this flag, a legacy-only agent bound to ANY bundle
1002    /// that happens to reference one private skill would silently lose all
1003    /// of its `db_agent_skills` entries the moment someone edits that
1004    /// bundle, with no action taken on the agent itself. The bundle's
1005    /// referenced skill must still appear in the result (it's not excluded)
1006    /// — it just must not trigger the "own refs are authoritative, discard
1007    /// legacy" path on its own.
1008    #[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        // agent-1 itself has NO own db_skills ref — only its bundle does.
1039
1040        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    /// reagentx P0 review on PR #2639: bundle existence must be checked
1192    /// against `id_store`, not `self` — see the identical test in
1193    /// mcp_servers.rs for the full reasoning, mirrored here for skills.
1194    #[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    /// reagentx P1 review on PR #2639: the missing "give this bundle its
1220    /// own skill" path — see the identical test in mcp_servers.rs.
1221    #[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    /// Codex P2, PR #3183: when an owner already holds a ref to BOTH the
1342    /// loser id and the survivor id (e.g. an agent independently bound two
1343    /// same-name-different-type skills before `m0033` discovered the
1344    /// collision), the old `UPDATE OR IGNORE` left the loser's ref row
1345    /// untouched — a caller that then deletes the loser catalog row (as
1346    /// `m0033` does) turns that into a permanently dangling ref. The fixed
1347    /// insert-then-delete version must leave the owner bound to ONLY the
1348    /// survivor.
1349    #[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    /// Same scenario, bundle-level ref table.
1367    #[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    /// The ordinary case (no pre-existing survivor ref) must still behave
1382    /// like a plain rename.
1383    #[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    /// Codex P1, PR #3183: `managed_delete` (via `skill_delete`) must delete
1396    /// the catalog row BEFORE purging refs, not after — so a catalog-delete
1397    /// failure never leaves a private row's refs already gone (which would
1398    /// make it permanently inaccessible and un-retryable, since the ordinary
1399    /// delete RPC's own pre-check depends on the very ref this would have
1400    /// already destroyed). Forces a real SQL error the same way
1401    /// `managed_upsert_unique_compensates_by_deleting_the_catalog_row_when_the_bind_fails`
1402    /// does (`managed.rs`'s own test) — dropping the catalog table, since
1403    /// `DELETE ... WHERE id = ?` on a missing row is not itself an error.
1404    #[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        // Re-create db_skills (empty) so the ref-table read below works —
1419        // the point being verified is that the ref row was NEVER purged in
1420        // the first place, i.e. the failure above happened before any ref
1421        // mutation, not that the schema self-heals.
1422        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;