Skip to main content

kernel_apis/
code_skills.rs

1//! Code skills: procedural memory as tested Python (port of `ultron/code-skills.ts`).
2//!
3//! A code skill is a Python module under `<dir>/<name>/`. Every proposal becomes a numbered version in
4//! `.versions/<n>/` (skill.py, test_skill.py, SKILL.md); its test runs in a fresh kernel that refuses every host
5//! request, and only a passing version becomes active. The active version is copied to the skill directory's top
6//! level (Pi's skill loader lists its SKILL.md) and `skills_api.py` makes it importable as
7//! `from code_skills import <name>` in every kernel, verified against the recorded sha256. States: proposed →
8//! active | rejected; an activation supersedes the previous active version and remembers it; only the active
9//! version can be rolled back, which restores the version it superseded (or leaves none active).
10//! `.history.json` is written as `JSON.stringify(history, null, "\t")`, so either implementation reads the other's.
11
12use crate::util::{Clock, object, system_clock};
13use kernel::{HostHandler, Kernel, KernelOptions, Signal, Status};
14use serde_json::{Map, Value, json};
15use std::path::{Path, PathBuf};
16use std::sync::Arc;
17use std::time::{Duration, Instant};
18
19pub const CODE_SKILL_TEST_TIMEOUT_MS_ENV: &str = "ULTRON_CODE_SKILL_TEST_TIMEOUT_MS";
20
21const MAX_SOURCE_BYTES: usize = 64 * 1024;
22const MAX_EVIDENCE_BYTES: usize = 16 * 1024;
23const MAX_FAMILY_CHARS: usize = 200;
24pub const DEFAULT_TEST_TIMEOUT_MS: u64 = 120_000;
25const MAX_DESCRIPTION_ENTRY_CHARS: usize = 240;
26const MAX_DESCRIPTION_CHARS: usize = 3000;
27const MAX_DESCRIPTION_ENTRIES: usize = 24;
28const REPORT_MARKER: &str = "ULTRON_CODE_SKILL_REPORT";
29const RUNNER: &str = include_str!("code_skill_runner.txt");
30const PYTHON_KEYWORDS: &[&str] = &[
31    "false", "none", "true", "and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del",
32    "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "nonlocal",
33    "not", "or", "pass", "raise", "return", "try", "while", "with", "yield", "match", "case", "type",
34];
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum CodeSkillKind {
38    Code,
39    Policy,
40}
41
42impl CodeSkillKind {
43    pub fn as_str(self) -> &'static str {
44        match self {
45            Self::Code => "code",
46            Self::Policy => "policy",
47        }
48    }
49}
50
51/// `validCodeSkillName`: a lowercase Python identifier of at most 64 characters that is not a keyword.
52pub fn valid_code_skill_name(name: &str) -> bool {
53    let bytes = name.as_bytes();
54    !bytes.is_empty()
55        && bytes.len() <= 64
56        && bytes[0].is_ascii_lowercase()
57        && bytes
58            .iter()
59            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_')
60        && !PYTHON_KEYWORDS.contains(&name)
61}
62
63fn code_skill_name(value: Option<&Value>) -> Result<String, String> {
64    match value.and_then(Value::as_str) {
65        Some(name) if valid_code_skill_name(name) => Ok(name.to_string()),
66        _ => Err("name must be a lowercase Python identifier (a-z, 0-9, _; at most 64 characters)".into()),
67    }
68}
69
70fn source_text(value: Option<&Value>, label: &str) -> Result<String, String> {
71    let text = match value.and_then(Value::as_str) {
72        Some(text) if !jsrt::string::trim(text).is_empty() => text,
73        _ => return Err(format!("{label} must be nonempty Python source")),
74    };
75    if text.len() > MAX_SOURCE_BYTES {
76        return Err(format!("{label} exceeds 64 KiB"));
77    }
78    Ok(text.to_string())
79}
80
81fn nonempty_json(value: &Value) -> bool {
82    match value {
83        Value::Null => false,
84        Value::String(text) => !jsrt::string::trim(text).is_empty(),
85        Value::Array(items) => items.iter().any(nonempty_json),
86        Value::Object(map) => map.values().any(nonempty_json),
87        _ => true,
88    }
89}
90
91fn evidence_value(value: Option<&Value>) -> Result<Value, String> {
92    // As for refinement activation, a skill needs nonempty evidence of the decomposition that worked.
93    let value = value
94        .filter(|value| nonempty_json(value))
95        .ok_or("evidence must be nonempty JSON (what worked, and where)")?;
96    if jsrt::json::stringify(value).len() > MAX_EVIDENCE_BYTES {
97        return Err("evidence exceeds 16 KiB".into());
98    }
99    Ok(value.clone())
100}
101
102fn atomic_write(path: &Path, content: &str) -> Result<(), String> {
103    let temporary = PathBuf::from(format!("{}.{}.tmp", path.display(), jsrt::random::uuid_v4()));
104    std::fs::write(&temporary, content).map_err(|error| error.to_string())?;
105    std::fs::rename(&temporary, path).map_err(|error| error.to_string())
106}
107
108fn read_history(base: &Path, name: &str) -> Result<Value, String> {
109    let path = base.join(".history.json");
110    let text = match std::fs::read_to_string(&path) {
111        Ok(text) => text,
112        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
113            return Ok(json!({"format": 1, "name": name, "active": null, "versions": []}));
114        }
115        Err(error) => return Err(error.to_string()),
116    };
117    let history: Value = serde_json::from_str(&text).map_err(|error| error.to_string())?;
118    if history["format"] != 1 || history["name"] != name || !history["versions"].is_array() {
119        return Err(format!("Code skill history for {name} is invalid"));
120    }
121    Ok(history)
122}
123
124fn versions(history: &mut Value) -> &mut Vec<Value> {
125    match history.get_mut("versions") {
126        Some(Value::Array(items)) => items,
127        _ => unreachable!("read_history checks versions"),
128    }
129}
130
131/// `oneLine`: the first nonblank line, trimmed, cut to `limit` UTF-16 units with an ellipsis.
132fn one_line(text: Option<&str>, limit: usize) -> String {
133    let line = text
134        .unwrap_or("")
135        .split('\n')
136        .map(|item| item.strip_suffix('\r').unwrap_or(item))
137        .find(|item| !jsrt::string::trim(item).is_empty())
138        .unwrap_or("");
139    let trimmed = jsrt::string::trim(line);
140    if jsrt::utf16::len(trimmed) > limit {
141        format!("{}…", jsrt::utf16::head(trimmed, limit - 1))
142    } else {
143        trimmed.to_string()
144    }
145}
146
147fn nonempty_str(value: &Value) -> Option<&str> {
148    value.as_str().filter(|text| !text.is_empty())
149}
150
151fn skill_markdown(name: &str, record: &Value) -> String {
152    let doc = nonempty_str(&record["test"]["doc"]);
153    let kind = record["kind"].as_str().unwrap_or("code");
154    let mut description = one_line(doc, 300);
155    if description.is_empty() {
156        let label = if kind == "policy" { "policy" } else { "code" };
157        description = format!("Python {label} skill {name} (tested).");
158    }
159    let mut lines = vec![
160        "---".to_string(),
161        format!("name: {}", name.replace('_', "-")),
162        format!("description: {}", jsrt::json::stringify(&Value::String(description))),
163        "---".to_string(),
164        format!("# {name} ({kind} skill, version {})", record["version"]),
165        String::new(),
166        format!("Tested Python. In the rlm tool: `from code_skills import {name}`."),
167    ];
168    if let Some(family) = nonempty_str(&record["family"]) {
169        lines.extend([String::new(), format!("Task family: {family}")]);
170    }
171    if let Some(doc) = doc {
172        lines.extend([String::new(), jsrt::string::trim(doc).to_string()]);
173    }
174    let functions = record["test"]["functions"].as_array().cloned().unwrap_or_default();
175    if !functions.is_empty() {
176        lines.extend([String::new(), "## Functions".to_string(), String::new()]);
177        for function in &functions {
178            let signature = function["signature"].as_str().unwrap_or("");
179            let doc = match nonempty_str(&function["doc"]) {
180                Some(doc) => format!(": {}", one_line(Some(doc), 200)),
181                None => String::new(),
182            };
183            lines.push(format!("- `{signature}`{doc}"));
184        }
185    }
186    lines.push(String::new());
187    lines.join("\n")
188}
189
190/// Python run in the fresh test kernel; it writes its report to a nonce file, never trusting stdout framing.
191fn test_runner(name: &str, kind: CodeSkillKind, dir: &Path, report_path: &Path) -> String {
192    let options = json!({
193        "name": name,
194        "kind": kind.as_str(),
195        "dir": dir.to_string_lossy(),
196        "reportPath": report_path.to_string_lossy(),
197    });
198    let literal = jsrt::json::stringify(&Value::String(jsrt::json::stringify(&options)));
199    format!("\n{}", RUNNER.replace("{CONFIG}", &literal))
200}
201
202fn failed_report(error: &str, duration_ms: i64) -> Value {
203    json!({
204        "passed": false,
205        "tests": [],
206        "error": jsrt::utf16::head(error, 2000),
207        "durationMs": duration_ms,
208        "doc": null,
209        "functions": [],
210    })
211}
212
213fn parse_report(text: &str) -> Result<Value, String> {
214    let body = text.strip_prefix(REPORT_MARKER).ok_or("malformed test report")?;
215    let value: Value = serde_json::from_str(body).map_err(|error| error.to_string())?;
216    if !value["passed"].is_boolean() || !value["tests"].is_array() {
217        return Err("malformed test report".into());
218    }
219    Ok(value)
220}
221
222/// A kernel that refuses every host request: a skill test gets no host capabilities.
223struct Refuse;
224
225impl HostHandler for Refuse {
226    fn handle(&self, _kind: &str, _payload: Map<String, Value>, _signal: &Signal) -> Result<Value, String> {
227        Err("Host requests are unavailable while a code skill test runs".into())
228    }
229}
230
231/// Cross-process exclusion per skill, compatible with proper-lockfile: the lock is the `.lock` directory; one older
232/// than 30 s is stale and taken over. Tried 101 times, 20 ms apart at first, doubling to 500 ms.
233fn lock_skill(base: &Path) -> Result<config::lock::LockGuard, String> {
234    std::fs::create_dir_all(base).map_err(|error| error.to_string())?;
235    let options = config::lock::Options {
236        stale: Duration::from_secs(30),
237        retry: config::lock::Retry {
238            delay: Duration::from_millis(20),
239            backoff_to: Some(Duration::from_millis(500)),
240            until: config::lock::Until::Tries(101),
241        },
242        update: None,
243    };
244    config::lock::acquire(&base.join(".lock"), options).map_err(|error| error.to_string())
245}
246
247pub struct CodeSkillsOptions {
248    /// Where skills live (`ULTRON_CODE_SKILLS_DIR`, else `<agentDir>/skills`).
249    pub dir: PathBuf,
250    /// runtime.py for the test kernels.
251    pub runtime_path: PathBuf,
252    /// Interpreter for the test kernels; default as for every kernel.
253    pub python: Option<PathBuf>,
254    /// Wall budget of one test run (a session's `ULTRON_CODE_SKILL_TEST_TIMEOUT_MS`, default 120 s).
255    pub test_timeout_ms: u64,
256    pub now: Clock,
257    /// The environment test kernels start from (`KernelOptions::base_env`): the session's, so a skill's test finds
258    /// its tools on the session's PATH, never the server process's. None: this process's environment.
259    pub base_env: Option<Vec<(String, String)>>,
260}
261
262impl CodeSkillsOptions {
263    /// Options with the default test budget and this process's environment for test kernels.
264    pub fn new(dir: impl Into<PathBuf>, runtime_path: impl Into<PathBuf>) -> Self {
265        Self {
266            dir: dir.into(),
267            runtime_path: runtime_path.into(),
268            python: None,
269            test_timeout_ms: DEFAULT_TEST_TIMEOUT_MS,
270            now: system_clock(),
271            base_env: None,
272        }
273    }
274
275    /// [`CodeSkillsOptions::new`] for a session: test kernels start from `base_env`, and the test budget is the
276    /// session's `ULTRON_CODE_SKILL_TEST_TIMEOUT_MS` (from `base_env`, never this process's environment).
277    pub fn for_session(
278        dir: impl Into<PathBuf>,
279        runtime_path: impl Into<PathBuf>,
280        base_env: Vec<(String, String)>,
281    ) -> Self {
282        let configured = base_env
283            .iter()
284            .find(|(key, _)| key == CODE_SKILL_TEST_TIMEOUT_MS_ENV)
285            .and_then(|(_, value)| value.trim().parse::<u64>().ok())
286            .filter(|value| *value > 0);
287        Self {
288            test_timeout_ms: configured.unwrap_or(DEFAULT_TEST_TIMEOUT_MS),
289            base_env: Some(base_env),
290            ..Self::new(dir, runtime_path)
291        }
292    }
293}
294
295pub struct CodeSkills {
296    options: CodeSkillsOptions,
297}
298
299impl CodeSkills {
300    pub fn new(options: CodeSkillsOptions) -> Self {
301        Self { options }
302    }
303
304    pub fn dir(&self) -> &Path {
305        &self.options.dir
306    }
307
308    fn base(&self, name: &str) -> PathBuf {
309        self.options.dir.join(name)
310    }
311
312    fn now(&self) -> i64 {
313        (self.options.now)()
314    }
315
316    fn write_history(&self, history: &Value) -> Result<(), String> {
317        let name = history["name"].as_str().unwrap_or_default();
318        atomic_write(
319            &self.base(name).join(".history.json"),
320            &format!("{}\n", jsrt::json::stringify_indented(history, "\t")),
321        )
322    }
323
324    /// Top-level copy of the active version for Pi's loader and people; removed when none is active.
325    fn publish(&self, history: &Value) -> Result<(), String> {
326        let base = self.base(history["name"].as_str().unwrap_or_default());
327        let active = history["versions"]
328            .as_array()
329            .and_then(|items| items.iter().find(|item| item["version"] == history["active"]));
330        for file in ["SKILL.md", "skill.py", "test_skill.py"] {
331            let target = base.join(file);
332            match active {
333                Some(record) => {
334                    let source = base.join(".versions").join(record["version"].to_string()).join(file);
335                    let content = std::fs::read_to_string(source).map_err(|error| error.to_string())?;
336                    atomic_write(&target, &content)?;
337                }
338                None => {
339                    let _ = std::fs::remove_file(target);
340                }
341            }
342        }
343        Ok(())
344    }
345
346    fn secret_check(name: &str, source: &str, test_source: &str, evidence: &Value) -> Value {
347        let evidence_text = match evidence {
348            Value::String(text) => text.clone(),
349            other => jsrt::json::stringify(other),
350        };
351        if host::secrets::contains_code_secret(&format!("{name}\n{source}\n{test_source}\n{evidence_text}")) {
352            json!({"status": "sensitive", "reason": "the proposal contains a secret or credential"})
353        } else {
354            json!({"status": "clean"})
355        }
356    }
357
358    fn run_test(
359        &self,
360        name: &str,
361        kind: CodeSkillKind,
362        source: &str,
363        test_source: &str,
364        signal: &Signal,
365    ) -> Result<Value, String> {
366        let started = self.now();
367        let work = tempfile::Builder::new()
368            .prefix("ultron-skill-test-")
369            .tempdir()
370            .map_err(|error| error.to_string())?;
371        let report_path = work.path().join(format!(".report-{}.json", jsrt::random::uuid_v4()));
372        // A copy, so the test can never alter the version it is judging.
373        let dir = work.path().join("candidate");
374        std::fs::create_dir(&dir).map_err(|error| error.to_string())?;
375        std::fs::write(dir.join("skill.py"), source).map_err(|error| error.to_string())?;
376        std::fs::write(dir.join("test_skill.py"), test_source).map_err(|error| error.to_string())?;
377        let mut options = KernelOptions::new(work.path(), &self.options.runtime_path);
378        options.python = self.options.python.clone();
379        options.base_env = self.options.base_env.clone();
380        options.env = vec![(
381            kernel::env::CODE_SKILLS_DIR_ENV.into(),
382            self.options.dir.to_string_lossy().into_owned(),
383        )];
384        let timeout = Duration::from_millis(self.options.test_timeout_ms);
385        let run = Signal::new();
386        let done = Signal::new();
387        let watcher = {
388            let (run, done, parent) = (run.clone(), done.clone(), signal.clone());
389            std::thread::spawn(move || {
390                let deadline = Instant::now() + timeout;
391                loop {
392                    let left = deadline.saturating_duration_since(Instant::now());
393                    if done.wait(left.min(Duration::from_millis(50))) {
394                        return;
395                    }
396                    if let Some(reason) = parent.reason() {
397                        run.abort(reason);
398                        return;
399                    }
400                    if Instant::now() >= deadline {
401                        run.abort(format!("test timed out after {} ms", timeout.as_millis()));
402                        return;
403                    }
404                }
405            })
406        };
407        let outcome = Kernel::new(options, Arc::new(Refuse)).and_then(|kernel| {
408            let result = kernel.execute(&test_runner(name, kind, &dir, &report_path), Some(&run), None);
409            kernel.shutdown();
410            result
411        });
412        done.abort("finished");
413        let _ = watcher.join();
414        let outcome = match outcome {
415            Ok(result) if result.status == Status::Error => {
416                let error = result.error.unwrap_or_else(|| kernel::CellError {
417                    ename: "PythonError".into(),
418                    evalue: "Execution failed".into(),
419                    traceback: Vec::new(),
420                });
421                Err(format!("{}: {}", error.ename, error.evalue))
422            }
423            Ok(_) => std::fs::read_to_string(&report_path)
424                .map_err(|error| error.to_string())
425                .and_then(|text| parse_report(&text)),
426            Err(error) => Err(error.message().to_string()),
427        };
428        match outcome {
429            Ok(report) => Ok(report),
430            Err(message) => {
431                if let Some(reason) = signal.reason() {
432                    return Err(reason);
433                }
434                let elapsed = self.now() - started;
435                let timed_out = elapsed >= self.options.test_timeout_ms as i64;
436                let message = if timed_out {
437                    format!("test timed out after {} ms", self.options.test_timeout_ms)
438                } else {
439                    message
440                };
441                Ok(failed_report(&message, elapsed))
442            }
443        }
444    }
445
446    /// `skills.propose_code` / `skills.propose_policy`.
447    pub fn propose(&self, kind: CodeSkillKind, payload: &Map<String, Value>, signal: &Signal) -> Result<Value, String> {
448        let op = match kind {
449            CodeSkillKind::Code => "skills.propose_code",
450            CodeSkillKind::Policy => "skills.propose_policy",
451        };
452        kernel::ops::fields(op, payload)?;
453        let name = code_skill_name(payload.get("name"))?;
454        let source = source_text(payload.get("source"), "source")?;
455        let test_source = source_text(payload.get("test_source"), "test_source")?;
456        let evidence = evidence_value(payload.get("evidence"))?;
457        let family = match payload.get("family") {
458            None => Value::Null,
459            Some(Value::String(family))
460                if !jsrt::string::trim(family).is_empty() && jsrt::utf16::len(family) <= MAX_FAMILY_CHARS =>
461            {
462                Value::String(jsrt::string::trim(family).to_string())
463            }
464            Some(_) => {
465                return Err(format!(
466                    "family must be a nonempty string of at most {MAX_FAMILY_CHARS} characters"
467                ));
468            }
469        };
470        let base = self.base(&name);
471        if base.join("SKILL.md").exists() && !base.join(".history.json").exists() {
472            return Err(format!(
473                "{name} is an instruction skill (SKILL.md without code history); choose another name"
474            ));
475        }
476        let secret_check = Self::secret_check(&name, &source, &test_source, &evidence);
477        if secret_check["status"] == "sensitive" {
478            return Ok(object(vec![
479                ("status", "refused".into()),
480                ("name", name.into()),
481                ("kind", kind.as_str().into()),
482                ("version", Value::Null),
483                ("previous", Value::Null),
484                (
485                    "reason",
486                    format!("{}; nothing was written", secret_check["reason"].as_str().unwrap_or("")).into(),
487                ),
488                ("test", Value::Null),
489                ("secretCheck", secret_check),
490            ]));
491        }
492        let at = || jsrt::date::iso_string(self.now());
493        let cause = jsrt::random::uuid_v4();
494        let version = {
495            let _lock = lock_skill(&base)?;
496            let mut history = read_history(&base, &name)?;
497            let next = versions(&mut history)
498                .iter()
499                .filter_map(|item| item["version"].as_i64())
500                .fold(0, i64::max)
501                + 1;
502            let directory = base.join(".versions").join(next.to_string());
503            std::fs::create_dir_all(&directory).map_err(|error| error.to_string())?;
504            let record = object(vec![
505                ("version", next.into()),
506                ("kind", kind.as_str().into()),
507                ("family", family.clone()),
508                ("state", "proposed".into()),
509                ("createdAt", at().into()),
510                (
511                    "sha256",
512                    json!({"skill": jsrt::hash::sha256_hex(source.as_bytes()), "test": jsrt::hash::sha256_hex(test_source.as_bytes())}),
513                ),
514                ("evidence", evidence.clone()),
515                ("previous", Value::Null),
516                ("secretCheck", secret_check.clone()),
517                ("test", Value::Null),
518                ("history", json!([{"state": "proposed", "at": at(), "cause": cause}])),
519            ]);
520            let write = |file: &str, content: &str| {
521                std::fs::write(directory.join(file), content).map_err(|error| error.to_string())
522            };
523            write("skill.py", &source)?;
524            write("test_skill.py", &test_source)?;
525            write("SKILL.md", &skill_markdown(&name, &record))?;
526            versions(&mut history).push(record);
527            self.write_history(&history)?;
528            next
529        };
530        let report = self.run_test(&name, kind, &source, &test_source, signal)?;
531        let _lock = lock_skill(&base)?;
532        let mut history = read_history(&base, &name)?;
533        let passed = report["passed"] == true;
534        let active = history["active"].clone();
535        let entries = versions(&mut history);
536        let index = entries
537            .iter()
538            .position(|item| item["version"] == version)
539            .ok_or_else(|| format!("Code skill {name} lost version {version}"))?;
540        entries[index]["test"] = report.clone();
541        // Regenerate SKILL.md now that the docstring is known.
542        let directory = base.join(".versions").join(version.to_string());
543        std::fs::write(directory.join("SKILL.md"), skill_markdown(&name, &entries[index]))
544            .map_err(|error| error.to_string())?;
545        let mut previous = Value::Null;
546        let push = |record: &mut Value, state: &str| {
547            record["state"] = state.into();
548            if let Some(Value::Array(changes)) = record.get_mut("history") {
549                changes.push(json!({"state": state, "at": at(), "cause": cause}));
550            }
551        };
552        if passed {
553            if let Some(current) = entries
554                .iter_mut()
555                .find(|item| item["version"] == active && item["state"] == "active")
556            {
557                push(current, "superseded");
558                previous = current["version"].clone();
559            }
560            entries[index]["previous"] = previous.clone();
561            push(&mut entries[index], "active");
562            history["active"] = version.into();
563        } else {
564            push(&mut entries[index], "rejected");
565        }
566        self.write_history(&history)?;
567        if passed {
568            self.publish(&history)?;
569        }
570        let mut result = vec![
571            ("status", Value::from(if passed { "active" } else { "rejected" })),
572            ("name", name.clone().into()),
573            ("kind", kind.as_str().into()),
574            ("version", version.into()),
575            ("previous", previous),
576        ];
577        if passed {
578            result.push(("import", format!("from code_skills import {name}").into()));
579        }
580        result.push(("test", report));
581        result.push(("secretCheck", secret_check));
582        Ok(object(result))
583    }
584
585    /// `skills.rollback`: only the active version can be rolled back; the version it superseded returns.
586    pub fn rollback(&self, payload: &Map<String, Value>) -> Result<Value, String> {
587        kernel::ops::fields("skills.rollback", payload)?;
588        let name = code_skill_name(payload.get("name"))?;
589        let version = payload
590            .get("version")
591            .and_then(jsrt::number::safe_integer)
592            .filter(|version| *version >= 1)
593            .ok_or("version must be a positive integer")?;
594        let base = self.base(&name);
595        if !base.join(".history.json").exists() {
596            return Err(format!("Unknown code skill: {name}"));
597        }
598        let _lock = lock_skill(&base)?;
599        let mut history = read_history(&base, &name)?;
600        let active = history["active"].clone();
601        let at = jsrt::date::iso_string(self.now());
602        let cause = jsrt::random::uuid_v4();
603        let entries = versions(&mut history);
604        let index = entries
605            .iter()
606            .position(|item| item["version"] == version)
607            .ok_or_else(|| format!("Unknown version {version} of code skill {name}"))?;
608        if active != version || entries[index]["state"] != "active" {
609            let has = if active.is_null() {
610                "no active version".to_string()
611            } else {
612                format!("version {active} active")
613            };
614            return Err(format!("Only the active version can be rolled back: {name} has {has}"));
615        }
616        let change = |record: &mut Value, state: &str| {
617            record["state"] = state.into();
618            if let Some(Value::Array(changes)) = record.get_mut("history") {
619                changes.push(json!({"state": state, "at": at, "cause": cause}));
620            }
621        };
622        change(&mut entries[index], "rolled_back");
623        let superseded = entries[index]["previous"].clone();
624        let restored = entries
625            .iter_mut()
626            .find(|item| item["version"] == superseded && item["state"] == "superseded")
627            .map(|previous| {
628                change(previous, "active");
629                previous["version"].clone()
630            })
631            .unwrap_or(Value::Null);
632        history["active"] = restored.clone();
633        self.write_history(&history)?;
634        self.publish(&history)?;
635        Ok(json!({"name": name, "rolledBack": version, "active": restored}))
636    }
637
638    /// `skills.code_history`.
639    pub fn history(&self, name: Option<&Value>) -> Result<Value, String> {
640        let name = code_skill_name(name)?;
641        let base = self.base(&name);
642        if !base.join(".history.json").exists() {
643            return Err(format!("Unknown code skill: {name}"));
644        }
645        read_history(&base, &name)
646    }
647
648    /// Active code skills, most recently activated first. Unreadable entries are skipped.
649    pub fn list(&self, kind: Option<&str>, family: Option<&str>) -> Vec<Value> {
650        let Ok(entries) = std::fs::read_dir(&self.options.dir) else {
651            return Vec::new();
652        };
653        let mut names: Vec<String> = entries
654            .filter_map(|entry| entry.ok()?.file_name().into_string().ok())
655            .collect();
656        names.sort();
657        let mut skills = Vec::new();
658        for name in names {
659            let base = self.base(&name);
660            if !valid_code_skill_name(&name) || !base.join(".history.json").exists() {
661                continue;
662            }
663            let Ok(history) = read_history(&base, &name) else {
664                continue;
665            };
666            let Some(record) = history["versions"].as_array().and_then(|items| {
667                items
668                    .iter()
669                    .find(|item| item["version"] == history["active"] && item["state"] == "active")
670            }) else {
671                continue;
672            };
673            if kind.is_some_and(|kind| record["kind"] != kind)
674                || family.is_some_and(|family| record["family"] != family)
675            {
676                continue;
677            }
678            let activated = record["history"]
679                .as_array()
680                .and_then(|changes| changes.iter().rev().find(|change| change["state"] == "active"))
681                .map(|change| change["at"].clone())
682                .unwrap_or_else(|| record["createdAt"].clone());
683            skills.push(object(vec![
684                ("name", name.into()),
685                ("kind", record["kind"].clone()),
686                ("family", record["family"].clone()),
687                ("version", record["version"].clone()),
688                ("doc", record["test"].get("doc").cloned().unwrap_or(Value::Null)),
689                (
690                    "functions",
691                    record["test"].get("functions").cloned().unwrap_or(json!([])),
692                ),
693                ("activatedAt", activated),
694            ]));
695        }
696        skills.sort_by(|a, b| {
697            let text = |value: &Value, key: &str| value[key].as_str().unwrap_or("").to_string();
698            text(b, "activatedAt")
699                .cmp(&text(a, "activatedAt"))
700                .then_with(|| jsrt::collate::locale_compare(&text(a, "name"), &text(b, "name")))
701        });
702        skills
703    }
704
705    /// The rlm tool description's listing: one line per active skill, bounded in entries and characters.
706    pub fn describe(&self) -> String {
707        let skills = self.list(None, None);
708        if skills.is_empty() {
709            return String::new();
710        }
711        let mut lines = Vec::new();
712        let mut size = 0;
713        for (index, skill) in skills.iter().enumerate() {
714            let signatures: Vec<&str> = skill["functions"]
715                .as_array()
716                .map(|functions| functions.iter().filter_map(|f| f["signature"].as_str()).collect())
717                .unwrap_or_default();
718            let signatures = signatures.join("; ");
719            let summary = one_line(nonempty_str(&skill["doc"]), 160);
720            let policy = if skill["kind"] == "policy" {
721                match nonempty_str(&skill["family"]) {
722                    Some(family) => format!(" (policy, {family})"),
723                    None => " (policy)".to_string(),
724                }
725            } else {
726                String::new()
727            };
728            let gap = if !summary.is_empty() && !signatures.is_empty() {
729                " "
730            } else {
731                ""
732            };
733            let listed = if signatures.is_empty() {
734                String::new()
735            } else {
736                format!("[{signatures}]")
737            };
738            let mut line = format!(
739                "- {} v{}{policy}: {summary}{gap}{listed}",
740                skill["name"].as_str().unwrap_or(""),
741                skill["version"]
742            );
743            if jsrt::utf16::len(&line) > MAX_DESCRIPTION_ENTRY_CHARS {
744                line = format!("{}…", jsrt::utf16::head(&line, MAX_DESCRIPTION_ENTRY_CHARS - 1));
745            }
746            if index >= MAX_DESCRIPTION_ENTRIES || size + jsrt::utf16::len(&line) > MAX_DESCRIPTION_CHARS {
747                lines.push(format!("- … {} more: `await skills.code_list()`", skills.len() - index));
748                break;
749            }
750            size += jsrt::utf16::len(&line) + 1;
751            lines.push(line);
752        }
753        let mut out = vec!["Active code skills (`from code_skills import <name>`):".to_string()];
754        out.extend(lines);
755        out.join("\n")
756    }
757}