Skip to main content

agent_hub_runtime/core/
skill_store.rs

1mod membership;
2mod recent_projects;
3mod rename;
4
5use anyhow::Result;
6use rusqlite::{params, Connection};
7use serde::Serialize;
8use std::path::PathBuf;
9use std::sync::Mutex;
10
11use super::audit_log::{AuditDraft, AuditEntry, MAX_ENTRIES as AUDIT_MAX_ENTRIES};
12use super::crypto;
13
14/// Settings keys whose values are encrypted at rest with AES-256-GCM.
15const SENSITIVE_KEYS: &[&str] = &["proxy_url", "git_backup_remote_url"];
16
17pub struct SkillStore {
18    conn: Mutex<Connection>,
19    secret_key: [u8; 32],
20}
21
22#[derive(Debug, Clone, Serialize)]
23pub struct SkillRecord {
24    pub id: String,
25    pub name: String,
26    pub description: Option<String>,
27    pub source_type: String,
28    pub source_ref: Option<String>,
29    pub source_ref_resolved: Option<String>,
30    pub source_subpath: Option<String>,
31    pub source_branch: Option<String>,
32    pub source_revision: Option<String>,
33    pub source_agent: Option<String>,
34    pub remote_revision: Option<String>,
35    pub central_path: String,
36    pub content_hash: Option<String>,
37    pub enabled: bool,
38    pub created_at: i64,
39    pub updated_at: i64,
40    pub status: String,
41    pub update_status: String,
42    pub last_checked_at: Option<i64>,
43    pub last_check_error: Option<String>,
44}
45
46#[derive(Debug, Clone, Serialize)]
47pub struct SkillTargetRecord {
48    pub id: String,
49    pub skill_id: String,
50    pub tool: String,
51    pub target_path: String,
52    pub mode: String,
53    pub status: String,
54    pub synced_at: Option<i64>,
55    pub last_error: Option<String>,
56    /// SHA-256 of the central skill source at the time of the last
57    /// successful sync. Compared against the current `skills.content_hash`
58    /// to skip redundant Copy-mode resyncs (issue #153). `None` for rows
59    /// written before this column existed, or when the source had no hash.
60    pub source_hash: Option<String>,
61}
62
63/// One row of the pending-conflict projection (merge-engine design §4).
64#[derive(Debug, Clone, Serialize)]
65pub struct PendingConflictRow {
66    pub skill_id: String,
67    pub theirs_commit: String,
68    pub theirs_path: Option<String>,
69    pub detected_at: i64,
70}
71
72#[derive(Debug, Clone, Serialize)]
73pub struct DiscoveredSkillRecord {
74    pub id: String,
75    pub tool: String,
76    pub found_path: String,
77    pub name_guess: Option<String>,
78    pub fingerprint: Option<String>,
79    pub found_at: i64,
80    pub imported_skill_id: Option<String>,
81}
82
83#[derive(Debug, Clone, Serialize)]
84pub struct ScenarioRecord {
85    pub id: String,
86    pub name: String,
87    pub description: Option<String>,
88    pub icon: Option<String>,
89    pub sort_order: i32,
90    pub created_at: i64,
91    pub updated_at: i64,
92}
93
94#[derive(Debug, Clone, Serialize)]
95pub struct ProjectRecord {
96    pub id: String,
97    pub name: String,
98    pub path: String,
99    pub workspace_type: String,
100    pub linked_agent_key: Option<String>,
101    pub linked_agent_name: Option<String>,
102    pub disabled_path: Option<String>,
103    pub sort_order: i32,
104    pub created_at: i64,
105    pub updated_at: i64,
106    pub visited_at: Option<i64>,
107}
108
109#[derive(Debug, Clone, Serialize)]
110pub struct ScenarioSkillToolToggleRecord {
111    pub scenario_id: String,
112    pub skill_id: String,
113    pub tool: String,
114    pub enabled: bool,
115    pub updated_at: i64,
116}
117
118impl SkillStore {
119    pub fn new(db_path: &PathBuf) -> Result<Self> {
120        let conn = Connection::open(db_path)?;
121        // busy_timeout makes concurrent CLI + GUI writers wait briefly instead
122        // of failing immediately with SQLITE_BUSY. 5s is generous for any
123        // realistic write contention here.
124        conn.busy_timeout(std::time::Duration::from_secs(5))?;
125        conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON;")?;
126
127        super::migrations::run_migrations(&conn)?;
128
129        // Derive key file path from the database directory.
130        let key_path = db_path
131            .parent()
132            .map(|p| p.join(".secret.key"))
133            .unwrap_or_else(|| PathBuf::from(".secret.key"));
134        let secret_key = crypto::load_or_create_key(&key_path)?;
135
136        Ok(Self {
137            conn: Mutex::new(conn),
138            secret_key,
139        })
140    }
141
142    // ── Skills CRUD ──
143
144    pub fn insert_skill(&self, skill: &SkillRecord) -> Result<()> {
145        let conn = self.conn.lock().unwrap();
146        conn.execute(
147            "INSERT INTO skills (
148                id, name, description, source_type, source_ref, source_ref_resolved, source_subpath,
149                source_branch, source_revision, source_agent, remote_revision, central_path, content_hash, enabled,
150                created_at, updated_at, status, update_status, last_checked_at, last_check_error
151             )
152             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20)",
153            params![
154                skill.id,
155                skill.name,
156                skill.description,
157                skill.source_type,
158                skill.source_ref,
159                skill.source_ref_resolved,
160                skill.source_subpath,
161                skill.source_branch,
162                skill.source_revision,
163                skill.source_agent,
164                skill.remote_revision,
165                skill.central_path,
166                skill.content_hash,
167                skill.enabled,
168                skill.created_at,
169                skill.updated_at,
170                skill.status,
171                skill.update_status,
172                skill.last_checked_at,
173                skill.last_check_error,
174            ],
175        )?;
176        Ok(())
177    }
178
179    pub fn upsert_skill(&self, skill: &SkillRecord) -> Result<()> {
180        let conn = self.conn.lock().unwrap();
181        conn.execute(
182            "INSERT INTO skills (
183                id, name, description, source_type, source_ref, source_ref_resolved, source_subpath,
184                source_branch, source_revision, source_agent, remote_revision, central_path, content_hash, enabled,
185                created_at, updated_at, status, update_status, last_checked_at, last_check_error
186             )
187             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20)
188             ON CONFLICT(id) DO UPDATE SET
189                name = excluded.name,
190                description = excluded.description,
191                source_type = excluded.source_type,
192                source_ref = excluded.source_ref,
193                source_ref_resolved = excluded.source_ref_resolved,
194                source_subpath = excluded.source_subpath,
195                source_branch = excluded.source_branch,
196                source_revision = excluded.source_revision,
197                source_agent = excluded.source_agent,
198                remote_revision = excluded.remote_revision,
199                central_path = excluded.central_path,
200                content_hash = excluded.content_hash,
201                enabled = excluded.enabled,
202                updated_at = excluded.updated_at,
203                status = excluded.status,
204                update_status = excluded.update_status,
205                last_checked_at = excluded.last_checked_at,
206                last_check_error = excluded.last_check_error",
207            params![
208                skill.id,
209                skill.name,
210                skill.description,
211                skill.source_type,
212                skill.source_ref,
213                skill.source_ref_resolved,
214                skill.source_subpath,
215                skill.source_branch,
216                skill.source_revision,
217                skill.source_agent,
218                skill.remote_revision,
219                skill.central_path,
220                skill.content_hash,
221                skill.enabled,
222                skill.created_at,
223                skill.updated_at,
224                skill.status,
225                skill.update_status,
226                skill.last_checked_at,
227                skill.last_check_error,
228            ],
229        )?;
230        Ok(())
231    }
232
233    pub fn get_all_skills(&self) -> Result<Vec<SkillRecord>> {
234        let conn = self.conn.lock().unwrap();
235        let mut stmt = conn.prepare(
236            "SELECT id, name, description, source_type, source_ref, source_ref_resolved, source_subpath,
237                    source_branch, source_revision, source_agent, remote_revision, central_path, content_hash, enabled,
238                    created_at, updated_at, status, update_status, last_checked_at, last_check_error
239             FROM skills ORDER BY name",
240        )?;
241        let rows = stmt.query_map([], map_skill_row)?;
242        Ok(rows.filter_map(|r| r.ok()).collect())
243    }
244
245    pub fn get_skill_by_id(&self, id: &str) -> Result<Option<SkillRecord>> {
246        let conn = self.conn.lock().unwrap();
247        let mut stmt = conn.prepare(
248            "SELECT id, name, description, source_type, source_ref, source_ref_resolved, source_subpath,
249                    source_branch, source_revision, source_agent, remote_revision, central_path, content_hash, enabled,
250                    created_at, updated_at, status, update_status, last_checked_at, last_check_error
251             FROM skills WHERE id = ?1",
252        )?;
253        let mut rows = stmt.query_map(params![id], map_skill_row)?;
254        Ok(rows.next().and_then(|r| r.ok()))
255    }
256
257    pub fn get_skill_by_central_path(&self, central_path: &str) -> Result<Option<SkillRecord>> {
258        let conn = self.conn.lock().unwrap();
259        let mut stmt = conn.prepare(
260            "SELECT id, name, description, source_type, source_ref, source_ref_resolved, source_subpath,
261                    source_branch, source_revision, source_agent, remote_revision, central_path, content_hash, enabled,
262                    created_at, updated_at, status, update_status, last_checked_at, last_check_error
263             FROM skills WHERE central_path = ?1",
264        )?;
265        let mut rows = stmt.query_map(params![central_path], map_skill_row)?;
266        Ok(rows.next().and_then(|r| r.ok()))
267    }
268
269    pub fn get_skill_by_source_ref(
270        &self,
271        source_type: &str,
272        source_ref: &str,
273    ) -> Result<Option<SkillRecord>> {
274        let conn = self.conn.lock().unwrap();
275        let mut stmt = conn.prepare(
276            "SELECT id, name, description, source_type, source_ref, source_ref_resolved, source_subpath,
277                    source_branch, source_revision, source_agent, remote_revision, central_path, content_hash, enabled,
278                    created_at, updated_at, status, update_status, last_checked_at, last_check_error
279             FROM skills
280             WHERE source_type = ?1 AND source_ref = ?2",
281        )?;
282        let mut rows = stmt.query_map(params![source_type, source_ref], map_skill_row)?;
283        Ok(rows.next().and_then(|r| r.ok()))
284    }
285
286    pub fn update_skill_source_metadata(
287        &self,
288        id: &str,
289        source_ref_resolved: Option<&str>,
290        source_subpath: Option<&str>,
291        source_branch: Option<&str>,
292        source_revision: Option<&str>,
293    ) -> Result<()> {
294        let conn = self.conn.lock().unwrap();
295        let now = chrono::Utc::now().timestamp_millis();
296        conn.execute(
297            "UPDATE skills
298             SET source_ref_resolved = ?1, source_subpath = ?2, source_branch = ?3, source_revision = ?4, updated_at = ?5
299             WHERE id = ?6",
300            params![
301                source_ref_resolved,
302                source_subpath,
303                source_branch,
304                source_revision,
305                now,
306                id
307            ],
308        )?;
309        Ok(())
310    }
311
312    pub fn update_skill_check_state(
313        &self,
314        id: &str,
315        remote_revision: Option<&str>,
316        update_status: &str,
317        last_check_error: Option<&str>,
318    ) -> Result<()> {
319        let conn = self.conn.lock().unwrap();
320        let now = chrono::Utc::now().timestamp_millis();
321        conn.execute(
322            "UPDATE skills
323             SET remote_revision = ?1, update_status = ?2, last_checked_at = ?3, last_check_error = ?4
324             WHERE id = ?5",
325            params![remote_revision, update_status, now, last_check_error, id],
326        )?;
327        Ok(())
328    }
329
330    pub fn update_skill_update_status(&self, id: &str, update_status: &str) -> Result<()> {
331        let conn = self.conn.lock().unwrap();
332        conn.execute(
333            "UPDATE skills SET update_status = ?1 WHERE id = ?2",
334            params![update_status, id],
335        )?;
336        Ok(())
337    }
338
339    pub fn update_skill_enabled(&self, id: &str, enabled: bool) -> Result<()> {
340        let conn = self.conn.lock().unwrap();
341        let now = chrono::Utc::now().timestamp_millis();
342        conn.execute(
343            "UPDATE skills SET enabled = ?1, updated_at = ?2 WHERE id = ?3",
344            params![enabled, now, id],
345        )?;
346        Ok(())
347    }
348
349    pub fn rename_skill(&self, id: &str, new_name: &str) -> Result<()> {
350        let conn = self.conn.lock().unwrap();
351        let now = chrono::Utc::now().timestamp_millis();
352        let changed = conn.execute(
353            "UPDATE skills SET name = ?1, updated_at = ?2 WHERE id = ?3",
354            params![new_name, now, id],
355        )?;
356        anyhow::ensure!(changed > 0, "skill not found: {id}");
357        Ok(())
358    }
359
360    pub fn update_central_path(&self, id: &str, new_path: &str) -> Result<()> {
361        let conn = self.conn.lock().unwrap();
362        let now = chrono::Utc::now().timestamp_millis();
363        let changed = conn.execute(
364            "UPDATE skills SET central_path = ?1, updated_at = ?2 WHERE id = ?3",
365            params![new_path, now, id],
366        )?;
367        anyhow::ensure!(changed > 0, "skill not found: {id}");
368        Ok(())
369    }
370
371    #[allow(clippy::too_many_arguments)]
372    pub fn update_skill_after_install(
373        &self,
374        id: &str,
375        name: &str,
376        description: Option<&str>,
377        source_revision: Option<&str>,
378        remote_revision: Option<&str>,
379        content_hash: Option<&str>,
380        update_status: &str,
381    ) -> Result<()> {
382        let conn = self.conn.lock().unwrap();
383        let now = chrono::Utc::now().timestamp_millis();
384        conn.execute(
385            "UPDATE skills
386             SET name = ?1, description = ?2, source_revision = ?3, remote_revision = ?4, content_hash = ?5,
387                 updated_at = ?6, update_status = ?7, last_checked_at = ?6, last_check_error = NULL
388             WHERE id = ?8",
389            params![
390                name,
391                description,
392                source_revision,
393                remote_revision,
394                content_hash,
395                now,
396                update_status,
397                id
398            ],
399        )?;
400        Ok(())
401    }
402
403    pub fn update_skill_source_ref(&self, id: &str, source_ref: &str) -> Result<()> {
404        let conn = self.conn.lock().unwrap();
405        conn.execute(
406            "UPDATE skills SET source_ref = ?1 WHERE id = ?2",
407            params![source_ref, id],
408        )?;
409        Ok(())
410    }
411
412    #[allow(clippy::too_many_arguments)]
413    pub fn update_skill_after_reinstall(
414        &self,
415        id: &str,
416        name: &str,
417        description: Option<&str>,
418        source_type: &str,
419        source_ref: Option<&str>,
420        source_ref_resolved: Option<&str>,
421        source_subpath: Option<&str>,
422        source_branch: Option<&str>,
423        source_revision: Option<&str>,
424        remote_revision: Option<&str>,
425        content_hash: Option<&str>,
426        update_status: &str,
427    ) -> Result<()> {
428        let conn = self.conn.lock().unwrap();
429        let now = chrono::Utc::now().timestamp_millis();
430        conn.execute(
431            "UPDATE skills
432             SET name = ?1, description = ?2, source_type = ?3, source_ref = ?4, source_ref_resolved = ?5,
433                 source_subpath = ?6, source_branch = ?7, source_revision = ?8, remote_revision = ?9,
434                 content_hash = ?10, updated_at = ?11, status = 'ok', update_status = ?12, last_checked_at = ?11,
435                 last_check_error = NULL
436             WHERE id = ?13",
437            params![
438                name,
439                description,
440                source_type,
441                source_ref,
442                source_ref_resolved,
443                source_subpath,
444                source_branch,
445                source_revision,
446                remote_revision,
447                content_hash,
448                now,
449                update_status,
450                id
451            ],
452        )?;
453        Ok(())
454    }
455
456    /// Park every skill's `central_path` on a unique placeholder before a
457    /// reindex rewrites them. Path reassignments between existing skills
458    /// (renames, collision reshuffles after a merge) would otherwise collide
459    /// with the UNIQUE constraint mid-loop — e.g. skill A moving onto the
460    /// path skill B is about to vacate.
461    pub fn park_central_paths_for_reindex(&self) -> Result<()> {
462        let conn = self.conn.lock().unwrap();
463        conn.execute(
464            "UPDATE skills SET central_path = 'sm-reindex-parked://' || id",
465            [],
466        )?;
467        Ok(())
468    }
469
470    pub fn delete_skill(&self, id: &str) -> Result<()> {
471        let conn = self.conn.lock().unwrap();
472        conn.execute("DELETE FROM skills WHERE id = ?1", params![id])?;
473        Ok(())
474    }
475
476    // ── Targets ──
477
478    pub fn insert_target(&self, target: &SkillTargetRecord) -> Result<()> {
479        let conn = self.conn.lock().unwrap();
480        conn.execute(
481            "INSERT OR REPLACE INTO skill_targets (id, skill_id, tool, target_path, mode, status, synced_at, last_error, source_hash)
482             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
483            params![
484                target.id,
485                target.skill_id,
486                target.tool,
487                target.target_path,
488                target.mode,
489                target.status,
490                target.synced_at,
491                target.last_error,
492                target.source_hash,
493            ],
494        )?;
495        Ok(())
496    }
497
498    pub fn get_targets_for_skill(&self, skill_id: &str) -> Result<Vec<SkillTargetRecord>> {
499        let conn = self.conn.lock().unwrap();
500        let mut stmt = conn.prepare(
501            "SELECT id, skill_id, tool, target_path, mode, status, synced_at, last_error, source_hash FROM skill_targets WHERE skill_id = ?1",
502        )?;
503        let rows = stmt.query_map(params![skill_id], |row| {
504            Ok(SkillTargetRecord {
505                id: row.get(0)?,
506                skill_id: row.get(1)?,
507                tool: row.get(2)?,
508                target_path: row.get(3)?,
509                mode: row.get(4)?,
510                status: row.get(5)?,
511                synced_at: row.get(6)?,
512                last_error: row.get(7)?,
513                source_hash: row.get(8)?,
514            })
515        })?;
516        Ok(rows.filter_map(|r| r.ok()).collect())
517    }
518
519    pub fn get_all_targets(&self) -> Result<Vec<SkillTargetRecord>> {
520        let conn = self.conn.lock().unwrap();
521        let mut stmt = conn.prepare(
522            "SELECT id, skill_id, tool, target_path, mode, status, synced_at, last_error, source_hash FROM skill_targets",
523        )?;
524        let rows = stmt.query_map([], |row| {
525            Ok(SkillTargetRecord {
526                id: row.get(0)?,
527                skill_id: row.get(1)?,
528                tool: row.get(2)?,
529                target_path: row.get(3)?,
530                mode: row.get(4)?,
531                status: row.get(5)?,
532                synced_at: row.get(6)?,
533                last_error: row.get(7)?,
534                source_hash: row.get(8)?,
535            })
536        })?;
537        Ok(rows.filter_map(|r| r.ok()).collect())
538    }
539
540    pub fn delete_target(&self, skill_id: &str, tool: &str) -> Result<()> {
541        let conn = self.conn.lock().unwrap();
542        conn.execute(
543            "DELETE FROM skill_targets WHERE skill_id = ?1 AND tool = ?2",
544            params![skill_id, tool],
545        )?;
546        Ok(())
547    }
548
549    // ── Discovered Skills ──
550
551    pub fn clear_discovered(&self) -> Result<()> {
552        let conn = self.conn.lock().unwrap();
553        conn.execute("DELETE FROM discovered_skills", [])?;
554        Ok(())
555    }
556
557    pub fn insert_discovered(&self, rec: &DiscoveredSkillRecord) -> Result<()> {
558        let conn = self.conn.lock().unwrap();
559        conn.execute(
560            "INSERT INTO discovered_skills (id, tool, found_path, name_guess, fingerprint, found_at, imported_skill_id)
561             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
562            params![
563                rec.id,
564                rec.tool,
565                rec.found_path,
566                rec.name_guess,
567                rec.fingerprint,
568                rec.found_at,
569                rec.imported_skill_id,
570            ],
571        )?;
572        Ok(())
573    }
574
575    pub fn get_all_discovered(&self) -> Result<Vec<DiscoveredSkillRecord>> {
576        let conn = self.conn.lock().unwrap();
577        let mut stmt = conn.prepare(
578            "SELECT id, tool, found_path, name_guess, fingerprint, found_at, imported_skill_id FROM discovered_skills",
579        )?;
580        let rows = stmt.query_map([], |row| {
581            Ok(DiscoveredSkillRecord {
582                id: row.get(0)?,
583                tool: row.get(1)?,
584                found_path: row.get(2)?,
585                name_guess: row.get(3)?,
586                fingerprint: row.get(4)?,
587                found_at: row.get(5)?,
588                imported_skill_id: row.get(6)?,
589            })
590        })?;
591        Ok(rows.filter_map(|r| r.ok()).collect())
592    }
593
594    // ── Cache ──
595
596    pub fn get_cache(&self, key: &str, ttl_secs: i64) -> Result<Option<String>> {
597        let conn = self.conn.lock().unwrap();
598        let now = chrono::Utc::now().timestamp();
599        let mut stmt = conn
600            .prepare("SELECT data FROM skillssh_cache WHERE cache_key = ?1 AND fetched_at > ?2")?;
601        let cutoff = now - ttl_secs;
602        let mut rows = stmt.query_map(params![key, cutoff], |row| row.get::<_, String>(0))?;
603        Ok(rows.next().and_then(|r| r.ok()))
604    }
605
606    pub fn set_cache(&self, key: &str, data: &str) -> Result<()> {
607        let conn = self.conn.lock().unwrap();
608        let now = chrono::Utc::now().timestamp();
609        conn.execute(
610            "INSERT OR REPLACE INTO skillssh_cache (cache_key, data, fetched_at) VALUES (?1, ?2, ?3)",
611            params![key, data, now],
612        )?;
613        Ok(())
614    }
615
616    // ── Pending conflicts (merge-engine design §4) ──
617    // A rebuildable UI projection of the trailer-derived pending set; never
618    // an input to merge decisions.
619
620    pub fn replace_pending_conflicts(&self, rows: &[PendingConflictRow]) -> Result<()> {
621        let mut conn = self.conn.lock().unwrap();
622        let tx = conn.transaction()?;
623        tx.execute("DELETE FROM pending_conflicts", [])?;
624        for row in rows {
625            tx.execute(
626                "INSERT OR REPLACE INTO pending_conflicts
627                 (skill_id, theirs_commit, theirs_path, detected_at)
628                 VALUES (?1, ?2, ?3, ?4)",
629                params![
630                    row.skill_id,
631                    row.theirs_commit,
632                    row.theirs_path,
633                    row.detected_at
634                ],
635            )?;
636        }
637        tx.commit()?;
638        Ok(())
639    }
640
641    pub fn list_pending_conflicts(&self) -> Result<Vec<PendingConflictRow>> {
642        let conn = self.conn.lock().unwrap();
643        let mut stmt = conn.prepare(
644            "SELECT skill_id, theirs_commit, theirs_path, detected_at
645             FROM pending_conflicts ORDER BY detected_at DESC, skill_id",
646        )?;
647        let rows = stmt
648            .query_map([], |row| {
649                Ok(PendingConflictRow {
650                    skill_id: row.get(0)?,
651                    theirs_commit: row.get(1)?,
652                    theirs_path: row.get(2)?,
653                    detected_at: row.get(3)?,
654                })
655            })?
656            .collect::<std::result::Result<Vec<_>, _>>()?;
657        Ok(rows)
658    }
659
660    /// Changes when another connection commits to this database.
661    pub(super) fn data_version(&self) -> rusqlite::Result<u64> {
662        self.conn
663            .lock()
664            .unwrap()
665            .pragma_query_value(None, "data_version", |row| row.get(0))
666    }
667
668    // ── Settings ──
669
670    pub fn proxy_url(&self) -> Option<String> {
671        self.get_setting("proxy_url")
672            .ok()
673            .flatten()
674            .filter(|s| !s.is_empty())
675    }
676
677    pub fn get_setting(&self, key: &str) -> Result<Option<String>> {
678        // Read the raw stored value while holding the lock, then release it
679        // before any write-back so we don't re-enter the mutex.
680        let raw = {
681            let conn = self.conn.lock().unwrap();
682            let mut stmt = conn.prepare("SELECT value FROM settings WHERE key = ?1")?;
683            let mut rows = stmt.query_map(params![key], |row| row.get::<_, String>(0))?;
684            rows.next().and_then(|r| r.ok())
685        };
686
687        let value = match raw {
688            None => return Ok(None),
689            Some(v) => v,
690        };
691
692        if SENSITIVE_KEYS.contains(&key) {
693            if crypto::is_encrypted(&value) {
694                // Happy path: already encrypted, just decrypt.
695                Ok(Some(crypto::decrypt(&self.secret_key, &value)?))
696            } else {
697                // Backward compat: old plaintext value — upgrade it silently.
698                let encrypted = crypto::encrypt(&self.secret_key, &value)?;
699                let conn = self.conn.lock().unwrap();
700                conn.execute(
701                    "INSERT OR REPLACE INTO settings (key, value) VALUES (?1, ?2)",
702                    params![key, encrypted],
703                )?;
704                Ok(Some(value))
705            }
706        } else {
707            Ok(Some(value))
708        }
709    }
710
711    pub fn set_setting(&self, key: &str, value: &str) -> Result<()> {
712        let stored = if SENSITIVE_KEYS.contains(&key) {
713            crypto::encrypt(&self.secret_key, value)?
714        } else {
715            value.to_string()
716        };
717        let conn = self.conn.lock().unwrap();
718        conn.execute(
719            "INSERT OR REPLACE INTO settings (key, value) VALUES (?1, ?2)",
720            params![key, stored],
721        )?;
722        Ok(())
723    }
724
725    pub fn remap_tool_key_references(&self, old_key: &str, new_key: &str) -> Result<()> {
726        if old_key == new_key {
727            return Ok(());
728        }
729        let conn = self.conn.lock().unwrap();
730
731        // scenario_skill_tools has a composite PK (scenario_id, skill_id, tool). If both old/new
732        // rows exist for the same skill in the same scenario, keep the new-key row.
733        conn.execute(
734            "DELETE FROM scenario_skill_tools AS old_rows
735             WHERE old_rows.tool = ?1
736               AND EXISTS (
737                 SELECT 1
738                 FROM scenario_skill_tools AS new_rows
739                 WHERE new_rows.tool = ?2
740                   AND new_rows.scenario_id = old_rows.scenario_id
741                   AND new_rows.skill_id = old_rows.skill_id
742               )",
743            params![old_key, new_key],
744        )?;
745        conn.execute(
746            "UPDATE scenario_skill_tools SET tool = ?2 WHERE tool = ?1",
747            params![old_key, new_key],
748        )?;
749
750        // skill_targets has UNIQUE(skill_id, tool). Same strategy: keep existing new-key rows.
751        conn.execute(
752            "DELETE FROM skill_targets AS old_rows
753             WHERE old_rows.tool = ?1
754               AND EXISTS (
755                 SELECT 1
756                 FROM skill_targets AS new_rows
757                 WHERE new_rows.tool = ?2
758                   AND new_rows.skill_id = old_rows.skill_id
759               )",
760            params![old_key, new_key],
761        )?;
762        conn.execute(
763            "UPDATE skill_targets SET tool = ?2 WHERE tool = ?1",
764            params![old_key, new_key],
765        )?;
766
767        conn.execute(
768            "UPDATE discovered_skills SET tool = ?2 WHERE tool = ?1",
769            params![old_key, new_key],
770        )?;
771        Ok(())
772    }
773
774    pub fn has_tool_key_references(&self, key: &str) -> Result<bool> {
775        let conn = self.conn.lock().unwrap();
776        let mut stmt = conn.prepare(
777            "SELECT EXISTS(SELECT 1 FROM skill_targets WHERE tool = ?1)
778             OR EXISTS(SELECT 1 FROM discovered_skills WHERE tool = ?1)
779             OR EXISTS(SELECT 1 FROM scenario_skill_tools WHERE tool = ?1)",
780        )?;
781        let exists: i64 = stmt.query_row(params![key], |row| row.get(0))?;
782        Ok(exists != 0)
783    }
784
785    // ── Scenarios ──
786
787    pub fn insert_scenario(&self, scenario: &ScenarioRecord) -> Result<()> {
788        let conn = self.conn.lock().unwrap();
789        conn.execute(
790            "INSERT INTO scenarios (id, name, description, icon, sort_order, created_at, updated_at)
791             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
792            params![
793                scenario.id,
794                scenario.name,
795                scenario.description,
796                scenario.icon,
797                scenario.sort_order,
798                scenario.created_at,
799                scenario.updated_at,
800            ],
801        )?;
802        Ok(())
803    }
804
805    pub fn get_all_scenarios(&self) -> Result<Vec<ScenarioRecord>> {
806        let conn = self.conn.lock().unwrap();
807        let mut stmt = conn.prepare(
808            "SELECT id, name, description, icon, sort_order, created_at, updated_at FROM scenarios ORDER BY sort_order, created_at",
809        )?;
810        let rows = stmt.query_map([], |row| {
811            Ok(ScenarioRecord {
812                id: row.get(0)?,
813                name: row.get(1)?,
814                description: row.get(2)?,
815                icon: row.get(3)?,
816                sort_order: row.get(4)?,
817                created_at: row.get(5)?,
818                updated_at: row.get(6)?,
819            })
820        })?;
821        Ok(rows.filter_map(|r| r.ok()).collect())
822    }
823
824    pub fn update_scenario(
825        &self,
826        id: &str,
827        name: &str,
828        description: Option<&str>,
829        icon: Option<&str>,
830    ) -> Result<()> {
831        let conn = self.conn.lock().unwrap();
832        let now = chrono::Utc::now().timestamp_millis();
833        conn.execute(
834            "UPDATE scenarios SET name = ?1, description = ?2, icon = ?3, updated_at = ?4 WHERE id = ?5",
835            params![name, description, icon, now, id],
836        )?;
837        Ok(())
838    }
839
840    pub fn delete_scenario(&self, id: &str) -> Result<()> {
841        let conn = self.conn.lock().unwrap();
842        conn.execute("DELETE FROM scenarios WHERE id = ?1", params![id])?;
843        Ok(())
844    }
845
846    pub fn reorder_scenarios(&self, ids: &[String]) -> Result<()> {
847        let conn = self.conn.lock().unwrap();
848        let tx = conn.unchecked_transaction()?;
849        for (i, id) in ids.iter().enumerate() {
850            tx.execute(
851                "UPDATE scenarios SET sort_order = ?1 WHERE id = ?2",
852                params![i as i32, id],
853            )?;
854        }
855        tx.commit()?;
856        Ok(())
857    }
858
859    pub fn reorder_projects(&self, ids: &[String]) -> Result<()> {
860        let conn = self.conn.lock().unwrap();
861        let tx = conn.unchecked_transaction()?;
862        for (i, id) in ids.iter().enumerate() {
863            tx.execute(
864                "UPDATE projects SET sort_order = ?1 WHERE id = ?2",
865                params![i as i32, id],
866            )?;
867        }
868        tx.commit()?;
869        Ok(())
870    }
871
872    // ── Scenario-Skill mapping ──
873
874    pub fn add_skill_to_scenario(&self, scenario_id: &str, skill_id: &str) -> Result<()> {
875        let conn = self.conn.lock().unwrap();
876        let now = chrono::Utc::now().timestamp_millis();
877        conn.execute(
878            "DELETE FROM scenario_skills WHERE skill_id = ?1 AND scenario_id != ?2",
879            params![skill_id, scenario_id],
880        )?;
881        conn.execute(
882            "INSERT OR IGNORE INTO scenario_skills (scenario_id, skill_id, added_at) VALUES (?1, ?2, ?3)",
883            params![scenario_id, skill_id, now],
884        )?;
885        Ok(())
886    }
887
888    pub fn remove_skill_from_scenario(&self, scenario_id: &str, skill_id: &str) -> Result<()> {
889        let conn = self.conn.lock().unwrap();
890        conn.execute(
891            "DELETE FROM scenario_skills WHERE scenario_id = ?1 AND skill_id = ?2",
892            params![scenario_id, skill_id],
893        )?;
894        Ok(())
895    }
896
897    pub fn reorder_scenario_skills(&self, scenario_id: &str, skill_ids: &[String]) -> Result<()> {
898        let conn = self.conn.lock().unwrap();
899        let tx = conn.unchecked_transaction()?;
900        for (i, skill_id) in skill_ids.iter().enumerate() {
901            tx.execute(
902                "UPDATE scenario_skills SET sort_order = ?1 WHERE scenario_id = ?2 AND skill_id = ?3",
903                params![i as i32, scenario_id, skill_id],
904            )?;
905        }
906        tx.commit()?;
907        Ok(())
908    }
909
910    pub fn get_skill_ids_for_scenario(&self, scenario_id: &str) -> Result<Vec<String>> {
911        let conn = self.conn.lock().unwrap();
912        let mut stmt = conn.prepare(
913            "SELECT skill_id FROM scenario_skills WHERE scenario_id = ?1 ORDER BY sort_order, added_at",
914        )?;
915        let rows = stmt.query_map(params![scenario_id], |row| row.get::<_, String>(0))?;
916        Ok(rows.filter_map(|r| r.ok()).collect())
917    }
918
919    pub fn get_skills_for_scenario(&self, scenario_id: &str) -> Result<Vec<SkillRecord>> {
920        let conn = self.conn.lock().unwrap();
921        let mut stmt = conn.prepare(
922            "SELECT s.id, s.name, s.description, s.source_type, s.source_ref, s.source_ref_resolved, s.source_subpath,
923                    s.source_branch, s.source_revision, s.source_agent, s.remote_revision, s.central_path, s.content_hash, s.enabled,
924                    s.created_at, s.updated_at, s.status, s.update_status, s.last_checked_at, s.last_check_error
925             FROM skills s
926             INNER JOIN scenario_skills ss ON s.id = ss.skill_id
927             WHERE ss.scenario_id = ?1
928             ORDER BY ss.sort_order, s.name",
929        )?;
930        let rows = stmt.query_map(params![scenario_id], map_skill_row)?;
931        Ok(rows.filter_map(|r| r.ok()).collect())
932    }
933
934    pub fn count_skills_for_scenario(&self, scenario_id: &str) -> Result<i64> {
935        let conn = self.conn.lock().unwrap();
936        let count: i64 = conn.query_row(
937            "SELECT COUNT(*) FROM scenario_skills WHERE scenario_id = ?1",
938            params![scenario_id],
939            |row| row.get(0),
940        )?;
941        Ok(count)
942    }
943
944    pub fn get_scenarios_for_skill(&self, skill_id: &str) -> Result<Vec<String>> {
945        let conn = self.conn.lock().unwrap();
946        let mut stmt =
947            conn.prepare("SELECT scenario_id FROM scenario_skills WHERE skill_id = ?1")?;
948        let rows = stmt.query_map(params![skill_id], |row| row.get::<_, String>(0))?;
949        Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
950    }
951
952    pub fn ensure_scenario_skill_tool_defaults(
953        &self,
954        scenario_id: &str,
955        skill_id: &str,
956        tools: &[String],
957    ) -> Result<()> {
958        if tools.is_empty() {
959            return Ok(());
960        }
961
962        let conn = self.conn.lock().unwrap();
963        let mut existing_stmt = conn.prepare(
964            "SELECT tool
965             FROM scenario_skill_tools
966             WHERE scenario_id = ?1 AND skill_id = ?2",
967        )?;
968        let existing_rows = existing_stmt.query_map(params![scenario_id, skill_id], |row| {
969            row.get::<_, String>(0)
970        })?;
971        let existing_tools: std::collections::HashSet<String> = existing_rows
972            .collect::<rusqlite::Result<Vec<_>>>()?
973            .into_iter()
974            .collect();
975
976        let missing_tools: Vec<&String> = tools
977            .iter()
978            .filter(|tool| !existing_tools.contains(*tool))
979            .collect();
980        if missing_tools.is_empty() {
981            return Ok(());
982        }
983
984        let tx = conn.unchecked_transaction()?;
985        let now = chrono::Utc::now().timestamp_millis();
986
987        for tool in missing_tools {
988            tx.execute(
989                "INSERT OR IGNORE INTO scenario_skill_tools (scenario_id, skill_id, tool, enabled, updated_at)
990                 VALUES (?1, ?2, ?3, 1, ?4)",
991                params![scenario_id, skill_id, tool, now],
992            )?;
993        }
994
995        tx.commit()?;
996        Ok(())
997    }
998
999    pub fn set_scenario_skill_tool_enabled(
1000        &self,
1001        scenario_id: &str,
1002        skill_id: &str,
1003        tool: &str,
1004        enabled: bool,
1005    ) -> Result<()> {
1006        let conn = self.conn.lock().unwrap();
1007        let now = chrono::Utc::now().timestamp_millis();
1008        conn.execute(
1009            "INSERT INTO scenario_skill_tools (scenario_id, skill_id, tool, enabled, updated_at)
1010             VALUES (?1, ?2, ?3, ?4, ?5)
1011             ON CONFLICT(scenario_id, skill_id, tool)
1012             DO UPDATE SET enabled = excluded.enabled, updated_at = excluded.updated_at",
1013            params![scenario_id, skill_id, tool, enabled, now],
1014        )?;
1015        Ok(())
1016    }
1017
1018    pub fn replace_scenarios_from_metadata(
1019        &self,
1020        scenarios: &[super::sync_metadata::ScenarioMetaFile],
1021    ) -> Result<()> {
1022        let conn = self.conn.lock().unwrap();
1023        let tx = conn.unchecked_transaction()?;
1024        let metadata_ids: std::collections::HashSet<&str> =
1025            scenarios.iter().map(|s| s.scenario_id.as_str()).collect();
1026        {
1027            let mut stmt = tx.prepare("SELECT id FROM scenarios")?;
1028            let ids = stmt
1029                .query_map([], |row| row.get::<_, String>(0))?
1030                .collect::<rusqlite::Result<Vec<_>>>()?;
1031            for id in ids {
1032                if !metadata_ids.contains(id.as_str()) {
1033                    tx.execute("DELETE FROM scenarios WHERE id = ?1", params![id])?;
1034                }
1035            }
1036        }
1037        let now = chrono::Utc::now().timestamp_millis();
1038        for scenario in scenarios {
1039            tx.execute(
1040                "INSERT INTO scenarios (id, name, description, icon, sort_order, created_at, updated_at)
1041                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6)
1042                 ON CONFLICT(id) DO UPDATE SET
1043                    name = excluded.name,
1044                    description = excluded.description,
1045                    icon = excluded.icon,
1046                    sort_order = excluded.sort_order,
1047                    updated_at = excluded.updated_at",
1048                params![
1049                    scenario.scenario_id,
1050                    scenario.name,
1051                    scenario.description,
1052                    scenario.icon,
1053                    scenario.sort_order,
1054                    now,
1055                ],
1056            )?;
1057        }
1058        tx.commit()?;
1059        Ok(())
1060    }
1061
1062    pub fn replace_scenario_memberships_from_metadata(
1063        &self,
1064        memberships: &[super::sync_metadata::ScenarioSkillMetaFile],
1065    ) -> Result<()> {
1066        let conn = self.conn.lock().unwrap();
1067        let tx = conn.unchecked_transaction()?;
1068        tx.execute("DELETE FROM scenario_skill_tools", [])?;
1069        tx.execute("DELETE FROM scenario_skills", [])?;
1070
1071        // OR IGNORE / OR REPLACE don't suppress FK violations in SQLite, so we
1072        // must skip memberships that reference skills or scenarios no longer in the DB.
1073        let valid_skill_ids: std::collections::HashSet<String> = {
1074            let mut stmt = tx.prepare("SELECT id FROM skills")?;
1075            let ids: rusqlite::Result<std::collections::HashSet<String>> =
1076                stmt.query_map([], |row| row.get::<_, String>(0))?.collect();
1077            ids?
1078        };
1079        let valid_scenario_ids: std::collections::HashSet<String> = {
1080            let mut stmt = tx.prepare("SELECT id FROM scenarios")?;
1081            let ids: rusqlite::Result<std::collections::HashSet<String>> =
1082                stmt.query_map([], |row| row.get::<_, String>(0))?.collect();
1083            ids?
1084        };
1085
1086        let now = chrono::Utc::now().timestamp_millis();
1087        for member in memberships {
1088            if !valid_skill_ids.contains(&member.skill_id)
1089                || !valid_scenario_ids.contains(&member.scenario_id)
1090            {
1091                log::warn!(
1092                    "Skipping stale scenario membership (scenario_id={}, skill_id={}): referenced skill or scenario no longer exists",
1093                    member.scenario_id,
1094                    member.skill_id
1095                );
1096                continue;
1097            }
1098            tx.execute(
1099                "INSERT OR IGNORE INTO scenario_skills (scenario_id, skill_id, added_at, sort_order)
1100                 VALUES (?1, ?2, ?3, ?4)",
1101                params![
1102                    member.scenario_id,
1103                    member.skill_id,
1104                    now,
1105                    member.sort_order,
1106                ],
1107            )?;
1108            for (tool, enabled) in &member.tools {
1109                tx.execute(
1110                    "INSERT OR REPLACE INTO scenario_skill_tools (scenario_id, skill_id, tool, enabled, updated_at)
1111                     VALUES (?1, ?2, ?3, ?4, ?5)",
1112                    params![
1113                        member.scenario_id,
1114                        member.skill_id,
1115                        tool,
1116                        enabled,
1117                        now,
1118                    ],
1119                )?;
1120            }
1121        }
1122        tx.commit()?;
1123        Ok(())
1124    }
1125
1126    pub fn get_scenario_skill_tool_toggles(
1127        &self,
1128        scenario_id: &str,
1129        skill_id: &str,
1130    ) -> Result<Vec<ScenarioSkillToolToggleRecord>> {
1131        let conn = self.conn.lock().unwrap();
1132        let mut stmt = conn.prepare(
1133            "SELECT scenario_id, skill_id, tool, enabled, updated_at
1134             FROM scenario_skill_tools
1135             WHERE scenario_id = ?1 AND skill_id = ?2
1136             ORDER BY tool",
1137        )?;
1138        let rows = stmt.query_map(params![scenario_id, skill_id], |row| {
1139            Ok(ScenarioSkillToolToggleRecord {
1140                scenario_id: row.get(0)?,
1141                skill_id: row.get(1)?,
1142                tool: row.get(2)?,
1143                enabled: row.get(3)?,
1144                updated_at: row.get(4)?,
1145            })
1146        })?;
1147        Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
1148    }
1149
1150    pub fn get_enabled_tools_for_scenario_skill(
1151        &self,
1152        scenario_id: &str,
1153        skill_id: &str,
1154    ) -> Result<Vec<String>> {
1155        let conn = self.conn.lock().unwrap();
1156        let mut stmt = conn.prepare(
1157            "SELECT tool
1158             FROM scenario_skill_tools
1159             WHERE scenario_id = ?1 AND skill_id = ?2 AND enabled = 1",
1160        )?;
1161        let rows = stmt.query_map(params![scenario_id, skill_id], |row| {
1162            row.get::<_, String>(0)
1163        })?;
1164        Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
1165    }
1166
1167    // ── Active Scenario ──
1168
1169    pub fn get_active_scenario_id(&self) -> Result<Option<String>> {
1170        let conn = self.conn.lock().unwrap();
1171        let mut stmt =
1172            conn.prepare("SELECT scenario_id FROM active_scenario WHERE key = 'current'")?;
1173        let mut rows = stmt.query_map([], |row| row.get::<_, Option<String>>(0))?;
1174        Ok(rows.next().and_then(|r| r.ok()).flatten())
1175    }
1176
1177    pub fn clear_active_scenario(&self) -> Result<()> {
1178        let conn = self.conn.lock().unwrap();
1179        conn.execute("DELETE FROM active_scenario WHERE key = 'current'", [])?;
1180        Ok(())
1181    }
1182
1183    pub fn set_active_scenario(&self, scenario_id: &str) -> Result<()> {
1184        let conn = self.conn.lock().unwrap();
1185        conn.execute(
1186            "INSERT OR REPLACE INTO active_scenario (key, scenario_id) VALUES ('current', ?1)",
1187            params![scenario_id],
1188        )?;
1189        Ok(())
1190    }
1191
1192    // ── Projects ──
1193
1194    pub fn insert_project(&self, project: &ProjectRecord) -> Result<()> {
1195        let conn = self.conn.lock().unwrap();
1196        conn.execute(
1197            "INSERT INTO projects (
1198                id, name, path, workspace_type, linked_agent_key, linked_agent_name, disabled_path,
1199                sort_order, created_at, updated_at, visited_at
1200             )
1201             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
1202            params![
1203                project.id,
1204                project.name,
1205                project.path,
1206                project.workspace_type,
1207                project.linked_agent_key,
1208                project.linked_agent_name,
1209                project.disabled_path,
1210                project.sort_order,
1211                project.created_at,
1212                project.updated_at,
1213                project.visited_at,
1214            ],
1215        )?;
1216        Ok(())
1217    }
1218
1219    pub fn get_all_projects(&self) -> Result<Vec<ProjectRecord>> {
1220        let conn = self.conn.lock().unwrap();
1221        let mut stmt = conn.prepare(
1222            "SELECT id, name, path, workspace_type, linked_agent_key, linked_agent_name, disabled_path,
1223                    sort_order, created_at, updated_at, visited_at
1224             FROM projects
1225             ORDER BY sort_order, created_at",
1226        )?;
1227        let rows = stmt.query_map([], |row| {
1228            Ok(ProjectRecord {
1229                id: row.get(0)?,
1230                name: row.get(1)?,
1231                path: row.get(2)?,
1232                workspace_type: row.get(3)?,
1233                linked_agent_key: row.get(4)?,
1234                linked_agent_name: row.get(5)?,
1235                disabled_path: row.get(6)?,
1236                sort_order: row.get(7)?,
1237                created_at: row.get(8)?,
1238                updated_at: row.get(9)?,
1239                visited_at: row.get(10)?,
1240            })
1241        })?;
1242        Ok(rows.filter_map(|r| r.ok()).collect())
1243    }
1244
1245    pub fn get_project_by_id(&self, id: &str) -> Result<Option<ProjectRecord>> {
1246        let conn = self.conn.lock().unwrap();
1247        let mut stmt = conn.prepare(
1248            "SELECT id, name, path, workspace_type, linked_agent_key, linked_agent_name, disabled_path,
1249                    sort_order, created_at, updated_at, visited_at
1250             FROM projects
1251             WHERE id = ?1",
1252        )?;
1253        let mut rows = stmt.query_map(params![id], |row| {
1254            Ok(ProjectRecord {
1255                id: row.get(0)?,
1256                name: row.get(1)?,
1257                path: row.get(2)?,
1258                workspace_type: row.get(3)?,
1259                linked_agent_key: row.get(4)?,
1260                linked_agent_name: row.get(5)?,
1261                disabled_path: row.get(6)?,
1262                sort_order: row.get(7)?,
1263                created_at: row.get(8)?,
1264                updated_at: row.get(9)?,
1265                visited_at: row.get(10)?,
1266            })
1267        })?;
1268        Ok(rows.next().and_then(|r| r.ok()))
1269    }
1270
1271    pub fn delete_project(&self, id: &str) -> Result<()> {
1272        let conn = self.conn.lock().unwrap();
1273        conn.execute("DELETE FROM projects WHERE id = ?1", params![id])?;
1274        Ok(())
1275    }
1276
1277    // ── Skill Tags ──
1278
1279    pub fn get_all_tags(&self) -> Result<Vec<String>> {
1280        let conn = self.conn.lock().unwrap();
1281        let mut stmt = conn.prepare("SELECT DISTINCT tag FROM skill_tags ORDER BY tag")?;
1282        let rows = stmt.query_map([], |row| row.get::<_, String>(0))?;
1283        Ok(rows.filter_map(|r| r.ok()).collect())
1284    }
1285
1286    pub fn set_tags_for_skill(&self, skill_id: &str, tags: &[String]) -> Result<()> {
1287        let conn = self.conn.lock().unwrap();
1288        conn.execute(
1289            "DELETE FROM skill_tags WHERE skill_id = ?1",
1290            params![skill_id],
1291        )?;
1292        for tag in tags {
1293            let trimmed = tag.trim();
1294            if !trimmed.is_empty() {
1295                conn.execute(
1296                    "INSERT OR IGNORE INTO skill_tags (skill_id, tag) VALUES (?1, ?2)",
1297                    params![skill_id, trimmed],
1298                )?;
1299            }
1300        }
1301        Ok(())
1302    }
1303
1304    pub fn get_tags_map(&self) -> Result<std::collections::HashMap<String, Vec<String>>> {
1305        let conn = self.conn.lock().unwrap();
1306        let mut stmt = conn.prepare("SELECT skill_id, tag FROM skill_tags ORDER BY tag")?;
1307        let rows = stmt.query_map([], |row| {
1308            Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
1309        })?;
1310        let mut map: std::collections::HashMap<String, Vec<String>> =
1311            std::collections::HashMap::new();
1312        for row in rows.filter_map(|r| r.ok()) {
1313            map.entry(row.0).or_default().push(row.1);
1314        }
1315        Ok(map)
1316    }
1317
1318    /// Globally rename a tag across every skill that carries it. Returns the
1319    /// ids of the affected skills so the caller can refresh their metadata.
1320    /// If a skill already has `new`, the rows are merged (no duplicate) thanks
1321    /// to `UPDATE OR IGNORE` followed by removing any leftover old rows.
1322    pub fn rename_tag(&self, old: &str, new: &str) -> Result<Vec<String>> {
1323        let conn = self.conn.lock().unwrap();
1324        let affected: Vec<String> = {
1325            let mut stmt =
1326                conn.prepare("SELECT DISTINCT skill_id FROM skill_tags WHERE tag = ?1")?;
1327            let rows = stmt.query_map(params![old], |row| row.get::<_, String>(0))?;
1328            rows.filter_map(|r| r.ok()).collect()
1329        };
1330        // Guard self-rename: the cleanup DELETE below would otherwise wipe the
1331        // tag entirely (the UPDATE is a no-op when old == new).
1332        if old == new {
1333            return Ok(affected);
1334        }
1335        // One transaction so a crash can't leave the tag half-renamed (the
1336        // non-conflicting rows updated while merged rows still hold `old`).
1337        let tx = conn.unchecked_transaction()?;
1338        tx.execute(
1339            "UPDATE OR IGNORE skill_tags SET tag = ?1 WHERE tag = ?2",
1340            params![new, old],
1341        )?;
1342        tx.execute("DELETE FROM skill_tags WHERE tag = ?1", params![old])?;
1343        tx.commit()?;
1344        Ok(affected)
1345    }
1346
1347    /// Globally remove a tag from every skill that carries it. Returns the ids
1348    /// of the affected skills so the caller can refresh their metadata.
1349    pub fn delete_tag(&self, name: &str) -> Result<Vec<String>> {
1350        let conn = self.conn.lock().unwrap();
1351        let affected: Vec<String> = {
1352            let mut stmt =
1353                conn.prepare("SELECT DISTINCT skill_id FROM skill_tags WHERE tag = ?1")?;
1354            let rows = stmt.query_map(params![name], |row| row.get::<_, String>(0))?;
1355            rows.filter_map(|r| r.ok()).collect()
1356        };
1357        conn.execute("DELETE FROM skill_tags WHERE tag = ?1", params![name])?;
1358        Ok(affected)
1359    }
1360
1361    // ── Audit log ──
1362
1363    /// Append an audit entry. Best-effort: errors are swallowed so callers
1364    /// never have to wrap or propagate them. Auto-prunes when the table
1365    /// grows beyond AUDIT_MAX_ENTRIES.
1366    pub fn log_audit(&self, draft: AuditDraft) {
1367        let ts = std::time::SystemTime::now()
1368            .duration_since(std::time::UNIX_EPOCH)
1369            .map(|d| d.as_secs() as i64)
1370            .unwrap_or(0);
1371
1372        let conn = match self.conn.lock() {
1373            Ok(c) => c,
1374            Err(_) => return,
1375        };
1376        let insert = conn.execute(
1377            "INSERT INTO audit_log (ts, action, skill_id, skill_name, tool, success, detail)
1378             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
1379            params![
1380                ts,
1381                draft.action,
1382                draft.skill_id,
1383                draft.skill_name,
1384                draft.tool,
1385                draft.success as i32,
1386                draft.detail,
1387            ],
1388        );
1389        if insert.is_err() {
1390            return;
1391        }
1392        // Prune to MAX_ENTRIES newest. Cheap when under the cap (DELETE matches 0 rows).
1393        let _ = conn.execute(
1394            "DELETE FROM audit_log WHERE id IN (
1395                 SELECT id FROM audit_log ORDER BY id DESC LIMIT -1 OFFSET ?1
1396             )",
1397            params![AUDIT_MAX_ENTRIES],
1398        );
1399    }
1400
1401    /// Read the most recent audit entries (newest first). When `limit` is
1402    /// `None`, returns everything.
1403    pub fn list_audit(&self, limit: Option<i64>) -> Result<Vec<AuditEntry>> {
1404        let conn = self.conn.lock().unwrap();
1405        let sql = if limit.is_some() {
1406            "SELECT id, ts, action, skill_id, skill_name, tool, success, detail
1407             FROM audit_log ORDER BY id DESC LIMIT ?1"
1408        } else {
1409            "SELECT id, ts, action, skill_id, skill_name, tool, success, detail
1410             FROM audit_log ORDER BY id DESC"
1411        };
1412        let mut stmt = conn.prepare(sql)?;
1413        let map_row = |row: &rusqlite::Row<'_>| -> rusqlite::Result<AuditEntry> {
1414            Ok(AuditEntry {
1415                id: row.get(0)?,
1416                ts: row.get(1)?,
1417                action: row.get(2)?,
1418                skill_id: row.get(3)?,
1419                skill_name: row.get(4)?,
1420                tool: row.get(5)?,
1421                success: row.get::<_, i32>(6)? != 0,
1422                detail: row.get(7)?,
1423            })
1424        };
1425        let rows = if let Some(n) = limit {
1426            stmt.query_map(params![n], map_row)?
1427                .collect::<rusqlite::Result<Vec<_>>>()?
1428        } else {
1429            stmt.query_map([], map_row)?
1430                .collect::<rusqlite::Result<Vec<_>>>()?
1431        };
1432        Ok(rows)
1433    }
1434}
1435
1436#[cfg(test)]
1437mod audit_log_tests;
1438
1439#[cfg(test)]
1440mod scenario_membership_tests;
1441
1442fn map_skill_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<SkillRecord> {
1443    Ok(SkillRecord {
1444        id: row.get(0)?,
1445        name: row.get(1)?,
1446        description: row.get(2)?,
1447        source_type: row.get(3)?,
1448        source_ref: row.get(4)?,
1449        source_ref_resolved: row.get(5)?,
1450        source_subpath: row.get(6)?,
1451        source_branch: row.get(7)?,
1452        source_revision: row.get(8)?,
1453        source_agent: row.get(9)?,
1454        remote_revision: row.get(10)?,
1455        central_path: row.get(11)?,
1456        content_hash: row.get(12)?,
1457        enabled: row.get::<_, i32>(13)? != 0,
1458        created_at: row.get(14)?,
1459        updated_at: row.get(15)?,
1460        status: row.get(16)?,
1461        update_status: row.get(17)?,
1462        last_checked_at: row.get(18)?,
1463        last_check_error: row.get(19)?,
1464    })
1465}
1466
1467#[cfg(test)]
1468mod tag_tests;