ikigai-script 0.3.5

Scripts (Lisp; SPARQL queries with typed parameters and authority derived from the graphs they name; or plans, validated before they are stored, with authority derived from their steps) as resources in any ikigai host: `urn:script:{name}` is an atom with content-addressed versions, a compiled form, a result you read and runs you record, run under the least of what the script declares, what its publisher held at publish time, the host's ceiling and the runner's own capability. A host library: no binary, no elevation.
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
//! What the atoms hold: a script's head, its immutable versions, and its runs.
//!
//! These are also the machine faces (`as=application/json`): one serde shape for the disk
//! and the wire, carrying `"schema": 1` so a consumer can tell a future shape apart.

use std::collections::BTreeSet;

use ikigai_core::{Error, Result};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use crate::authority::CAP_LISP;

/// The version of every JSON shape this crate writes.
pub const SCHEMA: u32 = 1;

/// The languages a script can be written in.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Language {
    /// Steel Scheme, evaluated by `ikigai-lisp` at `urn:lisp:eval`.
    Lisp,
    /// A SPARQL query or update, evaluated by the host's store through its graph-scoped
    /// doors (see [`crate::sparql`]). Its form, parameters and authority are read from the
    /// parsed text.
    Sparql,
    /// A plan: an `ik:Process` graph (Turtle), validated by the host's `urn:plan:validate`
    /// and run by its `urn:plan:eval` (see [`crate::plan`]). Its authority is derived from
    /// its steps' contracts, and whether it is a read or a write from its steps' verbs.
    Plan,
}

impl Language {
    /// Every language, in the order `language=` offers them.
    pub const ALL: [Language; 3] = [Language::Lisp, Language::Sparql, Language::Plan];

    /// The word `language=` takes and every face shows.
    pub fn as_str(self) -> &'static str {
        match self {
            Language::Lisp => "lisp",
            Language::Sparql => "sparql",
            Language::Plan => "plan",
        }
    }

    /// Parse `language=`.
    pub fn parse(text: &str) -> Result<Language> {
        match text.trim() {
            "lisp" => Ok(Language::Lisp),
            "sparql" => Ok(Language::Sparql),
            "plan" => Ok(Language::Plan),
            other => Err(Error::InvalidArgument {
                name: "language".to_string(),
                detail: format!(
                    "`{other}` is not a script language here; `lisp`, `sparql` or `plan`"
                ),
            }),
        }
    }

    /// The evaluator a Lisp run issues its sub-request to: the language is a resource, so
    /// this crate links no interpreter. `None` for SPARQL, whose door is the HOST's choice
    /// ([`crate::sparql::SparqlDoor`]) and depends on the query's form. A plan's is
    /// [`crate::plan::EVAL`].
    pub fn evaluator(self) -> Option<&'static str> {
        match self {
            Language::Lisp => Some("urn:lisp:eval"),
            Language::Sparql => None,
            Language::Plan => Some(crate::plan::EVAL),
        }
    }

    /// The capability the evaluator itself requires, which every script in the language
    /// declares implicitly: evaluating code is itself authority, so a publisher who may not
    /// run Lisp may not publish Lisp for others to run. `None` for SPARQL: a query's
    /// authority is the graphs it names, derived from its text (see
    /// [`crate::sparql::Analysis::requires`]). `None` for a plan: its authority is what its
    /// steps' contracts require, derived at publish (see [`crate::plan::derive`]), and
    /// `urn:plan:eval` declares none of its own.
    pub fn capability(self) -> Option<&'static str> {
        match self {
            Language::Lisp => Some(CAP_LISP),
            Language::Sparql | Language::Plan => None,
        }
    }
}

/// A script's lifecycle state.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum State {
    /// Saved, not runnable, and PRIVATE until published: a version that was never published
    /// is visible only to its author (the principal their capability named when they wrote
    /// it)
    /// and to root. To every other holder of the script's read or run grant it is absent.
    Draft,
    /// Runnable.
    Published,
    /// Retired by a Delete: still readable, versions still fetchable, never runnable.
    Retired,
}

impl State {
    /// The word every face shows.
    pub fn as_str(self) -> &'static str {
        match self {
            State::Draft => "draft",
            State::Published => "published",
            State::Retired => "retired",
        }
    }
}

/// One immutable version: the content a digest names.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Version {
    /// Its language.
    pub language: Language,
    /// The capability it declares it needs, its language's included.
    pub requires: BTreeSet<String>,
    /// The store time budget it declares, in milliseconds (`budget=` at publish), or `None`
    /// for the store's base. Part of the content, so a republish that changes it is a new
    /// version (see [`crate::authority::effective_budget`] for what a run gets).
    pub budget: Option<u64>,
    /// The source text.
    pub source: String,
}

impl Version {
    /// The bytes the digest is taken over:
    ///
    /// ```text
    /// ikigai-script/1\n
    /// language <language>\n
    /// requires <scope>\n        (one line per scope, sorted)
    /// budget <milliseconds>\n   (only when it declares one)
    /// \n
    /// <source>
    /// ```
    ///
    /// A scope contains no whitespace and the source comes last, so the framing is
    /// unambiguous without escaping anything. A version declaring no budget frames exactly as
    /// one did before `budget` existed, so every digest already stored is unchanged.
    pub fn canonical(&self) -> Vec<u8> {
        let mut out = format!("ikigai-script/1\nlanguage {}\n", self.language.as_str());
        for scope in &self.requires {
            out.push_str("requires ");
            out.push_str(scope);
            out.push('\n');
        }
        if let Some(millis) = self.budget {
            out.push_str(&format!("budget {millis}\n"));
        }
        out.push('\n');
        out.push_str(&self.source);
        out.into_bytes()
    }

    /// The version's name: `sha256:` and 64 lowercase hex digits over [`canonical`].
    ///
    /// ```
    /// use ikigai_script::model::{Language, Version};
    /// let v = Version {
    ///     language: Language::Lisp,
    ///     requires: ["urn:cap:lisp".to_string()].into_iter().collect(),
    ///     budget: None,
    ///     source: "(+ 1 2)".to_string(),
    /// };
    /// let digest = v.digest();
    /// assert!(digest.starts_with("sha256:"));
    /// assert_eq!(digest.len(), "sha256:".len() + 64);
    /// assert!(digest["sha256:".len()..].bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()));
    /// // Content-addressed: the same content is the same version.
    /// assert_eq!(digest, v.clone().digest());
    /// // A declared budget is content too.
    /// let budgeted = Version { budget: Some(900), ..v.clone() };
    /// assert_ne!(budgeted.digest(), digest);
    /// ```
    ///
    /// [`canonical`]: Version::canonical
    pub fn digest(&self) -> String {
        let hash = Sha256::digest(self.canonical());
        let mut out = String::with_capacity(7 + 64);
        out.push_str("sha256:");
        for byte in hash {
            out.push_str(&format!("{byte:02x}"));
        }
        out
    }

    /// The JSON face of this version under `name`.
    pub fn document(&self, name: &str) -> VersionDocument {
        let digest = self.digest();
        VersionDocument {
            schema: SCHEMA,
            iri: crate::name::version_iri(name, &digest),
            script: crate::name::script_iri(name),
            version: digest,
            language: self.language,
            requires: self.requires.clone(),
            budget: self.budget,
            source: self.source.clone(),
        }
    }
}

/// A version's JSON face.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct VersionDocument {
    /// [`SCHEMA`].
    pub schema: u32,
    /// `urn:script:{name}:version:{digest}`.
    pub iri: String,
    /// `urn:script:{name}`.
    pub script: String,
    /// `sha256:…`.
    pub version: String,
    /// Its language.
    pub language: Language,
    /// What it declares it needs.
    pub requires: BTreeSet<String>,
    /// The store time budget it declares, in milliseconds; absent when it declares none.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub budget: Option<u64>,
    /// The source text.
    pub source: String,
}

/// One change to a script's head: what its history is made of.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Event {
    /// `publish`, `draft` or `retire`.
    pub action: String,
    /// The version the head pointed at afterwards.
    pub version: String,
    /// The state afterwards.
    pub state: State,
    /// Whether it was public afterwards.
    pub public: bool,
    /// Who: the principal the writer's capability named ([`crate::authority::principal_of`]).
    pub principal: String,
    /// When, in milliseconds since the epoch, from the kernel's clock (`None` on a
    /// clockless kernel).
    pub at: Option<u64>,
}

/// A script's head: the mutable atom `urn:script:{name}` names.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Head {
    /// [`SCHEMA`].
    pub schema: u32,
    /// The script's name.
    pub name: String,
    /// The version it points at.
    pub version: String,
    /// Its state.
    pub state: State,
    /// Whether it is public: runnable by holders of
    /// [`CAP_RUN_PUBLIC`](crate::authority::CAP_RUN_PUBLIC) and readable by holders of
    /// [`CAP_READ_PUBLIC`](crate::authority::CAP_READ_PUBLIC), once published.
    pub public: bool,
    /// The part of the version's `requires` its publisher held when they published it.
    pub granted: BTreeSet<String>,
    /// Every exclusion the publisher's capability carried then.
    pub exclusions: BTreeSet<String>,
    /// The store time budget its publisher held when they published a version declaring one
    /// ([`crate::authority::budget_at_publish`]), in milliseconds; absent otherwise.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub granted_budget: Option<u64>,
    /// Who published the version the head points at.
    pub publisher: String,
    /// When the head last changed.
    pub updated: Option<u64>,
    /// Every change, oldest first.
    pub history: Vec<Event>,
}

/// How a run ended.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase", tag = "status")]
pub enum Outcome {
    /// Not finished. A run that stays here after its host stopped was abandoned.
    Running,
    /// Finished with an answer.
    Ok,
    /// Finished with an error.
    Failed {
        /// The error's kind: `denied`, `not-found`, `conflict`, `invalid-argument`,
        /// `timeout`, `unavailable`, `endpoint`, …
        kind: String,
        /// The error, as text.
        message: String,
    },
}

/// The longest result a run record keeps; a longer one is cut there and marked.
pub const MAX_RECORDED_RESULT: usize = 64 * 1024;

/// One run: the atom `urn:script:{name}:run:{id}` names.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Run {
    /// [`SCHEMA`].
    pub schema: u32,
    /// The script.
    pub name: String,
    /// Its number, unique per script, in order of starting.
    pub id: u64,
    /// The version that ran.
    pub version: String,
    /// Who ran it: the principal the runner's capability named
    /// ([`crate::authority::principal_of`]), never caller-supplied.
    pub principal: String,
    /// The capability the run executed under, exactly: grants and exclusions.
    pub capability: BTreeSet<String>,
    /// When it started, from the kernel's clock.
    pub started: Option<u64>,
    /// When it ended.
    pub ended: Option<u64>,
    /// How it ended.
    pub outcome: Outcome,
    /// What it answered, as text, up to [`MAX_RECORDED_RESULT`] bytes.
    pub result: Option<String>,
    /// Whether `result` was cut.
    pub truncated: bool,
    /// The trace span the host's tracer gave the run's request, when the host traced it:
    /// the key into the host's trace, which holds every verb the script issued.
    pub trace_span: Option<u64>,
}

impl Run {
    /// Its IRI.
    pub fn iri(&self) -> String {
        crate::name::run_iri(&self.name, self.id)
    }

    /// The plain face: one fact per line.
    pub fn render(&self) -> String {
        let outcome = match &self.outcome {
            Outcome::Running => "running".to_string(),
            Outcome::Ok => "ok".to_string(),
            Outcome::Failed { kind, message } => format!("failed ({kind}): {message}"),
        };
        let mut text = format!(
            "{}\n  script:     {}\n  version:    {}\n  principal:  {}\n  started:    {}\n  \
             ended:      {}\n  outcome:    {outcome}\n  capability: {}\n",
            self.iri(),
            crate::name::script_iri(&self.name),
            self.version,
            self.principal,
            when(self.started),
            when(self.ended),
            if self.capability.is_empty() {
                "(none)".to_string()
            } else {
                self.capability
                    .iter()
                    .cloned()
                    .collect::<Vec<_>>()
                    .join(" ")
            },
        );
        if let Some(span) = self.trace_span {
            text.push_str(&format!("  trace span: {span}\n"));
        }
        if let Some(result) = &self.result {
            text.push_str(&format!(
                "  result{}:\n{result}\n",
                if self.truncated { " (truncated)" } else { "" }
            ));
        }
        text
    }
}

/// A timestamp for the plain faces: `xsd:dateTime` in UTC, or a note that the kernel had
/// no clock.
///
/// ```
/// use ikigai_script::model::when;
/// assert_eq!(when(Some(1_789_430_400_000)), "2026-09-15T00:00:00.000Z");
/// assert_eq!(when(Some(0)), "1970-01-01T00:00:00.000Z");
/// assert_eq!(when(None), "unstamped (the kernel has no clock)");
/// ```
pub fn when(millis: Option<u64>) -> String {
    let Some(millis) = millis else {
        return "unstamped (the kernel has no clock)".to_string();
    };
    let secs = millis / 1000;
    let (days, rem) = (secs / 86_400, secs % 86_400);
    // Howard Hinnant's civil-from-days, over days since 1970-01-01.
    let z = days as i64 + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let day = doy - (153 * mp + 2) / 5 + 1;
    let month = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = yoe + era * 400 + i64::from(month <= 2);
    format!(
        "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z",
        rem / 3600,
        rem % 3600 / 60,
        rem % 60,
        millis % 1000
    )
}

/// Cut `text` to at most `max` bytes on a character boundary; whether it was cut.
pub(crate) fn truncate(mut text: String, max: usize) -> (String, bool) {
    if text.len() <= max {
        return (text, false);
    }
    let mut end = max;
    while !text.is_char_boundary(end) {
        end -= 1;
    }
    text.truncate(end);
    (text, true)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn requires_and_language_are_part_of_the_content() {
        let a = Version {
            language: Language::Lisp,
            requires: BTreeSet::new(),
            budget: None,
            source: "(+ 1 2)".to_string(),
        };
        let mut b = a.clone();
        b.requires.insert("urn:cap:lisp".to_string());
        assert_ne!(a.digest(), b.digest());
    }

    /// A version declaring no budget keeps the digest it had before `budget` existed
    /// (ledger #1384): the value is pinned from the framing as 0.3.3 wrote it, so every
    /// version a host already stores is still found by its name.
    #[test]
    fn a_version_without_a_budget_keeps_its_digest() {
        let v = Version {
            language: Language::Lisp,
            requires: ["urn:cap:lisp".to_string()].into_iter().collect(),
            budget: None,
            source: "(+ 1 2)".to_string(),
        };
        assert_eq!(
            v.digest(),
            "sha256:ccea630c6cbeb36e3c3a57a9199934e32666e552550dd3c2d321171a493c9bf6"
        );
        let budgeted = Version {
            budget: Some(900),
            ..v.clone()
        };
        assert!(String::from_utf8(budgeted.canonical())
            .unwrap()
            .contains("requires urn:cap:lisp\nbudget 900\n\n(+ 1 2)"));
    }

    #[test]
    fn truncation_respects_characters() {
        let (text, cut) = truncate("héllo".to_string(), 2);
        assert_eq!((text.as_str(), cut), ("h", true));
        let (text, cut) = truncate("abc".to_string(), 3);
        assert_eq!((text.as_str(), cut), ("abc", false));
    }
}