Skip to main content

ikigai_script/
model.rs

1//! What the atoms hold: a script's head, its immutable versions, and its runs.
2//!
3//! These are also the machine faces (`as=application/json`): one serde shape for the disk
4//! and the wire, carrying `"schema": 1` so a consumer can tell a future shape apart.
5
6use std::collections::BTreeSet;
7
8use ikigai_core::{Error, Result};
9use serde::{Deserialize, Serialize};
10use sha2::{Digest, Sha256};
11
12use crate::authority::CAP_LISP;
13
14/// The version of every JSON shape this crate writes.
15pub const SCHEMA: u32 = 1;
16
17/// The languages a script can be written in.
18#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
19#[serde(rename_all = "lowercase")]
20pub enum Language {
21    /// Steel Scheme, evaluated by `ikigai-lisp` at `urn:lisp:eval`.
22    Lisp,
23    /// A SPARQL query or update, evaluated by the host's store through its graph-scoped
24    /// doors (see [`crate::sparql`]). Its form, parameters and authority are read from the
25    /// parsed text.
26    Sparql,
27    /// A plan: an `ik:Process` graph (Turtle), validated by the host's `urn:plan:validate`
28    /// and run by its `urn:plan:eval` (see [`crate::plan`]). Its authority is derived from
29    /// its steps' contracts, and whether it is a read or a write from its steps' verbs.
30    Plan,
31}
32
33impl Language {
34    /// Every language, in the order `language=` offers them.
35    pub const ALL: [Language; 3] = [Language::Lisp, Language::Sparql, Language::Plan];
36
37    /// The word `language=` takes and every face shows.
38    pub fn as_str(self) -> &'static str {
39        match self {
40            Language::Lisp => "lisp",
41            Language::Sparql => "sparql",
42            Language::Plan => "plan",
43        }
44    }
45
46    /// Parse `language=`.
47    pub fn parse(text: &str) -> Result<Language> {
48        match text.trim() {
49            "lisp" => Ok(Language::Lisp),
50            "sparql" => Ok(Language::Sparql),
51            "plan" => Ok(Language::Plan),
52            other => Err(Error::InvalidArgument {
53                name: "language".to_string(),
54                detail: format!(
55                    "`{other}` is not a script language here; `lisp`, `sparql` or `plan`"
56                ),
57            }),
58        }
59    }
60
61    /// The evaluator a Lisp run issues its sub-request to: the language is a resource, so
62    /// this crate links no interpreter. `None` for SPARQL, whose door is the HOST's choice
63    /// ([`crate::sparql::SparqlDoor`]) and depends on the query's form. A plan's is
64    /// [`crate::plan::EVAL`].
65    pub fn evaluator(self) -> Option<&'static str> {
66        match self {
67            Language::Lisp => Some("urn:lisp:eval"),
68            Language::Sparql => None,
69            Language::Plan => Some(crate::plan::EVAL),
70        }
71    }
72
73    /// The capability the evaluator itself requires, which every script in the language
74    /// declares implicitly: evaluating code is itself authority, so a publisher who may not
75    /// run Lisp may not publish Lisp for others to run. `None` for SPARQL: a query's
76    /// authority is the graphs it names, derived from its text (see
77    /// [`crate::sparql::Analysis::requires`]). `None` for a plan: its authority is what its
78    /// steps' contracts require, derived at publish (see [`crate::plan::derive`]), and
79    /// `urn:plan:eval` declares none of its own.
80    pub fn capability(self) -> Option<&'static str> {
81        match self {
82            Language::Lisp => Some(CAP_LISP),
83            Language::Sparql | Language::Plan => None,
84        }
85    }
86}
87
88/// A script's lifecycle state.
89#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
90#[serde(rename_all = "lowercase")]
91pub enum State {
92    /// Saved, not runnable, and PRIVATE until published: a version that was never published
93    /// is visible only to its author (the principal the host stamped when they wrote it)
94    /// and to root. To every other holder of the script's read or run grant it is absent.
95    Draft,
96    /// Runnable.
97    Published,
98    /// Retired by a Delete: still readable, versions still fetchable, never runnable.
99    Retired,
100}
101
102impl State {
103    /// The word every face shows.
104    pub fn as_str(self) -> &'static str {
105        match self {
106            State::Draft => "draft",
107            State::Published => "published",
108            State::Retired => "retired",
109        }
110    }
111}
112
113/// One immutable version: the content a digest names.
114#[derive(Clone, Debug, PartialEq, Eq)]
115pub struct Version {
116    /// Its language.
117    pub language: Language,
118    /// The capability it declares it needs, its language's included.
119    pub requires: BTreeSet<String>,
120    /// The source text.
121    pub source: String,
122}
123
124impl Version {
125    /// The bytes the digest is taken over:
126    ///
127    /// ```text
128    /// ikigai-script/1\n
129    /// language <language>\n
130    /// requires <scope>\n        (one line per scope, sorted)
131    /// \n
132    /// <source>
133    /// ```
134    ///
135    /// A scope contains no whitespace and the source comes last, so the framing is
136    /// unambiguous without escaping anything.
137    pub fn canonical(&self) -> Vec<u8> {
138        let mut out = format!("ikigai-script/1\nlanguage {}\n", self.language.as_str());
139        for scope in &self.requires {
140            out.push_str("requires ");
141            out.push_str(scope);
142            out.push('\n');
143        }
144        out.push('\n');
145        out.push_str(&self.source);
146        out.into_bytes()
147    }
148
149    /// The version's name: `sha256:` and 64 lowercase hex digits over [`canonical`].
150    ///
151    /// ```
152    /// use ikigai_script::model::{Language, Version};
153    /// let v = Version {
154    ///     language: Language::Lisp,
155    ///     requires: ["urn:cap:lisp".to_string()].into_iter().collect(),
156    ///     source: "(+ 1 2)".to_string(),
157    /// };
158    /// let digest = v.digest();
159    /// assert!(digest.starts_with("sha256:"));
160    /// assert_eq!(digest.len(), "sha256:".len() + 64);
161    /// assert!(digest["sha256:".len()..].bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()));
162    /// // Content-addressed: the same content is the same version.
163    /// assert_eq!(digest, v.clone().digest());
164    /// ```
165    ///
166    /// [`canonical`]: Version::canonical
167    pub fn digest(&self) -> String {
168        let hash = Sha256::digest(self.canonical());
169        let mut out = String::with_capacity(7 + 64);
170        out.push_str("sha256:");
171        for byte in hash {
172            out.push_str(&format!("{byte:02x}"));
173        }
174        out
175    }
176
177    /// The JSON face of this version under `name`.
178    pub fn document(&self, name: &str) -> VersionDocument {
179        let digest = self.digest();
180        VersionDocument {
181            schema: SCHEMA,
182            iri: crate::name::version_iri(name, &digest),
183            script: crate::name::script_iri(name),
184            version: digest,
185            language: self.language,
186            requires: self.requires.clone(),
187            source: self.source.clone(),
188        }
189    }
190}
191
192/// A version's JSON face.
193#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
194pub struct VersionDocument {
195    /// [`SCHEMA`].
196    pub schema: u32,
197    /// `urn:script:{name}:version:{digest}`.
198    pub iri: String,
199    /// `urn:script:{name}`.
200    pub script: String,
201    /// `sha256:…`.
202    pub version: String,
203    /// Its language.
204    pub language: Language,
205    /// What it declares it needs.
206    pub requires: BTreeSet<String>,
207    /// The source text.
208    pub source: String,
209}
210
211/// One change to a script's head: what its history is made of.
212#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
213pub struct Event {
214    /// `publish`, `draft` or `retire`.
215    pub action: String,
216    /// The version the head pointed at afterwards.
217    pub version: String,
218    /// The state afterwards.
219    pub state: State,
220    /// Whether it was public afterwards.
221    pub public: bool,
222    /// Who, as the host stamped it.
223    pub principal: String,
224    /// When, in milliseconds since the epoch, from the kernel's clock (`None` on a
225    /// clockless kernel).
226    pub at: Option<u64>,
227}
228
229/// A script's head: the mutable atom `urn:script:{name}` names.
230#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
231pub struct Head {
232    /// [`SCHEMA`].
233    pub schema: u32,
234    /// The script's name.
235    pub name: String,
236    /// The version it points at.
237    pub version: String,
238    /// Its state.
239    pub state: State,
240    /// Whether it is public: runnable by holders of
241    /// [`CAP_RUN_PUBLIC`](crate::authority::CAP_RUN_PUBLIC) and readable by holders of
242    /// [`CAP_READ_PUBLIC`](crate::authority::CAP_READ_PUBLIC), once published.
243    pub public: bool,
244    /// The part of the version's `requires` its publisher held when they published it.
245    pub granted: BTreeSet<String>,
246    /// Every exclusion the publisher's capability carried then.
247    pub exclusions: BTreeSet<String>,
248    /// Who published the version the head points at.
249    pub publisher: String,
250    /// When the head last changed.
251    pub updated: Option<u64>,
252    /// Every change, oldest first.
253    pub history: Vec<Event>,
254}
255
256/// How a run ended.
257#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
258#[serde(rename_all = "lowercase", tag = "status")]
259pub enum Outcome {
260    /// Not finished. A run that stays here after its host stopped was abandoned.
261    Running,
262    /// Finished with an answer.
263    Ok,
264    /// Finished with an error.
265    Failed {
266        /// The error's kind: `denied`, `not-found`, `conflict`, `invalid-argument`,
267        /// `timeout`, `unavailable`, `endpoint`, …
268        kind: String,
269        /// The error, as text.
270        message: String,
271    },
272}
273
274/// The longest result a run record keeps; a longer one is cut there and marked.
275pub const MAX_RECORDED_RESULT: usize = 64 * 1024;
276
277/// One run: the atom `urn:script:{name}:run:{id}` names.
278#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
279pub struct Run {
280    /// [`SCHEMA`].
281    pub schema: u32,
282    /// The script.
283    pub name: String,
284    /// Its number, unique per script, in order of starting.
285    pub id: u64,
286    /// The version that ran.
287    pub version: String,
288    /// Who ran it, as the host stamped it — never caller-supplied.
289    pub principal: String,
290    /// The capability the run executed under, exactly: grants and exclusions.
291    pub capability: BTreeSet<String>,
292    /// When it started, from the kernel's clock.
293    pub started: Option<u64>,
294    /// When it ended.
295    pub ended: Option<u64>,
296    /// How it ended.
297    pub outcome: Outcome,
298    /// What it answered, as text, up to [`MAX_RECORDED_RESULT`] bytes.
299    pub result: Option<String>,
300    /// Whether `result` was cut.
301    pub truncated: bool,
302    /// The trace span the host's tracer gave the run's request, when the host traced it:
303    /// the key into the host's trace, which holds every verb the script issued.
304    pub trace_span: Option<u64>,
305}
306
307impl Run {
308    /// Its IRI.
309    pub fn iri(&self) -> String {
310        crate::name::run_iri(&self.name, self.id)
311    }
312
313    /// The plain face: one fact per line.
314    pub fn render(&self) -> String {
315        let outcome = match &self.outcome {
316            Outcome::Running => "running".to_string(),
317            Outcome::Ok => "ok".to_string(),
318            Outcome::Failed { kind, message } => format!("failed ({kind}): {message}"),
319        };
320        let mut text = format!(
321            "{}\n  script:     {}\n  version:    {}\n  principal:  {}\n  started:    {}\n  \
322             ended:      {}\n  outcome:    {outcome}\n  capability: {}\n",
323            self.iri(),
324            crate::name::script_iri(&self.name),
325            self.version,
326            self.principal,
327            when(self.started),
328            when(self.ended),
329            if self.capability.is_empty() {
330                "(none)".to_string()
331            } else {
332                self.capability
333                    .iter()
334                    .cloned()
335                    .collect::<Vec<_>>()
336                    .join(" ")
337            },
338        );
339        if let Some(span) = self.trace_span {
340            text.push_str(&format!("  trace span: {span}\n"));
341        }
342        if let Some(result) = &self.result {
343            text.push_str(&format!(
344                "  result{}:\n{result}\n",
345                if self.truncated { " (truncated)" } else { "" }
346            ));
347        }
348        text
349    }
350}
351
352/// A timestamp for the plain faces: `xsd:dateTime` in UTC, or a note that the kernel had
353/// no clock.
354///
355/// ```
356/// use ikigai_script::model::when;
357/// assert_eq!(when(Some(1_789_430_400_000)), "2026-09-15T00:00:00.000Z");
358/// assert_eq!(when(Some(0)), "1970-01-01T00:00:00.000Z");
359/// assert_eq!(when(None), "unstamped (the kernel has no clock)");
360/// ```
361pub fn when(millis: Option<u64>) -> String {
362    let Some(millis) = millis else {
363        return "unstamped (the kernel has no clock)".to_string();
364    };
365    let secs = millis / 1000;
366    let (days, rem) = (secs / 86_400, secs % 86_400);
367    // Howard Hinnant's civil-from-days, over days since 1970-01-01.
368    let z = days as i64 + 719_468;
369    let era = z.div_euclid(146_097);
370    let doe = z - era * 146_097;
371    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
372    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
373    let mp = (5 * doy + 2) / 153;
374    let day = doy - (153 * mp + 2) / 5 + 1;
375    let month = if mp < 10 { mp + 3 } else { mp - 9 };
376    let year = yoe + era * 400 + i64::from(month <= 2);
377    format!(
378        "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z",
379        rem / 3600,
380        rem % 3600 / 60,
381        rem % 60,
382        millis % 1000
383    )
384}
385
386/// Cut `text` to at most `max` bytes on a character boundary; whether it was cut.
387pub(crate) fn truncate(mut text: String, max: usize) -> (String, bool) {
388    if text.len() <= max {
389        return (text, false);
390    }
391    let mut end = max;
392    while !text.is_char_boundary(end) {
393        end -= 1;
394    }
395    text.truncate(end);
396    (text, true)
397}
398
399#[cfg(test)]
400mod tests {
401    use super::*;
402
403    #[test]
404    fn requires_and_language_are_part_of_the_content() {
405        let a = Version {
406            language: Language::Lisp,
407            requires: BTreeSet::new(),
408            source: "(+ 1 2)".to_string(),
409        };
410        let mut b = a.clone();
411        b.requires.insert("urn:cap:lisp".to_string());
412        assert_ne!(a.digest(), b.digest());
413    }
414
415    #[test]
416    fn truncation_respects_characters() {
417        let (text, cut) = truncate("héllo".to_string(), 2);
418        assert_eq!((text.as_str(), cut), ("h", true));
419        let (text, cut) = truncate("abc".to_string(), 3);
420        assert_eq!((text.as_str(), cut), ("abc", false));
421    }
422}