Skip to main content

agentmux_srv_core/backend/storage/
skill_app.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What makes a catalog skill a computer-use skill (docs/specs/SPEC_PACKS_2026_11_05.md §3, §7): its
5//! manifest (`computer-use.json`), the files that sit beside its `SKILL.md`, and the records of tests
6//! that passed. They live in `db_skill_app`, `db_skill_file` and `db_skill_verified`, in the identity
7//! store beside `db_skills`, and are created on first use without a schema bump (like
8//! `db_skill_source`). A skill written by hand has no `db_skill_app` row.
9//!
10//! The skill's `SKILL.md` body stays in `db_skills.content`, so every existing path that lists,
11//! binds, reaches or exports a skill keeps working. The pass records are not part of what a signature
12//! covers, so a new pass never breaks one (spec §7).
13
14use std::collections::BTreeMap;
15
16use rusqlite::{params, OptionalExtension};
17
18use super::error::StoreError;
19use super::store::Store;
20use crate::backend::memory::record::sha256_hex;
21
22const SCHEMA: &str = "CREATE TABLE IF NOT EXISTS db_skill_app (
23        skill_id     TEXT PRIMARY KEY,
24        publisher    TEXT NOT NULL,
25        app_id       TEXT NOT NULL,
26        version      TEXT NOT NULL,
27        manifest     TEXT NOT NULL,
28        content_hash TEXT NOT NULL DEFAULT '',
29        installed_at INTEGER NOT NULL DEFAULT 0
30    );
31    CREATE TABLE IF NOT EXISTS db_skill_file (
32        skill_id TEXT NOT NULL,
33        path     TEXT NOT NULL,
34        content  TEXT NOT NULL,
35        image    BLOB,
36        sha256   TEXT NOT NULL,
37        script   INTEGER NOT NULL DEFAULT 0,
38        approved INTEGER NOT NULL DEFAULT 0,
39        PRIMARY KEY (skill_id, path)
40    );
41    CREATE TABLE IF NOT EXISTS db_skill_signature (
42        skill_id   TEXT PRIMARY KEY,
43        signer_key TEXT NOT NULL
44    );
45    CREATE TABLE IF NOT EXISTS db_skill_origin (
46        skill_id  TEXT PRIMARY KEY,
47        skill_md  TEXT NOT NULL,
48        signature TEXT
49    );
50    CREATE TABLE IF NOT EXISTS db_skill_catalog_source (
51        skill_id      TEXT PRIMARY KEY,
52        content_hash  TEXT NOT NULL,
53        publisher_key TEXT NOT NULL
54    );
55    CREATE TABLE IF NOT EXISTS db_skill_publisher_pin (
56        publisher  TEXT PRIMARY KEY,
57        public_key TEXT NOT NULL,
58        pinned_at  INTEGER NOT NULL DEFAULT 0
59    );
60    CREATE TABLE IF NOT EXISTS db_skill_verified (
61        skill_id       TEXT NOT NULL,
62        skill_version  TEXT NOT NULL,
63        app_version    TEXT NOT NULL,
64        platform       TEXT NOT NULL,
65        date           TEXT NOT NULL,
66        runner         TEXT NOT NULL,
67        route          TEXT NOT NULL DEFAULT '',
68        result         TEXT NOT NULL,
69        notes          TEXT NOT NULL DEFAULT '',
70        evidence_sha256 TEXT NOT NULL DEFAULT '',
71        added_by       TEXT NOT NULL DEFAULT '',
72        added_at       INTEGER NOT NULL DEFAULT 0,
73        PRIMARY KEY (skill_id, skill_version, app_version, platform, date, runner, result, evidence_sha256)
74    );";
75
76/// One rung of a skill's ladder, best first.
77#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
78#[ts(export, export_to = "../../../frontend/types/rpc/")]
79pub struct LadderStep {
80    /// `api`, `mcp`, `shortcuts` or `desktop`.
81    pub kind: String,
82    pub note: String,
83}
84
85/// A test that ran against an app, as the skill's `verification` record states it.
86#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
87#[serde(rename_all = "camelCase")]
88#[ts(export, export_to = "../../../frontend/types/rpc/")]
89pub struct VerifiedRecord {
90    pub skill_version: String,
91    pub app_version: String,
92    /// `windows`, `macos` or `linux`.
93    pub platform: String,
94    /// `YYYY-MM-DD`.
95    pub date: String,
96    /// `AgentMux test machine` or `community:<handle>`; never a host or user name.
97    pub runner: String,
98    /// Which rung of the ladder the test used; empty when it did not say.
99    #[serde(default)]
100    pub route: String,
101    /// `pass` or `fail`.
102    pub result: String,
103    #[serde(default)]
104    pub notes: String,
105    /// SHA-256 of the output file or screenshot; the evidence itself is never kept.
106    #[serde(default)]
107    pub evidence_sha256: String,
108}
109
110/// A file beside `SKILL.md`, as the card lists it (its text is read with `Skills get`).
111#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
112#[ts(export, export_to = "../../../frontend/types/rpc/")]
113pub struct SkillFileInfo {
114    pub path: String,
115    /// SHA-256 of the file as stored: what an approval is for.
116    pub sha256: String,
117    #[ts(type = "number")]
118    pub bytes: u64,
119    /// A script the agent's shell would run: not written to an agent's folder until a person approves it.
120    pub script: bool,
121    pub approved: bool,
122    /// A reference crop (a PNG under `references/`), read as an image.
123    pub image: bool,
124}
125
126/// One reference crop of the app's UI (SPEC_PACKS §3.1), as the manifest tags it.
127#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
128#[serde(rename_all = "camelCase")]
129#[ts(export, export_to = "../../../frontend/types/rpc/")]
130pub struct ReferenceInfo {
131    pub path: String,
132    /// What the crop is of: "master fader".
133    pub label: String,
134    /// One line on what to look for.
135    #[serde(default)]
136    pub shows: String,
137    pub app_version: String,
138    pub platform: String,
139    /// `light`, `dark`, or the app's own skin name.
140    pub theme: String,
141    /// Display scaling in percent.
142    pub scale: u32,
143    /// `AgentMux test machine`; never a host or user name.
144    pub captured_by: String,
145    pub date: String,
146    pub sha256: String,
147}
148
149/// The manifest's own fields, in the form Memory and `Desktop` read them.
150#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
151#[ts(export, export_to = "../../../frontend/types/rpc/")]
152pub struct SkillAppInfo {
153    pub publisher: String,
154    pub id: String,
155    pub name: String,
156    pub version: String,
157    pub vendor: String,
158    /// Executable names per platform (`windows`, `macos`, `linux`).
159    pub executables: BTreeMap<String, Vec<String>>,
160    pub title_hints: Vec<String>,
161    pub platforms: Vec<String>,
162    pub ladder: Vec<LadderStep>,
163    /// The id of the MCP catalog entry the skill points at, never a command.
164    pub mcp: Option<String>,
165    /// A semver range of app versions the skill claims; `None` while unknown.
166    pub supported: Option<String>,
167    /// App versions a test passed on, as the manifest says.
168    pub tested: Vec<String>,
169    /// Reference crops, each tagged with the app version it was taken at.
170    pub references: Vec<ReferenceInfo>,
171}
172
173/// What a person asks of a script: revoke it, or approve the text with this hash.
174#[derive(Debug, Clone, Copy)]
175pub enum ScriptApproval<'a> {
176    Revoke,
177    Approve { reviewed_sha256: &'a str },
178}
179
180/// What `skill_script_set_approved` did.
181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
182pub enum ScriptOutcome {
183    Done,
184    NotAScript,
185    /// The script is not the text that was reviewed: it was replaced since.
186    Changed,
187    /// The publisher is pinned to another key than this skill's signer.
188    OtherAuthor,
189}
190
191/// What a script's manifest entry says about it, for the prompt that asks for its approval.
192#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
193#[ts(export, export_to = "../../../frontend/types/rpc/")]
194pub struct ScriptInfo {
195    pub path: String,
196    /// What it is for, in the publisher's words.
197    pub purpose: String,
198    /// What it needs to run ("python 3", "network").
199    pub needs: Vec<String>,
200}
201
202/// A computer-use skill as the catalog holds it: the manifest, the files beside `SKILL.md`, and the pass records.
203#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
204#[ts(export, export_to = "../../../frontend/types/rpc/")]
205pub struct SkillApp {
206    #[serde(flatten)]
207    pub info: SkillAppInfo,
208    /// The manifest's scripts, with what each is for and needs.
209    pub scripts: Vec<ScriptInfo>,
210    /// Who signed it, and whether that is the key its publisher is pinned to.
211    pub signature: crate::backend::widget::signature::WidgetSignatureInfo,
212    pub files: Vec<SkillFileInfo>,
213    pub verified: Vec<VerifiedRecord>,
214    /// The SHA-256 the publisher's signature covers (empty for a skill that came without one).
215    pub content_hash: String,
216    /// Installed from the public catalog, and still exactly what the catalog listed then: the same files (content
217    /// hash) signed by the same publisher key. An edited skill, or one replaced from another source, is not.
218    pub from_catalog: bool,
219}
220
221/// A file ready to store: its text and whether it is a script.
222#[derive(Debug, Clone, PartialEq, Eq)]
223pub struct SkillFileInput {
224    pub path: String,
225    /// The text; empty for an image.
226    pub content: String,
227    /// The PNG bytes of a reference crop; `None` for a text file.
228    pub image: Option<Vec<u8>>,
229    pub script: bool,
230}
231
232/// A file of a skill with its text, for the launch step and `Skills get`.
233#[derive(Debug, Clone, PartialEq, Eq)]
234pub struct SkillFile {
235    pub path: String,
236    pub content: String,
237    pub image: Option<Vec<u8>>,
238    pub script: bool,
239    pub approved: bool,
240}
241
242fn pins_of(conn: &rusqlite::Connection) -> Result<crate::backend::widget::signature::Pins, StoreError> {
243    let mut stmt = conn.prepare("SELECT publisher, public_key FROM db_skill_publisher_pin")?;
244    let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
245    Ok(rows.collect::<Result<_, _>>()?)
246}
247
248impl Store {
249    /// Make `skill_id` a computer-use skill, replacing any earlier manifest and files in one step.
250    /// A script that was approved with the same text stays approved; a changed or new one needs a new
251    /// approval. Call on the catalog store.
252    pub fn skill_app_set(
253        &self,
254        skill_id: &str,
255        info: &SkillAppInfo,
256        manifest_json: &str,
257        content_hash: &str,
258        files: &[SkillFileInput],
259        now_ms: i64,
260    ) -> Result<(), StoreError> {
261        let mut conn = self.conn.lock().unwrap();
262        conn.execute_batch(SCHEMA)?;
263        let tx = conn.transaction()?;
264        // (path, sha256) of scripts already approved: kept only when the text is the same.
265        let approved: std::collections::HashSet<(String, String)> = {
266            let mut stmt = tx.prepare("SELECT path, sha256 FROM db_skill_file WHERE skill_id = ?1 AND script = 1 AND approved = 1")?;
267            let rows = stmt.query_map(params![skill_id], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
268            rows.collect::<Result<_, _>>()?
269        };
270        tx.execute(
271            "INSERT INTO db_skill_app (skill_id, publisher, app_id, version, manifest, content_hash, installed_at)
272             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
273             ON CONFLICT(skill_id) DO UPDATE SET publisher = excluded.publisher, app_id = excluded.app_id,
274                version = excluded.version, manifest = excluded.manifest, content_hash = excluded.content_hash,
275                installed_at = excluded.installed_at",
276            params![skill_id, info.publisher, info.id, info.version, manifest_json, content_hash, now_ms],
277        )?;
278        tx.execute("DELETE FROM db_skill_file WHERE skill_id = ?1", params![skill_id])?;
279        for f in files {
280            let sha = sha256_hex(f.image.as_deref().unwrap_or(f.content.as_bytes()));
281            let keep = f.script && approved.contains(&(f.path.clone(), sha.clone()));
282            tx.execute(
283                "INSERT INTO db_skill_file (skill_id, path, content, image, sha256, script, approved) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
284                params![skill_id, f.path, f.content, f.image, sha, f.script as i64, keep as i64],
285            )?;
286        }
287        tx.commit()?;
288        Ok(())
289    }
290
291    /// The computer-use fields of one skill, if it is one.
292    pub fn skill_app_get(&self, skill_id: &str) -> Result<Option<SkillApp>, StoreError> {
293        let mut map = self.skill_app_query(Some(skill_id))?;
294        self.confirm_catalog_text(&mut map);
295        Ok(map.remove(skill_id))
296    }
297
298    /// Every computer-use skill, by skill id.
299    pub fn skill_app_map(&self) -> Result<BTreeMap<String, SkillApp>, StoreError> {
300        let mut map = self.skill_app_query(None)?;
301        self.confirm_catalog_text(&mut map);
302        Ok(map)
303    }
304
305    /// A skill is still what the catalog listed only while its text is too: the content hash does not follow an edit made
306    /// in Memory, so the `SKILL.md` kept from the install is compared with the skill as it is now.
307    fn confirm_catalog_text(&self, map: &mut BTreeMap<String, SkillApp>) {
308        for (id, app) in map.iter_mut().filter(|(_, a)| a.from_catalog) {
309            let folder = format!("{}-{}", app.info.publisher, app.info.id);
310            let same = match (self.skill_get(id), self.skill_origin_get(id)) {
311                (Ok(Some(skill)), Ok(Some((md, _)))) => crate::backend::skill_file::original_still_applies(&folder, &md, &skill),
312                _ => false,
313            };
314            app.from_catalog = same;
315        }
316    }
317
318    fn skill_app_query(&self, only: Option<&str>) -> Result<BTreeMap<String, SkillApp>, StoreError> {
319        let conn = self.conn.lock().unwrap();
320        conn.execute_batch(SCHEMA)?;
321        let mut out = BTreeMap::new();
322        let mut signers: BTreeMap<String, String> = BTreeMap::new();
323        let pins = pins_of(&conn)?;
324        {
325            let mut stmt = conn.prepare("SELECT skill_id, manifest, content_hash FROM db_skill_app WHERE (?1 IS NULL OR skill_id = ?1)")?;
326            let rows = stmt.query_map(params![only], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?)))?;
327            for row in rows {
328                let (id, manifest, content_hash) = row?;
329                // A manifest this build can't read is left out rather than failing the whole list.
330                if let Ok(info) = crate::backend::computer_use_skill::info_from_manifest(&manifest) {
331                    let scripts = crate::backend::computer_use_skill::script_infos(&manifest);
332                    let signature = crate::backend::widget::signature::describe(&format!("{}.{}", info.publisher, info.id), None, &pins);
333                    out.insert(id, SkillApp { info, scripts, signature, files: Vec::new(), verified: Vec::new(), content_hash, from_catalog: false });
334                }
335            }
336        }
337        {
338            let mut stmt = conn.prepare("SELECT skill_id, signer_key FROM db_skill_signature WHERE (?1 IS NULL OR skill_id = ?1)")?;
339            let rows = stmt.query_map(params![only], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
340            for row in rows {
341                let (id, key) = row?;
342                if let Some(app) = out.get_mut(&id) {
343                    app.signature = crate::backend::widget::signature::describe(&format!("{}.{}", app.info.publisher, app.info.id), Some(&key), &pins);
344                    signers.insert(id, key);
345                }
346            }
347        }
348        {
349            let mut stmt = conn.prepare("SELECT skill_id, content_hash, publisher_key FROM db_skill_catalog_source WHERE (?1 IS NULL OR skill_id = ?1)")?;
350            let rows = stmt.query_map(params![only], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?)))?;
351            for row in rows {
352                let (id, hash, key) = row?;
353                if let Some(app) = out.get_mut(&id) {
354                    app.from_catalog = !hash.is_empty() && app.content_hash == hash && signers.get(&id) == Some(&key);
355                }
356            }
357        }
358        {
359            let mut stmt = conn.prepare(
360                "SELECT skill_id, path, length(CAST(content AS BLOB)) + COALESCE(length(image), 0), script, approved, image IS NOT NULL, sha256 FROM db_skill_file
361                 WHERE (?1 IS NULL OR skill_id = ?1) ORDER BY skill_id, path",
362            )?;
363            let rows = stmt.query_map(params![only], |r| {
364                Ok((
365                    r.get::<_, String>(0)?,
366                    SkillFileInfo {
367                        path: r.get(1)?,
368                        bytes: r.get::<_, i64>(2)? as u64,
369                        script: r.get::<_, i64>(3)? != 0,
370                        approved: r.get::<_, i64>(4)? != 0,
371                        image: r.get::<_, i64>(5)? != 0,
372                        sha256: r.get(6)?,
373                    },
374                ))
375            })?;
376            for row in rows {
377                let (id, file) = row?;
378                if let Some(app) = out.get_mut(&id) {
379                    app.files.push(file);
380                }
381            }
382        }
383        {
384            let mut stmt = conn.prepare(
385                "SELECT skill_id, skill_version, app_version, platform, date, runner, route, result, notes, evidence_sha256
386                 FROM db_skill_verified WHERE (?1 IS NULL OR skill_id = ?1) ORDER BY skill_id, date, rowid",
387            )?;
388            let rows = stmt.query_map(params![only], |r| {
389                Ok((
390                    r.get::<_, String>(0)?,
391                    VerifiedRecord {
392                        skill_version: r.get(1)?,
393                        app_version: r.get(2)?,
394                        platform: r.get(3)?,
395                        date: r.get(4)?,
396                        runner: r.get(5)?,
397                        route: r.get(6)?,
398                        result: r.get(7)?,
399                        notes: r.get(8)?,
400                        evidence_sha256: r.get(9)?,
401                    },
402                ))
403            })?;
404            for row in rows {
405                let (id, rec) = row?;
406                if let Some(app) = out.get_mut(&id) {
407                    app.verified.push(rec);
408                }
409            }
410        }
411        Ok(out)
412    }
413
414    /// The files beside `SKILL.md`, with their text.
415    pub fn skill_files(&self, skill_id: &str) -> Result<Vec<SkillFile>, StoreError> {
416        let conn = self.conn.lock().unwrap();
417        conn.execute_batch(SCHEMA)?;
418        let mut stmt = conn.prepare("SELECT path, content, image, script, approved FROM db_skill_file WHERE skill_id = ?1 ORDER BY path")?;
419        let rows = stmt.query_map(params![skill_id], |r| {
420            Ok(SkillFile { path: r.get(0)?, content: r.get(1)?, image: r.get(2)?, script: r.get::<_, i64>(3)? != 0, approved: r.get::<_, i64>(4)? != 0 })
421        })?;
422        Ok(rows.collect::<Result<Vec<_>, _>>()?)
423    }
424
425    /// One file beside `SKILL.md`.
426    pub fn skill_file_get(&self, skill_id: &str, path: &str) -> Result<Option<SkillFile>, StoreError> {
427        let conn = self.conn.lock().unwrap();
428        conn.execute_batch(SCHEMA)?;
429        Ok(conn
430            .query_row(
431                "SELECT path, content, image, script, approved FROM db_skill_file WHERE skill_id = ?1 AND path = ?2",
432                params![skill_id, path],
433                |r| Ok(SkillFile { path: r.get(0)?, content: r.get(1)?, image: r.get(2)?, script: r.get::<_, i64>(3)? != 0, approved: r.get::<_, i64>(4)? != 0 }),
434            )
435            .optional()?)
436    }
437
438    /// Add a test record. The same record twice is kept once. Records are only ever added.
439    /// Returns whether a new one was stored. `added_by` is the agent or window that filed it.
440    pub fn skill_verified_append(&self, skill_id: &str, rec: &VerifiedRecord, added_by: &str, now_ms: i64) -> Result<bool, StoreError> {
441        let conn = self.conn.lock().unwrap();
442        conn.execute_batch(SCHEMA)?;
443        let n = conn.execute(
444            "INSERT OR IGNORE INTO db_skill_verified
445                (skill_id, skill_version, app_version, platform, date, runner, route, result, notes, evidence_sha256, added_by, added_at)
446             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
447            params![
448                skill_id,
449                rec.skill_version,
450                rec.app_version,
451                rec.platform,
452                rec.date,
453                rec.runner,
454                rec.route,
455                rec.result,
456                rec.notes,
457                rec.evidence_sha256,
458                added_by,
459                now_ms
460            ],
461        )?;
462        Ok(n > 0)
463    }
464
465    /// Everything the catalog keeps beside a deleted skill's row: reach, source, computer-use files and records, opt-outs.
466    pub fn skill_catalog_forget(&self, skill_id: &str) -> Result<(), StoreError> {
467        self.skill_reach_forget(skill_id)?;
468        self.skill_source_forget(skill_id)?;
469        self.skill_app_forget(skill_id)?;
470        self.skill_optout_forget(skill_id)
471    }
472
473    /// Record which key verified a skill's signature at install; `None` for a skill that came unsigned.
474    pub fn skill_signer_set(&self, skill_id: &str, signer: Option<&str>) -> Result<(), StoreError> {
475        let conn = self.conn.lock().unwrap();
476        conn.execute_batch(SCHEMA)?;
477        match signer {
478            Some(key) => conn.execute(
479                "INSERT INTO db_skill_signature (skill_id, signer_key) VALUES (?1, ?2) ON CONFLICT(skill_id) DO UPDATE SET signer_key = excluded.signer_key",
480                params![skill_id, key],
481            )?,
482            None => conn.execute("DELETE FROM db_skill_signature WHERE skill_id = ?1", params![skill_id])?,
483        };
484        Ok(())
485    }
486
487    /// Record that `skill_id` was installed from the public catalog's entry with this content hash and publisher key.
488    pub fn skill_catalog_source_set(&self, skill_id: &str, content_hash: &str, publisher_key: &str) -> Result<(), StoreError> {
489        let conn = self.conn.lock().unwrap();
490        conn.execute_batch(SCHEMA)?;
491        conn.execute(
492            "INSERT INTO db_skill_catalog_source (skill_id, content_hash, publisher_key) VALUES (?1, ?2, ?3)
493             ON CONFLICT(skill_id) DO UPDATE SET content_hash = excluded.content_hash, publisher_key = excluded.publisher_key",
494            params![skill_id, content_hash, publisher_key],
495        )?;
496        Ok(())
497    }
498
499    /// The manifest as the skill was installed with it.
500    pub fn skill_manifest_get(&self, skill_id: &str) -> Result<Option<String>, StoreError> {
501        let conn = self.conn.lock().unwrap();
502        conn.execute_batch(SCHEMA)?;
503        Ok(conn.query_row("SELECT manifest FROM db_skill_app WHERE skill_id = ?1", params![skill_id], |r| r.get(0)).optional()?)
504    }
505
506    /// Keep the `SKILL.md` and `skill.sig` a skill was installed from, as written. The content hash covers `SKILL.md`, so
507    /// an export can only carry the publisher's signature if it writes those exact bytes back.
508    pub fn skill_origin_set(&self, skill_id: &str, skill_md: &str, signature: Option<&str>) -> Result<(), StoreError> {
509        let conn = self.conn.lock().unwrap();
510        conn.execute_batch(SCHEMA)?;
511        conn.execute(
512            "INSERT INTO db_skill_origin (skill_id, skill_md, signature) VALUES (?1, ?2, ?3)
513             ON CONFLICT(skill_id) DO UPDATE SET skill_md = excluded.skill_md, signature = excluded.signature",
514            params![skill_id, skill_md, signature],
515        )?;
516        Ok(())
517    }
518
519    /// The `SKILL.md` and `skill.sig` the skill was installed from; `None` for one installed before they were kept.
520    pub fn skill_origin_get(&self, skill_id: &str) -> Result<Option<(String, Option<String>)>, StoreError> {
521        let conn = self.conn.lock().unwrap();
522        conn.execute_batch(SCHEMA)?;
523        Ok(conn
524            .query_row("SELECT skill_md, signature FROM db_skill_origin WHERE skill_id = ?1", params![skill_id], |r| Ok((r.get(0)?, r.get(1)?)))
525            .optional()?)
526    }
527
528    /// Publisher → the key it is pinned to (the first key a person approved a script of its for).
529    pub fn skill_publisher_pins(&self) -> Result<crate::backend::widget::signature::Pins, StoreError> {
530        let conn = self.conn.lock().unwrap();
531        conn.execute_batch(SCHEMA)?;
532        pins_of(&conn)
533    }
534
535    /// Approve or revoke one script. Approving needs the SHA-256 the person reviewed and applies only if the stored
536    /// script still has it, and not at all when the skill's publisher is pinned to another key than the one that
537    /// signed this skill (or it is unsigned): that is a different author, not an update. A first approval of a
538    /// signed skill pins its publisher to the signer's key.
539    pub fn skill_script_set_approved(&self, skill_id: &str, path: &str, approval: ScriptApproval<'_>, now_ms: i64) -> Result<ScriptOutcome, StoreError> {
540        let conn = self.conn.lock().unwrap();
541        conn.execute_batch(SCHEMA)?;
542        let stored: Option<String> = conn
543            .query_row("SELECT sha256 FROM db_skill_file WHERE skill_id = ?1 AND path = ?2 AND script = 1", params![skill_id, path], |r| r.get(0))
544            .optional()?;
545        let Some(stored) = stored else { return Ok(ScriptOutcome::NotAScript) };
546        let ScriptApproval::Approve { reviewed_sha256 } = approval else {
547            conn.execute("UPDATE db_skill_file SET approved = 0 WHERE skill_id = ?1 AND path = ?2", params![skill_id, path])?;
548            return Ok(ScriptOutcome::Done);
549        };
550        if stored != reviewed_sha256 {
551            return Ok(ScriptOutcome::Changed);
552        }
553        let (publisher, signer): (Option<String>, Option<String>) = conn
554            .query_row(
555                "SELECT a.publisher, (SELECT signer_key FROM db_skill_signature WHERE skill_id = a.skill_id)
556                 FROM db_skill_app a WHERE a.skill_id = ?1",
557                params![skill_id],
558                |r| Ok((r.get(0)?, r.get(1)?)),
559            )
560            .optional()?
561            .unwrap_or((None, None));
562        if let Some(publisher) = &publisher {
563            let pinned: Option<String> = conn.query_row("SELECT public_key FROM db_skill_publisher_pin WHERE publisher = ?1", params![publisher], |r| r.get(0)).optional()?;
564            if pinned.is_some() && pinned != signer {
565                return Ok(ScriptOutcome::OtherAuthor);
566            }
567        }
568        conn.execute("UPDATE db_skill_file SET approved = 1 WHERE skill_id = ?1 AND path = ?2", params![skill_id, path])?;
569        conn.execute(
570            "INSERT OR IGNORE INTO db_skill_publisher_pin (publisher, public_key, pinned_at)
571             SELECT a.publisher, s.signer_key, ?2 FROM db_skill_app a JOIN db_skill_signature s ON s.skill_id = a.skill_id WHERE a.skill_id = ?1",
572            params![skill_id, now_ms],
573        )?;
574        Ok(ScriptOutcome::Done)
575    }
576
577    /// Drop a deleted skill's manifest, files and records. Call on the catalog store.
578    pub fn skill_app_forget(&self, skill_id: &str) -> Result<(), StoreError> {
579        let conn = self.conn.lock().unwrap();
580        conn.execute_batch(SCHEMA)?;
581        conn.execute("DELETE FROM db_skill_signature WHERE skill_id = ?1", params![skill_id])?;
582        conn.execute("DELETE FROM db_skill_origin WHERE skill_id = ?1", params![skill_id])?;
583        conn.execute("DELETE FROM db_skill_catalog_source WHERE skill_id = ?1", params![skill_id])?;
584        conn.execute("DELETE FROM db_skill_app WHERE skill_id = ?1", params![skill_id])?;
585        conn.execute("DELETE FROM db_skill_file WHERE skill_id = ?1", params![skill_id])?;
586        conn.execute("DELETE FROM db_skill_verified WHERE skill_id = ?1", params![skill_id])?;
587        Ok(())
588    }
589}
590
591#[cfg(test)]
592#[path = "skill_app_tests.rs"]
593mod tests;