ultron-kernel-apis 1.0.0

Host operations behind the thin Python kernel APIs: code skills and the skill catalog, memory, hints, images
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
//! `skills.*` requests (port of `ultron/skills.ts`): the version-pinned, explainable skill catalog and the code-skill
//! requests, journaled in the module document. Selection never grants capabilities: frontmatter keys that would
//! grant tools, models, budgets or permissions are reported and ignored.

use crate::TaskHost;
use crate::code_skills::{CodeSkillKind, CodeSkills};
use crate::store::read_versioned;
use crate::util::{Clock, object};
use kernel::Signal;
use kernel::store::DocumentStore;
use serde_json::{Map, Value, json};
use std::collections::HashSet;
use std::sync::{Arc, Mutex};
use yaml_rust2::Yaml;

/// A skill as Pi's loader discovered it; this module never discovers skills itself.
#[derive(Debug, Clone)]
pub struct SkillSource {
    pub name: String,
    pub description: String,
    pub file_path: String,
    pub content: String,
    pub disable_model_invocation: bool,
}

pub type SkillLoader = Arc<dyn Fn() -> Result<Vec<SkillSource>, String> + Send + Sync>;

const CAPABILITY_KEYS: &[&str] = &[
    "allowed-tools",
    "allowed_tools",
    "allowedTools",
    "tools",
    "grants",
    "permissions",
    "capabilities",
    "model",
    "budget",
    "timeout",
];
const STOPWORDS: &[&str] = &[
    "a", "an", "and", "are", "for", "how", "i", "in", "is", "it", "me", "my", "of", "on", "or", "the", "this", "to",
    "with",
];
const EXACT_NAME_BONUS: i64 = 5;
const MAX_RECORDS: usize = 2000;
const MAX_QUERY_CHARS: usize = 4000;

struct Skill {
    name: String,
    description: String,
    file_path: String,
    version: String,
    invocable: bool,
    content: String,
    body: String,
    ignored: Map<String, Value>,
}

fn parse_skill(source: &SkillSource) -> Skill {
    let (frontmatter, body) = match resources::frontmatter::parse(&source.content) {
        Ok(parsed) => (parsed.frontmatter, parsed.body),
        // Pi's loader already rejected unparseable skills; tolerate them here as plain bodies.
        Err(_) => (Yaml::Null, source.content.clone()),
    };
    let mut ignored = Map::new();
    if let Yaml::Hash(map) = &frontmatter {
        for key in CAPABILITY_KEYS {
            if let Some(value) = map.get(&Yaml::String((*key).to_string())) {
                ignored.insert((*key).to_string(), resources::frontmatter::to_json(value));
            }
        }
    }
    Skill {
        name: source.name.clone(),
        description: source.description.clone(),
        file_path: source.file_path.clone(),
        version: jsrt::hash::sha256_hex(source.content.as_bytes()),
        invocable: !source.disable_model_invocation,
        content: source.content.clone(),
        body,
        ignored,
    }
}

fn tokens(text: &str) -> Vec<String> {
    let lower = text.to_lowercase();
    lower
        .split(|c: char| !(c.is_ascii_lowercase() || c.is_ascii_digit()))
        .filter(|token| !token.is_empty())
        .map(str::to_string)
        .collect()
}

fn query_terms(query: &str) -> Vec<String> {
    let mut seen = HashSet::new();
    tokens(query)
        .into_iter()
        .filter(|term| term.len() > 1 && !STOPWORDS.contains(&term.as_str()) && seen.insert(term.clone()))
        .collect()
}

fn score(skill: &Skill, terms: &[String], query: &str) -> Option<Value> {
    let set = |text: &str| -> HashSet<String> { tokens(text).into_iter().collect() };
    let (name, description, body) = (set(&skill.name), set(&skill.description), set(&skill.body));
    let mut matches = Vec::new();
    let mut total = 0;
    for term in terms {
        let mut matched = Vec::new();
        for (field, tokens, weight) in [("name", &name, 3), ("description", &description, 2), ("body", &body, 1)] {
            if tokens.contains(term) {
                matched.push(field);
                total += weight;
            }
        }
        if !matched.is_empty() {
            matches.push(json!({"term": term, "fields": matched}));
        }
    }
    if skill.name.to_lowercase() == query.trim().to_lowercase() {
        total += EXACT_NAME_BONUS;
    }
    (total > 0).then(|| json!({"name": skill.name, "version": skill.version, "score": total, "matches": matches}))
}

fn version_string(value: Option<&Value>) -> Result<String, String> {
    match value.and_then(Value::as_str) {
        Some(text) if text.len() == 64 && text.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) => {
            Ok(text.to_string())
        }
        _ => Err("version must be a lowercase sha256 hex digest".into()),
    }
}

fn empty_document() -> Value {
    json!({"format": 1, "generation": 0, "catalog": [], "changes": [], "decisions": [], "loads": [], "invocations": []})
}

fn read_document(saved: Option<Value>) -> Result<Value, String> {
    let Some(document) = read_versioned("ultron.module/skills", saved, "format")? else {
        return Ok(empty_document());
    };
    let valid = document["format"] == 1
        && document
            .get("generation")
            .and_then(jsrt::number::safe_integer)
            .is_some()
        && ["catalog", "changes", "decisions", "loads", "invocations"]
            .iter()
            .all(|key| document[key].is_array());
    if !valid {
        return Err("Skill module document is invalid".into());
    }
    Ok(document)
}

fn append(document: &mut Value, key: &str, record: Value) {
    if document.get(key).is_none() {
        document[key] = json!([]);
    }
    if let Some(Value::Array(records)) = document.get_mut(key) {
        records.push(record);
        if records.len() > MAX_RECORDS {
            let excess = records.len() - MAX_RECORDS;
            records.drain(..excess);
        }
    }
}

/// `invocationPrompt`: the skill block of Pi's `/skill` expansion, its version and the input as JSON.
fn invocation_prompt(skill: &Skill, input: &Value) -> String {
    let dir = match skill.file_path.rfind('/') {
        Some(0) => "/",
        Some(at) => &skill.file_path[..at],
        None => ".",
    };
    format!(
        "<skill name=\"{}\" location=\"{}\">\nReferences are relative to {dir}.\n\n{}\n</skill>\n\nSkill version: {}\n\nInput (JSON):\n{}",
        skill.name,
        skill.file_path,
        skill.body,
        skill.version,
        jsrt::json::stringify(input)
    )
}

struct Snapshot {
    generation: i64,
    skills: Vec<Skill>,
}

impl Snapshot {
    fn get(&self, name: &str) -> Option<&Skill> {
        self.skills.iter().find(|skill| skill.name == name)
    }
}

/// One catalog skill as pinned for a caller outside this module (skill procedures, `delegation::skill_runs`).
#[derive(Debug, Clone)]
pub struct PinnedSkill {
    pub name: String,
    /// sha256 of the file content.
    pub version: String,
    pub file_path: String,
    pub content: String,
}

/// Serves `skills.*`. Durable mutations and snapshot installation run one at a time.
pub struct SkillsModule {
    store: Arc<dyn DocumentStore>,
    load_skills: SkillLoader,
    now: Clock,
    code: Option<CodeSkills>,
    snapshot: Mutex<Option<Arc<Snapshot>>>,
    exclusive: Mutex<()>,
}

impl SkillsModule {
    pub fn new(store: Arc<dyn DocumentStore>, load_skills: SkillLoader, now: Clock, code: Option<CodeSkills>) -> Self {
        Self {
            store,
            load_skills,
            now,
            code,
            snapshot: Mutex::new(None),
            exclusive: Mutex::new(()),
        }
    }

    pub fn code(&self) -> Option<&CodeSkills> {
        self.code.as_ref()
    }

    fn mutate<T>(&self, change: impl FnOnce(&mut Value) -> T) -> Result<T, String> {
        let mut document = read_document(self.store.read()?)?;
        let result = change(&mut document);
        self.store.write(&document)?;
        Ok(result)
    }

    /// Caller holds `exclusive`.
    fn refresh_locked(&self) -> Result<Value, String> {
        let sources = (self.load_skills)()?;
        let mut seen = HashSet::new();
        for source in &sources {
            if source.name.is_empty() {
                return Err("loadSkills returned an invalid skill".into());
            }
            if !seen.insert(source.name.clone()) {
                return Err(format!("Duplicate skill name: {}", source.name));
            }
        }
        let skills: Vec<Skill> = sources.iter().map(parse_skill).collect();
        let at = (self.now)();
        let outcome = self.mutate(|document| {
            let previous: Vec<(String, String)> = document["catalog"]
                .as_array()
                .map(|entries| {
                    entries
                        .iter()
                        .map(|entry| {
                            let text = |key: &str| entry[key].as_str().unwrap_or_default().to_string();
                            (text("name"), text("version"))
                        })
                        .collect()
                })
                .unwrap_or_default();
            let generation = document["generation"].as_i64().unwrap_or(0) + 1;
            let lookup = |list: &[(String, String)], name: &str| {
                list.iter()
                    .find(|(key, _)| key == name)
                    .map(|(_, version)| version.clone())
            };
            let next: Vec<(String, String)> = skills.iter().map(|s| (s.name.clone(), s.version.clone())).collect();
            let mut names: Vec<String> = previous
                .iter()
                .chain(next.iter())
                .map(|(name, _)| name.clone())
                .collect();
            names.sort();
            names.dedup();
            let mut changes = Vec::new();
            for name in names {
                let (from, to) = (lookup(&previous, &name), lookup(&next, &name));
                if from != to {
                    changes.push(json!({"at": at, "generation": generation, "name": name, "from": from, "to": to}));
                }
            }
            document["generation"] = generation.into();
            document["catalog"] = skills
                .iter()
                .map(|skill| {
                    json!({"name": skill.name, "description": skill.description, "file_path": skill.file_path,
                        "version": skill.version, "invocable": skill.invocable})
                })
                .collect();
            for change in &changes {
                append(document, "changes", change.clone());
            }
            json!({"generation": generation, "changes": changes})
        })?;
        // Install only after the catalog record is durable.
        *jsrt::sync::lock(&self.snapshot) = Some(Arc::new(Snapshot {
            generation: outcome["generation"].as_i64().unwrap_or(0),
            skills,
        }));
        Ok(outcome)
    }

    /// One consistent catalog for the whole request, loaded on first use.
    fn current(&self) -> Result<Arc<Snapshot>, String> {
        if let Some(snapshot) = jsrt::sync::lock(&self.snapshot).clone() {
            return Ok(snapshot);
        }
        let _exclusive = jsrt::sync::lock(&self.exclusive);
        if jsrt::sync::lock(&self.snapshot).is_none() {
            self.refresh_locked()?;
        }
        Ok(jsrt::sync::lock(&self.snapshot).clone().expect("installed by refresh"))
    }

    fn pinned<'a>(snapshot: &'a Snapshot, name: &str, version: Option<&str>) -> Result<&'a Skill, String> {
        let Some(skill) = snapshot.get(name) else {
            return Err(match version {
                Some(version) => {
                    format!("Stale skill version: {name}@{version} is no longer in the catalog (skill removed)")
                }
                None => format!("Unknown skill: {name}"),
            });
        };
        if let Some(version) = version
            && skill.version != version
        {
            return Err(format!(
                "Stale skill version: {name}@{version} was requested but the catalog has {name}@{}; select or load again",
                skill.version
            ));
        }
        Ok(skill)
    }

    /// Module start: loads the catalog.
    pub fn start(&self) -> Result<(), String> {
        self.current().map(drop)
    }

    /// A request without a task runtime (`skills.invoke` is refused: nothing can spawn the skill's task).
    pub fn handle(
        &self,
        kind: &str,
        payload: &Map<String, Value>,
        caller: Option<&str>,
        signal: &Signal,
    ) -> Result<Value, String> {
        let host = crate::RootOnly {
            now: crate::util::system_clock(),
        };
        self.handle_with_host(kind, payload, caller, &host, signal)
    }

    /// A request whose `skills.invoke` spawns through `host`.
    pub fn handle_with_host(
        &self,
        kind: &str,
        payload: &Map<String, Value>,
        caller: Option<&str>,
        host: &dyn TaskHost,
        signal: &Signal,
    ) -> Result<Value, String> {
        match kind {
            "skills.refresh" => {
                kernel::ops::fields("skills.refresh", payload)?;
                let _exclusive = jsrt::sync::lock(&self.exclusive);
                self.refresh_locked()
            }
            "skills.list" => {
                kernel::ops::fields("skills.list", payload)?;
                let snapshot = self.current()?;
                let skills: Vec<Value> = snapshot
                    .skills
                    .iter()
                    .map(|s| json!({"name": s.name, "description": s.description, "version": s.version, "invocable": s.invocable}))
                    .collect();
                Ok(json!({"generation": snapshot.generation, "skills": skills}))
            }
            "skills.select" => self.select(payload, caller),
            "skills.load" => self.load(payload, caller),
            "skills.why" => {
                kernel::ops::fields("skills.why", payload)?;
                let id = jsrt::payload::nonempty_string(payload.get("decision_id"), "decision_id")?;
                let document = read_document(self.store.read()?)?;
                document["decisions"]
                    .as_array()
                    .and_then(|decisions| decisions.iter().find(|decision| decision["id"] == id.as_str()))
                    .cloned()
                    .ok_or_else(|| format!("Unknown skill decision: {id}"))
            }
            "skills.invoke" => self.invoke(payload, caller, host),
            "skills.propose_code" | "skills.propose_policy" | "skills.rollback" => {
                self.change_code(kind, payload, caller, signal)
            }
            "skills.code_list" => {
                kernel::ops::fields("skills.code_list", payload)?;
                let filter_kind = match payload.get("kind") {
                    None => None,
                    Some(Value::String(kind)) if kind == "code" || kind == "policy" => Some(kind.as_str()),
                    Some(_) => return Err("kind must be \"code\" or \"policy\"".into()),
                };
                let family = match payload.get("family") {
                    None => None,
                    value => Some(jsrt::payload::nonempty_string(value, "family")?),
                };
                Ok(Value::Array(self.code_skills()?.list(filter_kind, family.as_deref())))
            }
            "skills.code_history" => {
                kernel::ops::fields("skills.code_history", payload)?;
                self.code_skills()?.history(payload.get("name"))
            }
            _ => Err(format!("Unsupported skills request: {kind}")),
        }
    }

    /// `invoke`: the pinned skill as an `rlm-child@1` task of the caller. Only definition, input and key reach the
    /// host: frontmatter never changes the child's model, tools or budget. Each invocation is journaled
    /// (`admitting`, then `spawned` with its task, or `failed` with the error).
    fn invoke(&self, payload: &Map<String, Value>, caller: Option<&str>, host: &dyn TaskHost) -> Result<Value, String> {
        kernel::ops::fields("skills.invoke", payload)?;
        let name = jsrt::payload::nonempty_string(payload.get("name"), "name")?;
        let version = version_string(payload.get("version"))?;
        let Some(input) = payload.get("input") else {
            return Err("input must be JSON".into());
        };
        let snapshot = self.current()?;
        let skill = Self::pinned(&snapshot, &name, Some(&version))?;
        if !skill.invocable {
            return Err(format!("Skill {name} disables model invocation"));
        }
        let invocation = json!({
            "id": jsrt::random::uuid_v4(),
            "at": (self.now)(),
            "name": name,
            "version": skill.version,
            "caller_task_id": caller,
            "state": "admitting",
        });
        let id = invocation["id"].as_str().unwrap_or_default().to_string();
        let record = |change: Value| self.upsert("invocations", &invocation, &change);
        record(json!({}))?;
        let request = json!({
            "definition": "rlm-child@1",
            "input": {"prompt": invocation_prompt(skill, input)},
            "key": format!("skills.invoke:{id}"),
        });
        let task_id = match host.spawn(&request, caller) {
            Ok(task) => task["id"].as_str().unwrap_or_default().to_string(),
            Err(error) => {
                record(json!({"state": "failed", "error": error}))?;
                return Err(error);
            }
        };
        record(json!({"state": "spawned", "task_id": task_id}))?;
        Ok(json!({
            "invocation_id": id,
            "task_id": task_id,
            "name": name,
            "version": skill.version,
            "ignored_capability_requests": skill.ignored,
        }))
    }

    /// Merge `change` into the record of `key` (a journal list of the module document) whose `id` is `base`'s, or
    /// append `base` with `change` merged when there is none.
    pub fn upsert(&self, key: &str, base: &Value, change: &Value) -> Result<(), String> {
        let _exclusive = jsrt::sync::lock(&self.exclusive);
        self.mutate(|document| {
            let id = &base["id"];
            let existing = document
                .get_mut(key)
                .and_then(Value::as_array_mut)
                .and_then(|items| items.iter_mut().find(|item| &item["id"] == id));
            let merge = |target: &mut Value| {
                for (field, value) in change.as_object().into_iter().flatten() {
                    target[field] = value.clone();
                }
            };
            match existing {
                Some(existing) => merge(existing),
                None => {
                    let mut next = base.clone();
                    merge(&mut next);
                    append(document, key, next);
                }
            }
        })
    }

    /// The records of `key` (a journal list of the module document), oldest first.
    pub fn records(&self, key: &str) -> Result<Vec<Value>, String> {
        let document = read_document(self.store.read()?)?;
        Ok(document[key].as_array().cloned().unwrap_or_default())
    }

    /// The catalog's `name` (at `version`, when given: an older version is refused as stale).
    pub fn pinned_skill(&self, name: &str, version: Option<&str>) -> Result<PinnedSkill, String> {
        let snapshot = self.current()?;
        let skill = Self::pinned(&snapshot, name, version)?;
        Ok(PinnedSkill {
            name: skill.name.clone(),
            version: skill.version.clone(),
            file_path: skill.file_path.clone(),
            content: skill.content.clone(),
        })
    }

    fn code_skills(&self) -> Result<&CodeSkills, String> {
        self.code
            .as_ref()
            .ok_or_else(|| "Code skills are not configured in this worker".to_string())
    }

    /// Proposals and rollbacks, recorded in this module's journal whatever their outcome.
    fn change_code(
        &self,
        kind: &str,
        payload: &Map<String, Value>,
        caller: Option<&str>,
        signal: &Signal,
    ) -> Result<Value, String> {
        let code = self.code_skills()?;
        let action = &kind["skills.".len()..];
        let name = payload
            .get("name")
            .and_then(Value::as_str)
            .map(|name| jsrt::utf16::head(name, 64).to_string())
            .unwrap_or_default();
        let base = vec![
            ("id", Value::from(jsrt::random::uuid_v4())),
            ("at", Value::from((self.now)())),
            ("action", Value::from(action)),
            ("name", Value::from(name)),
            ("caller_task_id", caller.into()),
        ];
        let outcome = if kind == "skills.rollback" {
            code.rollback(payload).map(|result| {
                let mut record = base.clone();
                record.extend([
                    ("version", result["rolledBack"].clone()),
                    ("status", "rolled_back".into()),
                    ("active", result["active"].clone()),
                ]);
                (object(record), result)
            })
        } else {
            let kind = if kind == "skills.propose_policy" {
                CodeSkillKind::Policy
            } else {
                CodeSkillKind::Code
            };
            code.propose(kind, payload, signal).map(|result| {
                let mut record = base.clone();
                record.extend([
                    ("version", result["version"].clone()),
                    ("status", result["status"].clone()),
                    ("secretCheck", result["secretCheck"].clone()),
                ]);
                if let Some(test) = result["test"].as_object() {
                    let tests = test.get("tests").and_then(Value::as_array).cloned().unwrap_or_default();
                    let failed: Vec<Value> = tests
                        .iter()
                        .filter(|item| item["ok"] != true)
                        .map(|item| item["name"].clone())
                        .collect();
                    let mut summary = vec![
                        ("passed", test.get("passed").cloned().unwrap_or(Value::Null)),
                        ("tests", tests.len().into()),
                        ("failed", failed.into()),
                    ];
                    if let Some(error) = test.get("error").and_then(Value::as_str).filter(|e| !e.is_empty()) {
                        summary.push(("error", jsrt::utf16::head(error, 500).into()));
                    }
                    record.push(("test", object(summary)));
                }
                (object(record), result)
            })
        };
        let (record, result) = match outcome {
            Ok(done) => (done.0, Ok(done.1)),
            Err(error) => {
                let mut record = base;
                record.extend([
                    ("version", Value::Null),
                    ("status", "failed".into()),
                    ("error", jsrt::utf16::head(&error, 500).into()),
                ]);
                (object(record), Err(error))
            }
        };
        {
            let _exclusive = jsrt::sync::lock(&self.exclusive);
            self.mutate(|document| append(document, "code", record))?;
        }
        result
    }

    fn select(&self, payload: &Map<String, Value>, caller: Option<&str>) -> Result<Value, String> {
        kernel::ops::fields("skills.select", payload)?;
        let query = jsrt::payload::nonempty_string(payload.get("query"), "query")?;
        if jsrt::utf16::len(&query) > MAX_QUERY_CHARS {
            return Err(format!("query must be at most {MAX_QUERY_CHARS} characters"));
        }
        let limit = match payload.get("limit") {
            None => 5,
            Some(value) => jsrt::number::safe_integer(value)
                .filter(|limit| (1..=50).contains(limit) && value.is_number())
                .ok_or("limit must be an integer between 1 and 50")?,
        };
        let snapshot = self.current()?;
        let terms = query_terms(&query);
        let mut considered = Map::new();
        let mut excluded = Vec::new();
        let mut scored = Vec::new();
        let mut ordered: Vec<&Skill> = snapshot.skills.iter().collect();
        ordered.sort_by(|a, b| jsrt::collate::locale_compare(&a.name, &b.name));
        for skill in ordered {
            considered.insert(skill.name.clone(), skill.version.clone().into());
            if !skill.invocable {
                excluded.push(json!({"name": skill.name, "version": skill.version, "reason": "not_invocable"}));
                continue;
            }
            if let Some(candidate) = score(skill, &terms, &query) {
                scored.push(candidate);
            }
        }
        scored.sort_by(|a, b| {
            b["score"]
                .as_i64()
                .cmp(&a["score"].as_i64())
                .then_with(|| a["name"].as_str().cmp(&b["name"].as_str()))
        });
        scored.truncate(limit as usize);
        let chosen: Vec<Value> = scored
            .iter()
            .map(|candidate| json!({"name": candidate["name"], "version": candidate["version"]}))
            .collect();
        let decision = json!({
            "id": jsrt::random::uuid_v4(),
            "at": (self.now)(),
            "query": query,
            "terms": terms,
            "caller_task_id": caller,
            "catalog_generation": snapshot.generation,
            "considered": considered,
            "excluded": excluded,
            "candidates": scored,
            "chosen": chosen,
        });
        let _exclusive = jsrt::sync::lock(&self.exclusive);
        self.mutate(|document| append(document, "decisions", decision.clone()))?;
        Ok(decision)
    }

    fn load(&self, payload: &Map<String, Value>, caller: Option<&str>) -> Result<Value, String> {
        kernel::ops::fields("skills.load", payload)?;
        let name = jsrt::payload::nonempty_string(payload.get("name"), "name")?;
        let version = match payload.get("version") {
            None => None,
            value => Some(version_string(value)?),
        };
        let snapshot = self.current()?;
        let skill = Self::pinned(&snapshot, &name, version.as_deref())?;
        let id = jsrt::random::uuid_v4();
        let context_chars = jsrt::utf16::len(&skill.content);
        let record = json!({"id": id, "at": (self.now)(), "name": name, "version": skill.version,
            "caller_task_id": caller, "context_chars": context_chars});
        {
            let _exclusive = jsrt::sync::lock(&self.exclusive);
            self.mutate(|document| append(document, "loads", record))?;
        }
        Ok(json!({
            "load_id": id,
            "name": name,
            "version": skill.version,
            "description": skill.description,
            "invocable": skill.invocable,
            "content": skill.content,
            "context_chars": context_chars,
            "ignored_capability_requests": skill.ignored,
        }))
    }
}

impl crate::ApiModule for SkillsModule {
    fn prefixes(&self) -> &[&str] {
        &["skills."]
    }

    fn start(&self, _host: &dyn crate::TaskHost) -> Result<(), String> {
        SkillsModule::start(self)
    }

    fn handle(&self, request: &crate::Request<'_>) -> Result<Value, String> {
        SkillsModule::handle_with_host(
            self,
            request.kind,
            request.payload,
            request.caller_task,
            request.host,
            request.signal,
        )
    }
}