Skip to main content

ikigai_script/
endpoints.rs

1//! The resources, as endpoints.
2//!
3//! Only two of them hold state — the script (its head and versions) and a run — and they
4//! hold it through the host's [`Backend`]. Everything else is composed: `…:result` and
5//! `…:runs` read `…:compiled` through the kernel and hand the program to the language's
6//! evaluator as a sub-request; `urn:script:eval` saves a draft by sinking to the script
7//! like any other writer.
8
9use std::collections::{BTreeMap, BTreeSet, HashMap};
10use std::sync::{Arc, Mutex};
11
12use async_trait::async_trait;
13use ikigai_core::{
14    ActionSpec, ArgRef, ArgSpec, Description, Endpoint, EndpointSpace, Error, Exact, Invocation,
15    Iri, ReprType, Representation, Request, Resolution, Result, Scope, Space, SpaceEntry, Topology,
16    UriTemplate, Verb,
17};
18use serde::{Deserialize, Serialize};
19
20use crate::authority::{
21    self, cap, cap_run, principal_of, Act, Ceiling, CeilingPolicy, CAP_ANY, CAP_DELETE, CAP_LISP,
22    CAP_READ, CAP_READ_PUBLIC, CAP_RUN, CAP_RUN_PUBLIC, CAP_WRITE,
23};
24use crate::backend::Backend;
25use crate::model::{
26    self, Event, Head, Language, Outcome, Run, State, Version, MAX_RECORDED_RESULT, SCHEMA,
27};
28use crate::name::{self, CATALOG_IRI, EVAL_IRI};
29use crate::plan;
30use crate::sparql::{self, Analysis, Form, Parameter, SparqlDoor, Value, CAP_READ_GRAPH};
31
32const PLAIN: &str = "text/plain";
33const JSON: &str = "application/json";
34const XSD_STRING: &str = "http://www.w3.org/2001/XMLSchema#string";
35const XSD_BOOLEAN: &str = "http://www.w3.org/2001/XMLSchema#boolean";
36const XSD_INTEGER: &str = "http://www.w3.org/2001/XMLSchema#integer";
37const TURTLE: &str = "text/turtle";
38/// The faces of a read: the source (or a summary) for people, the record for machines.
39const READ_FACES: [&str; 2] = [PLAIN, JSON];
40/// The faces of the catalog and a run record: those, and the graph (see [`crate::graph`]).
41const RECORD_FACES: [&str; 3] = [PLAIN, JSON, TURTLE];
42
43/// What a host decides when it mounts scripts: where they live and the ceiling it allows each
44/// one. Built with [`SpaceConfig::new`] and handed to [`space`].
45///
46/// Who a request comes from is not configured here: it is the principal the request's
47/// capability names (`urn:cap:principal:<iri>`), which the host's door mints with
48/// `Capability::with_principal` (see [`authority::principal_of`]).
49///
50/// There is no default backend and no default ceiling, on purpose: both are the host's
51/// decision, and a library that guessed either would be guessing about authority.
52#[derive(Clone)]
53#[non_exhaustive]
54pub struct SpaceConfig {
55    backend: Arc<dyn Backend>,
56    ceiling: CeilingPolicy,
57    sparql: Option<SparqlDoor>,
58    on_change: Option<ChangeHook>,
59    /// Each published SPARQL script's own endpoints (its contract), built once per head and
60    /// dropped by every publish or retire through this crate. `None`: the template's.
61    described: Arc<Mutex<HashMap<String, Option<PerScript>>>>,
62}
63
64/// What a host runs when a script's head changes through this crate: see
65/// [`SpaceConfig::on_change`].
66pub type ChangeHook = Arc<dyn Fn(&str) + Send + Sync>;
67
68impl SpaceConfig {
69    /// Scripts kept in `backend`, each run under the ceiling `ceiling` answers for it.
70    pub fn new(backend: Arc<dyn Backend>, ceiling: CeilingPolicy) -> SpaceConfig {
71        SpaceConfig {
72            backend,
73            ceiling,
74            sparql: None,
75            on_change: None,
76            described: Arc::new(Mutex::new(HashMap::new())),
77        }
78    }
79
80    /// Accept SPARQL scripts, evaluated through `door` (the store's graph-scoped doors).
81    /// Without it, publishing `language=sparql` is refused: which store a query runs
82    /// against is the host's decision, as the evaluator a Lisp script reaches is.
83    pub fn sparql(mut self, door: SparqlDoor) -> SpaceConfig {
84        self.sparql = Some(door);
85        self
86    }
87
88    /// Run `hook` with the script's name after every publish or retire through this crate.
89    ///
90    /// ★ **Wire it to `kernel.cut(ikigai_core::BINDINGS_THREAD)`.** A published SPARQL
91    /// script is its own entry in the catalog and the action manifold (`…:result` and
92    /// `…:runs` with ITS parameters as arguments), and the kernel caches every description
93    /// and Meta answer under `urn:kernel:bindings`, which it cannot know a publish changed.
94    /// The library holds no kernel and an endpoint may not cut that thread without
95    /// `urn:cap:kernel:cut`, so the host, which holds both, makes the cut. Unwired, a new
96    /// query is runnable at once but the catalog, MCP and the engine's argument routing
97    /// describe the old set until something else cuts the thread.
98    pub fn on_change(mut self, hook: ChangeHook) -> SpaceConfig {
99        self.on_change = Some(hook);
100        self
101    }
102
103    /// A script's head changed through this crate: forget its contract, tell the host.
104    fn changed(&self, name: &str) {
105        self.described
106            .lock()
107            .expect("the described-script memo")
108            .remove(name);
109        if let Some(hook) = &self.on_change {
110            hook(name);
111        }
112    }
113}
114
115/// Bind every script resource.
116///
117/// ⚠ **Bind order is resolution order** (`EndpointSpace` takes the first grammar that
118/// matches), and `urn:script:{name}`'s template captures the rest of an IRI, so the two
119/// exact names go first and the bare script last. A name cannot contain `:`, so
120/// `urn:script:x:compiled` can only be the compiled form of `x`.
121pub fn space(config: SpaceConfig) -> ScriptSpace {
122    let shared = Arc::new(config);
123    let template = |t: &str| UriTemplate::parse(t).expect("a constant template");
124    let inner = EndpointSpace::new()
125        .bind(Exact::new(EVAL_IRI), EvalEndpoint)
126        .bind(
127            Exact::new(CATALOG_IRI),
128            CatalogEndpoint {
129                shared: Arc::clone(&shared),
130            },
131        )
132        .bind(
133            template("urn:script:{name}:version:{digest}"),
134            VersionEndpoint {
135                shared: Arc::clone(&shared),
136            },
137        )
138        .bind(
139            template("urn:script:{name}:run:{id}"),
140            RunEndpoint {
141                shared: Arc::clone(&shared),
142            },
143        )
144        .bind(
145            template("urn:script:{name}:compiled"),
146            CompiledEndpoint {
147                shared: Arc::clone(&shared),
148            },
149        )
150        .bind(
151            template("urn:script:{name}:result"),
152            ResultEndpoint {
153                shared: Arc::clone(&shared),
154            },
155        )
156        .bind(
157            template("urn:script:{name}:runs"),
158            RunsEndpoint {
159                shared: Arc::clone(&shared),
160            },
161        )
162        .bind(
163            template("urn:script:{name}"),
164            ScriptEndpoint {
165                shared: Arc::clone(&shared),
166            },
167        );
168    ScriptSpace { inner, shared }
169}
170
171// ---------------------------------------------------------------------------------------
172// Gates
173// ---------------------------------------------------------------------------------------
174
175fn holds(inv: &Invocation<'_>, scope: &str) -> bool {
176    inv.capability.allows(scope)
177}
178
179/// Whether the caller may `act` on `name`: its exact grant or a namespace grant, and no
180/// exclusion naming it ([`authority::holds`]).
181fn may(inv: &Invocation<'_>, act: Act, name: &str) -> bool {
182    authority::holds(inv.capability, act, name)
183}
184
185/// Whether the caller reaches a PUBLIC script through `public` (a `…:public` grant), unless
186/// an exclusion it holds names the script.
187fn may_public(inv: &Invocation<'_>, act: Act, public: &str, name: &str) -> bool {
188    holds(inv, public) && !authority::excluded(inv.capability, act, name)
189}
190
191/// How a refusal says what a script grant can name.
192const GRANT_FORMS: &str = "A script grant names one script (`urn:cap:script:{act}:{name}`) or a \
193     namespace of them (`urn:cap:script:{act}:{namespace}-*`)";
194
195/// Public and published: what the `…:public` grants reach.
196fn is_public(head: &Head) -> bool {
197    head.public && head.state == State::Published
198}
199
200/// The head of `name`, if the caller may read it.
201///
202/// ★ No existence oracle: a caller without the script's own read grant is told `Denied`
203/// whether the script exists or not, unless it is public and they hold
204/// [`CAP_READ_PUBLIC`]. Only a caller who may read it learns that it is absent.
205fn readable_head(inv: &Invocation<'_>, shared: &SpaceConfig, name: &str) -> Result<Option<Head>> {
206    gated_head(inv, shared, name, &[(Act::Read, CAP_READ_PUBLIC)])
207}
208
209/// The head of `name` if the caller may do one of `acts` to it ([`may`]), or the script is
210/// public and they hold that act's public grant. Otherwise `Denied`, naming both.
211fn gated_head(
212    inv: &Invocation<'_>,
213    shared: &SpaceConfig,
214    name: &str,
215    acts: &[(Act, &str)],
216) -> Result<Option<Head>> {
217    if acts.iter().any(|(act, _)| may(inv, *act, name)) {
218        return shared.backend.head(name);
219    }
220    if let Ok(Some(head)) = shared.backend.head(name) {
221        if is_public(&head)
222            && acts
223                .iter()
224                .any(|(act, public)| may_public(inv, *act, public, name))
225        {
226            return Ok(Some(head));
227        }
228    }
229    Err(Error::Denied(format!(
230        "this capability holds none of {} — nor, for a public script, {}. {GRANT_FORMS}, and \
231         an exclusion (`…:-{{name}}`) takes one back out",
232        acts.iter()
233            .map(|(act, _)| cap(*act, name))
234            .collect::<Vec<_>>()
235            .join(", "),
236        acts.iter()
237            .map(|(_, public)| *public)
238            .collect::<Vec<_>>()
239            .join(", ")
240    )))
241}
242
243fn require(inv: &Invocation<'_>, act: Act, name: &str, doing: &str) -> Result<()> {
244    if may(inv, act, name) {
245        Ok(())
246    } else {
247        Err(Error::Denied(format!(
248            "{doing} needs `{}`, which this capability does not hold. {GRANT_FORMS}, and an \
249             exclusion (`…:-{{name}}`) takes one back out",
250            cap(act, name)
251        )))
252    }
253}
254
255fn found(head: Option<Head>, name: &str) -> Result<Head> {
256    head.ok_or_else(|| Error::NotFound(format!("no script is published at urn:script:{name}")))
257}
258
259// ---------------------------------------------------------------------------------------
260// Drafts: a version never published is its author's alone
261// ---------------------------------------------------------------------------------------
262
263/// Who may see one version of a script, beyond the read (or run) grant that gates it.
264///
265/// ★ **A draft is visible only to its author until it is published.** The author is the
266/// principal recorded when the draft was written, the principal the writer's CAPABILITY
267/// named ([`authority::principal_of`]), and the reader is its author when their capability
268/// `acts_as` that principal. Never an argument, so no caller can name itself the author.
269/// This only ever NARROWS what a grant reaches: seeing a draft needs the grant AND
270/// authorship, so it can give no one more than their capability.
271///
272/// Every answer is CACHEABLE, whatever the sight (ledger #1077). It is a function of the
273/// capability and the script's state alone: the kernel keys its cache on the capability,
274/// which carries the principal, so alice's cached draft is never bob's answer even when the
275/// rest of their capabilities are the same; and every answer hangs from the script's
276/// thread, which a publish or retire cuts. Before 0.2.0 the principal came from a host
277/// stamper the cache key could not see, and these answers could not be cached.
278#[derive(Clone, Copy, Debug, PartialEq, Eq)]
279enum Sight {
280    /// Published content, the caller's own draft, or a root caller.
281    Visible,
282    /// A version never published, and the caller is not its author: absent, told exactly
283    /// as a name nobody wrote is (`NotFound`, `false`), so its existence does not leak.
284    Hidden,
285}
286
287/// Whether `digest` was ever published under this head: the head published at it, or any
288/// change in its history did. Once published, always: history only grows.
289fn ever_published(head: &Head, digest: &str) -> bool {
290    (head.version == digest && head.state == State::Published)
291        || head
292            .history
293            .iter()
294            .any(|event| event.action == "publish" && event.version == digest)
295}
296
297/// What the caller may see of version `digest` of `head`'s script.
298///
299/// Root sees everything: it is the host's own authority, not a principal's, and holds the
300/// backend the draft is stored in (`acts_as` is true for root, and root also sees a draft
301/// whose author is nobody's identity).
302fn sight(inv: &Invocation<'_>, head: &Head, digest: &str) -> Sight {
303    if ever_published(head, digest) || inv.capability.is_root() {
304        return Sight::Visible;
305    }
306    let wrote_it = |author: &str| authority::is_identity(author) && inv.capability.acts_as(author);
307    let mine = (head.version == digest && wrote_it(&head.publisher))
308        || head
309            .history
310            .iter()
311            .any(|e| e.action == "draft" && e.version == digest && wrote_it(&e.principal));
312    if mine {
313        Sight::Visible
314    } else {
315        Sight::Hidden
316    }
317}
318
319/// `found`'s NotFound for a name the caller may read but cannot see: the same words as for
320/// a name nobody wrote, plus, for a capability naming no principal (which says nothing
321/// about any one name), why that caller can see no draft at all.
322fn absent(inv: &Invocation<'_>, name: &str) -> Error {
323    let mut message = format!("no script is published at urn:script:{name}");
324    if inv.capability.principal().is_none() && !inv.capability.is_root() {
325        message.push_str(
326            " (this request's capability names no principal (`urn:cap:principal:…`, minted \
327             by the host's door), so it cannot be shown to be a draft's author: a draft is \
328             visible to its author and root alone until it is published)",
329        );
330    }
331    Error::NotFound(message)
332}
333
334/// The head of `name`, from a gate's answer, if the caller may also SEE the version it
335/// points at.
336fn seen_head(inv: &Invocation<'_>, name: &str, gated: Option<Head>) -> Result<Head> {
337    let Some(head) = gated else {
338        return Err(absent(inv, name));
339    };
340    match sight(inv, &head, &head.version) {
341        Sight::Hidden => Err(absent(inv, name)),
342        Sight::Visible => Ok(head),
343    }
344}
345
346fn head_version(shared: &SpaceConfig, head: &Head) -> Result<Version> {
347    shared
348        .backend
349        .version(&head.name, &head.version)?
350        .ok_or_else(|| {
351            Error::Endpoint(format!(
352                "urn:script:{} points at version {}, which its backend does not hold",
353                head.name, head.version
354            ))
355        })
356}
357
358// ---------------------------------------------------------------------------------------
359// Arguments and faces
360// ---------------------------------------------------------------------------------------
361
362/// An optional inline argument; present-but-not-UTF-8 is an error, absent is `None`.
363fn optional<'a>(inv: &'a Invocation<'_>, name: &str) -> Result<Option<&'a str>> {
364    match inv.inline_str(name) {
365        Ok(value) => Ok(Some(value)),
366        Err(Error::MissingArgument(_)) => Ok(None),
367        Err(other) => Err(other),
368    }
369}
370
371fn parse_bool(name: &str, text: &str) -> Result<bool> {
372    match text.trim() {
373        "true" => Ok(true),
374        "false" => Ok(false),
375        other => Err(Error::InvalidArgument {
376            name: name.to_string(),
377            detail: format!("`{other}` is not `true` or `false`"),
378        }),
379    }
380}
381
382/// Which face was asked for: [`READ_FACES`]. One this resource cannot serve is refused,
383/// never substituted.
384fn wanted_face(inv: &Invocation<'_>) -> Result<&'static str> {
385    face_of(inv, &READ_FACES)
386}
387
388/// Which of `faces` was asked for (the first when none was).
389fn face_of(inv: &Invocation<'_>, faces: &[&'static str]) -> Result<&'static str> {
390    match optional(inv, "as")? {
391        None => Ok(faces[0]),
392        Some(asked) => {
393            let bare = asked.split(';').next().unwrap_or(asked).trim();
394            faces
395                .iter()
396                .find(|face| **face == bare)
397                .copied()
398                .ok_or_else(|| Error::InvalidArgument {
399                    name: "as".to_string(),
400                    detail: format!(
401                        "`{asked}` is not a face this resource serves; one of {}",
402                        faces.join(", ")
403                    ),
404                })
405        }
406    }
407}
408
409fn plain(text: impl Into<String>) -> Representation {
410    Representation::new(
411        ReprType::new(PLAIN).with_param("charset", "utf-8"),
412        text.into().into_bytes(),
413    )
414}
415
416fn json<T: Serialize>(value: &T) -> Result<Representation> {
417    let mut bytes = serde_json::to_vec_pretty(value)
418        .map_err(|e| Error::Endpoint(format!("could not serialize a record: {e}")))?;
419    bytes.push(b'\n');
420    Ok(Representation::new(ReprType::new(JSON), bytes))
421}
422
423fn iri(text: &str) -> Result<Iri> {
424    Iri::parse(text).map_err(|e| Error::Endpoint(format!("`{text}` is not an IRI: {e}")))
425}
426
427fn inline(text: &str) -> ArgRef {
428    ArgRef::Inline(text.as_bytes().to_vec())
429}
430
431fn name_arg() -> ArgSpec {
432    ArgSpec::new("name")
433        .summary(
434            "The script's name: one segment of lowercase letters, digits, `-` and `_` \
435             (`eval`, `catalog`, `public`, `outcome` and `principal` are reserved).",
436        )
437        .class(XSD_STRING)
438        .binding()
439}
440
441fn as_arg() -> ArgSpec {
442    ArgSpec::new("as")
443        .summary(
444            "The face: `text/plain` (for people) or `application/json` (the versioned \
445             record, `\"schema\": 1`). Any other is refused, never substituted.",
446        )
447        .class(XSD_STRING)
448        .one_of(READ_FACES)
449        .default_value(PLAIN)
450        .optional()
451}
452
453/// `as` for a record with a graph face.
454fn record_as_arg() -> ArgSpec {
455    ArgSpec::new("as")
456        .summary(
457            "The face: `text/plain` (for people), `application/json` (the versioned record, \
458             `\"schema\": 1`) or `text/turtle` (the graph: PROV-O and the shared \
459             vocabulary, no blank nodes). Any other is refused, never substituted.",
460        )
461        .class(XSD_STRING)
462        .one_of(RECORD_FACES)
463        .default_value(PLAIN)
464        .optional()
465}
466
467fn turtle(graph: crate::graph::Graph) -> Result<Representation> {
468    let bytes = graph
469        .turtle()
470        .map_err(|e| Error::Endpoint(format!("could not write the graph face: {e}")))?;
471    Ok(Representation::new(
472        ReprType::new(TURTLE).with_param("charset", "utf-8"),
473        bytes,
474    ))
475}
476
477fn data_arg(arg: &str, summary: &str) -> ArgSpec {
478    ArgSpec::new(arg)
479        .summary(summary)
480        .class(XSD_STRING)
481        .optional()
482}
483
484// ---------------------------------------------------------------------------------------
485// urn:script:{name} — the script (the head), and publishing
486// ---------------------------------------------------------------------------------------
487
488/// The script's JSON face: its head, flattened, with the version it points at.
489#[derive(Serialize)]
490struct ScriptDocument<'a> {
491    iri: String,
492    #[serde(flatten)]
493    head: &'a Head,
494    #[serde(rename = "versionIri")]
495    version_iri: String,
496    language: Language,
497    requires: &'a BTreeSet<String>,
498    source: &'a str,
499}
500
501struct ScriptEndpoint {
502    shared: Arc<SpaceConfig>,
503}
504
505#[async_trait]
506impl Endpoint for ScriptEndpoint {
507    async fn invoke(&self, inv: &Invocation<'_>) -> Result<Representation> {
508        let name = name::from_bindings(inv)?;
509        let shared = &self.shared;
510        match inv.request.verb {
511            Verb::Exists => {
512                let exists = match readable_head(inv, shared, &name)? {
513                    None => false,
514                    Some(head) => sight(inv, &head, &head.version) == Sight::Visible,
515                };
516                Ok(plain(if exists { "true\n" } else { "false\n" }).cacheable())
517            }
518            Verb::Source => {
519                let want = wanted_face(inv)?;
520                let head = seen_head(inv, &name, readable_head(inv, shared, &name)?)?;
521                let version = head_version(shared, &head)?;
522                let repr = if want == JSON {
523                    json(&ScriptDocument {
524                        iri: name::script_iri(&name),
525                        head: &head,
526                        version_iri: name::version_iri(&name, &head.version),
527                        language: version.language,
528                        requires: &version.requires,
529                        source: &version.source,
530                    })?
531                } else {
532                    plain(version.source)
533                };
534                Ok(repr.cacheable())
535            }
536            Verb::Sink => publish(inv, shared, &name).await,
537            Verb::Delete => retire(inv, shared, &name),
538            other => Err(unsupported("script", other)),
539        }
540    }
541
542    fn name(&self) -> &str {
543        "script"
544    }
545
546    fn describe(&self) -> Description {
547        Description::new("script")
548            .title("A script")
549            .summary(
550                "A script as a resource: fetch its source without running it, publish or \
551                 replace it (every write is a new content-addressed version), or retire it.",
552            )
553            .verb(Verb::Meta)
554            .action(
555                ActionSpec::new(Verb::Source)
556                    .summary(
557                        "The script, WITHOUT running it: its source (`text/plain`), or its head \
558                         record (`application/json`): state, public flag, version, what it \
559                         declares and what its publisher held. Needs \
560                         `urn:cap:script:read:{name}`, or `urn:cap:script:read:public` for a \
561                         public published script.",
562                    )
563                    .input(name_arg())
564                    .input(as_arg())
565                    .output(PLAIN)
566                    .output(JSON)
567                    .requires(CAP_READ),
568            )
569            .action(
570                ActionSpec::new(Verb::Exists)
571                    .summary("Whether the script exists (to a caller who may read it).")
572                    .input(name_arg())
573                    .output(PLAIN)
574                    .requires(CAP_READ),
575            )
576            .action(
577                ActionSpec::new(Verb::Sink)
578                    .summary(
579                        "Publish or replace the script; answers the new version's IRI. The \
580                         declared `requires` (plus the language's own capability) must all \
581                         be held by the publisher, or the publish is refused: a script never \
582                         runs with more than its publisher held. Needs \
583                         `urn:cap:script:write:{name}`.",
584                    )
585                    .input(name_arg())
586                    .input(
587                        ArgSpec::new("content")
588                            .summary("The source text.")
589                            .class(XSD_STRING),
590                    )
591                    .input(
592                        ArgSpec::new("language")
593                            .summary(
594                                "The script's language: `lisp`, `sparql` (a query or update, \
595                                 when the host mounts a SPARQL door), or `plan` (an \
596                                 ik:Process graph, when the host binds the plan doors).",
597                            )
598                            .class(XSD_STRING)
599                            .one_of(Language::ALL.map(Language::as_str))
600                            .default_value("lisp")
601                            .optional(),
602                    )
603                    .input(
604                        ArgSpec::new("requires")
605                            .summary(
606                                "Whitespace-separated `urn:cap:` grants the script needs to \
607                                 run. Lisp: the language's capability is added; exact grants \
608                                 only, no wildcards, no exclusions. SPARQL: DERIVED from the \
609                                 graphs the text names; a plan: DERIVED from its steps' \
610                                 contracts. For both, omit it: one that says anything else \
611                                 is refused, naming the derived set.",
612                            )
613                            .class(XSD_STRING)
614                            .optional(),
615                    )
616                    .input(
617                        ArgSpec::new("public")
618                            .summary(
619                                "Whether holders of `urn:cap:script:run:public` (a host's \
620                                 anonymous principal) may run it and holders of \
621                                 `urn:cap:script:read:public` read it.",
622                            )
623                            .class(XSD_BOOLEAN)
624                            .one_of(["true", "false"])
625                            .default_value("false")
626                            .optional(),
627                    )
628                    .input(
629                        ArgSpec::new("state")
630                            .summary(
631                                "`published` (runnable) or `draft` (saved, not runnable, \
632                                 and visible only to its author until published). To \
633                                 retire, Delete.",
634                            )
635                            .class(XSD_STRING)
636                            .one_of(["published", "draft"])
637                            .default_value("published")
638                            .optional(),
639                    )
640                    .input(
641                        ArgSpec::new("if-version")
642                            .summary(
643                                "Write only if the head is still this version (`none`: only \
644                                 if the script does not exist yet); otherwise `Conflict`.",
645                            )
646                            .class(XSD_STRING)
647                            .optional(),
648                    )
649                    .output(PLAIN)
650                    .requires(CAP_WRITE),
651            )
652            .action(
653                ActionSpec::new(Verb::Delete)
654                    .summary(
655                        "Retire the script: it stays readable and its versions fetchable, but \
656                         it never runs again until republished. Needs \
657                         `urn:cap:script:delete:{name}`.",
658                    )
659                    .input(name_arg())
660                    .output(PLAIN)
661                    .requires(CAP_DELETE),
662            )
663    }
664}
665
666async fn publish(inv: &Invocation<'_>, shared: &SpaceConfig, name: &str) -> Result<Representation> {
667    require(inv, Act::Write, name, "publishing a script")?;
668    let source = inv.inline_str("content")?;
669    let language = optional(inv, "language")?
670        .map(Language::parse)
671        .transpose()?
672        .unwrap_or(Language::Lisp);
673    let requires = match language {
674        Language::Lisp => {
675            let mut requires = optional(inv, "requires")?
676                .map(authority::parse_requires)
677                .transpose()?
678                .unwrap_or_default();
679            requires.insert(CAP_LISP.to_string());
680            requires
681        }
682        Language::Sparql => derived_requires(inv, shared, source)?,
683        Language::Plan => {
684            // Validated by the host's validator first, so a malformed plan is refused
685            // naming the shape it broke; then read for what this crate decides itself;
686            // then its authority derived from its steps' contracts.
687            plan::check_bound(source)?;
688            plan::validate(inv, source).await?;
689            plan::analyze(source)?;
690            plan::derive(inv, source, optional(inv, "requires")?).await?
691        }
692    };
693    let public = optional(inv, "public")?
694        .map(|v| parse_bool("public", v))
695        .transpose()?
696        .unwrap_or(false);
697    let state = match optional(inv, "state")?.map(str::trim) {
698        None | Some("published") => State::Published,
699        Some("draft") => State::Draft,
700        Some(other) => {
701            return Err(Error::InvalidArgument {
702                name: "state".to_string(),
703                detail: format!(
704                    "`{other}` is not `published` or `draft`; to retire a script, Delete it"
705                ),
706            })
707        }
708    };
709    // ★ No elevation: refused here, before anything is written, if the publisher does not
710    // hold every scope the script declares.
711    let grant = authority::grant_at_publish(inv.capability, &requires)?;
712
713    let version = Version {
714        language,
715        requires,
716        source: source.to_string(),
717    };
718    let digest = version.digest();
719    let current = shared.backend.head(name)?;
720    if let Some(expected) = optional(inv, "if-version")? {
721        let at = current.as_ref().map_or("none", |h| h.version.as_str());
722        if at != expected.trim() {
723            return Err(Error::Conflict(format!(
724                "urn:script:{name} is at {at}, not {}; read it again and retry",
725                expected.trim()
726            )));
727        }
728    }
729    shared.backend.put_version(name, &version)?;
730
731    let principal = principal_of(inv.capability);
732    let at = inv.now().map(|t| t.as_millis());
733    let mut history = current
734        .as_ref()
735        .map(|h| h.history.clone())
736        .unwrap_or_default();
737    history.push(Event {
738        action: if state == State::Draft {
739            "draft"
740        } else {
741            "publish"
742        }
743        .to_string(),
744        version: digest.clone(),
745        state,
746        public,
747        principal: principal.clone(),
748        at,
749    });
750    let head = Head {
751        schema: SCHEMA,
752        name: name.to_string(),
753        version: digest.clone(),
754        state,
755        public,
756        granted: grant.granted,
757        exclusions: grant.exclusions,
758        publisher: principal,
759        updated: at,
760        history,
761    };
762    shared.backend.swap_head(name, current.as_ref(), &head)?;
763    shared.changed(name);
764    Ok(plain(format!("{}\n", name::version_iri(name, &digest))))
765}
766
767/// A SPARQL script's authority: DERIVED from the graphs its text names, never declared.
768/// A `requires=` is accepted only when it says exactly the same thing, and refused naming
769/// the derived set when it does not, so an author can neither under- nor over-declare.
770fn derived_requires(
771    inv: &Invocation<'_>,
772    shared: &SpaceConfig,
773    source: &str,
774) -> Result<BTreeSet<String>> {
775    let door = door(shared).map_err(|_| Error::InvalidArgument {
776        name: "language".to_string(),
777        detail: "this host takes no SPARQL scripts: it mounts no SPARQL door".to_string(),
778    })?;
779    let derived = sparql::analyze(source, door)?.requires();
780    if let Some(said) = optional(inv, "requires")? {
781        let said: BTreeSet<String> = said.split_whitespace().map(str::to_string).collect();
782        if said != derived {
783            return Err(Error::InvalidArgument {
784                name: "requires".to_string(),
785                detail: format!(
786                    "a SPARQL script's authority is derived from the graphs its text names, \
787                     not declared, and this one derives {}; the `requires` given says {}. \
788                     Omit `requires`",
789                    listed(&derived),
790                    listed(&said)
791                ),
792            });
793        }
794    }
795    Ok(derived)
796}
797
798fn listed(scopes: &BTreeSet<String>) -> String {
799    if scopes.is_empty() {
800        "nothing".to_string()
801    } else {
802        scopes.iter().cloned().collect::<Vec<_>>().join(" ")
803    }
804}
805
806fn door(shared: &SpaceConfig) -> Result<&SparqlDoor> {
807    shared.sparql.as_ref().ok_or_else(|| {
808        Error::Endpoint(
809            "this host mounts no SPARQL door (`SpaceConfig::sparql`), so it cannot run a \
810             SPARQL script"
811                .to_string(),
812        )
813    })
814}
815
816fn retire(inv: &Invocation<'_>, shared: &SpaceConfig, name: &str) -> Result<Representation> {
817    require(inv, Act::Delete, name, "retiring a script")?;
818    let current = found(shared.backend.head(name)?, name)?;
819    let iri = name::script_iri(name);
820    if current.state == State::Retired {
821        return Ok(plain(format!("{iri} was already retired\n")));
822    }
823    let at = inv.now().map(|t| t.as_millis());
824    let mut head = current.clone();
825    head.state = State::Retired;
826    head.updated = at;
827    head.history.push(Event {
828        action: "retire".to_string(),
829        version: current.version.clone(),
830        state: State::Retired,
831        public: current.public,
832        principal: principal_of(inv.capability),
833        at,
834    });
835    shared.backend.swap_head(name, Some(&current), &head)?;
836    shared.changed(name);
837    Ok(plain(format!("retired {iri}\n")))
838}
839
840// ---------------------------------------------------------------------------------------
841// urn:script:{name}:version:{digest}
842// ---------------------------------------------------------------------------------------
843
844struct VersionEndpoint {
845    shared: Arc<SpaceConfig>,
846}
847
848#[async_trait]
849impl Endpoint for VersionEndpoint {
850    async fn invoke(&self, inv: &Invocation<'_>) -> Result<Representation> {
851        let name = name::from_bindings(inv)?;
852        let digest = inv
853            .bindings
854            .get("digest")
855            .ok_or_else(|| Error::Endpoint("no `digest` captured".to_string()))?
856            .to_string();
857        // ★ Hung from the SCRIPT's thread, which every publish and retire cuts, and named
858        // FIRST, so every answer below carries it: a success (ledger #1076) and a NotFound
859        // alike (ledger #1079). Everything this answer says is the script's state, not the
860        // version's: whether that content has been written under the name (a version named
861        // by its content can be asked for before anyone publishes it), whether the caller may
862        // see it (a draft is its author's until it is published), and whether the caller may
863        // read the name at all (a public script's version stops being readable through the
864        // public grant when it is retired). The kernel hangs an answer from its OWN name,
865        // which no write here ever targets, so without this a cached `false`, or a cached
866        // fallback over a NotFound, outlived the publish that ended the absence. Caching the
867        // negative is kept, not dropped: it is a backend read per ask, and an uncacheable
868        // `Exists` would make every composite over it uncacheable. The kernel carries the
869        // thread on a miss only (NotFound, Unresolved); a refusal stays never-cached.
870        inv.depends_on(name::script_iri(&name));
871        let head = readable_head(inv, &self.shared, &name)?;
872        let version = self.shared.backend.version(&name, &digest);
873        // A version that exists is seen as its head's history says: one never published is
874        // its author's alone. One with no head at all (a write that lost its race) was never
875        // published either.
876        let seen = match (&version, &head) {
877            (Ok(Some(_)), Some(head)) => sight(inv, head, &digest),
878            (Ok(Some(_)), None) if !inv.capability.is_root() => Sight::Hidden,
879            _ => Sight::Visible,
880        };
881        let no_such = || Error::NotFound(format!("urn:script:{name} has no version {digest}"));
882        match inv.request.verb {
883            Verb::Exists => {
884                let exists = match version {
885                    Ok(v) => v.is_some() && seen != Sight::Hidden,
886                    Err(Error::InvalidArgument { .. }) => false,
887                    Err(other) => return Err(other),
888                };
889                Ok(plain(if exists { "true\n" } else { "false\n" }).cacheable())
890            }
891            Verb::Source => {
892                let want = wanted_face(inv)?;
893                let version = version?.ok_or_else(no_such)?;
894                if seen == Sight::Hidden {
895                    return Err(no_such());
896                }
897                let repr = if want == JSON {
898                    json(&version.document(&name))?
899                } else {
900                    plain(version.source)
901                };
902                Ok(repr.cacheable())
903            }
904            other => Err(unsupported("script-version", other)),
905        }
906    }
907
908    fn name(&self) -> &str {
909        "script-version"
910    }
911
912    fn describe(&self) -> Description {
913        let digest = || {
914            ArgSpec::new("digest")
915                .summary("The version's digest: `sha256:` and 64 hex digits over its content.")
916                .class(XSD_STRING)
917                .binding()
918        };
919        Description::new("script-version")
920            .title("One version of a script")
921            .summary(
922                "An immutable version, named by the sha256 of its content (language, declared \
923                 capability, source). Republishing moves the head; every version stays \
924                 fetchable here.",
925            )
926            .verb(Verb::Meta)
927            .action(
928                ActionSpec::new(Verb::Source)
929                    .summary(
930                        "The version's source (`text/plain`) or its record (`application/json`).",
931                    )
932                    .input(name_arg())
933                    .input(digest())
934                    .input(as_arg())
935                    .output(PLAIN)
936                    .output(JSON)
937                    .requires(CAP_READ),
938            )
939            .action(
940                ActionSpec::new(Verb::Exists)
941                    .summary("Whether the script has this version.")
942                    .input(name_arg())
943                    .input(digest())
944                    .output(PLAIN)
945                    .requires(CAP_READ),
946            )
947    }
948}
949
950// ---------------------------------------------------------------------------------------
951// urn:script:{name}:compiled — the prepared form
952// ---------------------------------------------------------------------------------------
953
954/// The compiled form: everything a run needs, in one cacheable resource hung from the
955/// script's thread. For Lisp the "compilation" is preparation — the evaluator offers no
956/// separate compile step to cache — so this is the program and the authority it runs
957/// under, bound to the version they came from. For SPARQL it adds what the parsed text
958/// says: its form, its parameters and the graphs it names ([`Analysis`]).
959#[derive(Clone, Debug, Serialize, Deserialize)]
960pub struct Prepared {
961    /// [`SCHEMA`].
962    pub schema: u32,
963    /// The script.
964    pub name: String,
965    /// `urn:script:{name}:compiled`.
966    pub iri: String,
967    /// The version prepared.
968    pub version: String,
969    /// Its language.
970    pub language: Language,
971    /// The door a run issues to: `urn:lisp:eval`, or the host's SPARQL door for this form.
972    pub evaluator: String,
973    /// The program.
974    pub program: String,
975    /// What it declares (for SPARQL: what its text derives).
976    pub requires: BTreeSet<String>,
977    /// What its publisher held of that.
978    pub granted: BTreeSet<String>,
979    /// The publisher's exclusions.
980    pub exclusions: BTreeSet<String>,
981    /// Whether it is public.
982    pub public: bool,
983    /// Its state.
984    pub state: State,
985    /// For a SPARQL script: its form, parameters and graphs, read from the parsed text.
986    #[serde(default, skip_serializing_if = "Option::is_none")]
987    pub sparql: Option<Analysis>,
988    /// For a plan: its process, its steps' verbs (read or write) and its parameters.
989    #[serde(default, skip_serializing_if = "Option::is_none")]
990    pub plan: Option<plan::Analysis>,
991}
992
993struct CompiledEndpoint {
994    shared: Arc<SpaceConfig>,
995}
996
997#[async_trait]
998impl Endpoint for CompiledEndpoint {
999    async fn invoke(&self, inv: &Invocation<'_>) -> Result<Representation> {
1000        if inv.request.verb != Verb::Source {
1001            return Err(unsupported("script-compiled", inv.request.verb));
1002        }
1003        let name = name::from_bindings(inv)?;
1004        // ★ Hung from the SCRIPT's thread, which every publish and retire cuts (the kernel
1005        // cuts the thread named after a Sink's or Delete's target), and named FIRST so a
1006        // NotFound carries it as well as a success (ledger #1079): without it a cached
1007        // compiled form would outlive the version it was prepared from, and a cached fallback
1008        // over "nothing is published here" (or "this draft is not yours") would outlive the
1009        // publish that ended it. A run as a read reaches this form by sub-request, so its
1010        // answers, and its misses, inherit the thread.
1011        inv.depends_on(name::script_iri(&name));
1012        // Readable by a reader or a runner: a run reads its program here. A draft's program
1013        // is its author's alone, so a run of someone else's draft finds nothing to run.
1014        let gated = gated_head(
1015            inv,
1016            &self.shared,
1017            &name,
1018            &[(Act::Read, CAP_READ_PUBLIC), (Act::Run, CAP_RUN_PUBLIC)],
1019        )?;
1020        let head = seen_head(inv, &name, gated)?;
1021        let version = head_version(&self.shared, &head)?;
1022        let (evaluator, analysis, plan_analysis) = match version.language {
1023            Language::Lisp => (LISP_EVAL.to_string(), None, None),
1024            Language::Sparql => {
1025                let door = door(&self.shared)?;
1026                let analysis = sparql::analyze(&version.source, door)?;
1027                (door.query_iri(analysis.form), Some(analysis), None)
1028            }
1029            Language::Plan => (
1030                plan::EVAL.to_string(),
1031                None,
1032                Some(plan::analyze(&version.source)?),
1033            ),
1034        };
1035        let prepared = Prepared {
1036            schema: SCHEMA,
1037            iri: name::part_iri(&name, "compiled"),
1038            version: head.version.clone(),
1039            language: version.language,
1040            evaluator,
1041            program: version.source,
1042            requires: version.requires,
1043            granted: head.granted,
1044            exclusions: head.exclusions,
1045            public: head.public,
1046            state: head.state,
1047            sparql: analysis,
1048            plan: plan_analysis,
1049            name: name.clone(),
1050        };
1051        Ok(json(&prepared)?.cacheable())
1052    }
1053
1054    fn name(&self) -> &str {
1055        "script-compiled"
1056    }
1057
1058    fn describe(&self) -> Description {
1059        Description::new("script-compiled")
1060            .title("A script's compiled form")
1061            .summary(
1062                "The head version prepared for its evaluator, with the authority it runs \
1063                 under (and, for SPARQL, its form, parameters and graphs; for a plan, its \
1064                 steps' verbs and its parameters): cached, and cut \
1065                 whenever the script is republished or retired. Readable by a holder of the \
1066                 script's read OR run grant (a run reads its program here).",
1067            )
1068            .verb(Verb::Meta)
1069            .action(
1070                ActionSpec::new(Verb::Source)
1071                    .summary("The prepared form, as JSON.")
1072                    .input(name_arg())
1073                    .output(JSON)
1074                    .requires(CAP_ANY),
1075            )
1076    }
1077}
1078
1079// ---------------------------------------------------------------------------------------
1080// Running: …:result (a read) and …:runs (a write)
1081// ---------------------------------------------------------------------------------------
1082
1083const LISP_EVAL: &str = "urn:lisp:eval";
1084
1085/// Read the compiled form through the kernel, check the run gate and the state, and
1086/// compute what the run may keep of the runner's capability (and under which ceiling).
1087async fn prepare_run(
1088    inv: &Invocation<'_>,
1089    shared: &SpaceConfig,
1090    name: &str,
1091) -> Result<(Prepared, BTreeSet<String>, Ceiling)> {
1092    // Composed, not reached into: the run is a reader of its own compiled form, so the
1093    // compiled form's thread (and the script's, through it) lands on the result.
1094    let compiled = inv
1095        .issue(Request::new(
1096            Verb::Source,
1097            iri(&name::part_iri(name, "compiled"))?,
1098        ))
1099        .await?;
1100    let prepared: Prepared = serde_json::from_slice(&compiled.bytes).map_err(|e| {
1101        Error::Endpoint(format!(
1102            "urn:script:{name}:compiled did not answer a prepared form: {e}"
1103        ))
1104    })?;
1105    if prepared.name != name {
1106        return Err(Error::Endpoint(format!(
1107            "urn:script:{name}:compiled answered for `{}`",
1108            prepared.name
1109        )));
1110    }
1111    let public = prepared.public && prepared.state == State::Published;
1112    let may_run =
1113        may(inv, Act::Run, name) || (public && may_public(inv, Act::Run, CAP_RUN_PUBLIC, name));
1114    if !may_run {
1115        return Err(Error::Denied(format!(
1116            "running urn:script:{name} needs `{}` or a namespace grant covering it{}. \
1117             {GRANT_FORMS}, and an exclusion (`…:-{{name}}`) takes one back out",
1118            cap_run(name),
1119            if prepared.public {
1120                format!(" (or `{CAP_RUN_PUBLIC}`, since it is public)")
1121            } else {
1122                " — it is not public".to_string()
1123            }
1124        )));
1125    }
1126    match prepared.state {
1127        State::Published => {}
1128        State::Draft => {
1129            return Err(Error::Conflict(format!(
1130                "urn:script:{name} is a draft; publish it (`state=published`) to run it, or \
1131                 try the code at urn:script:eval"
1132            )))
1133        }
1134        State::Retired => {
1135            return Err(Error::Conflict(format!(
1136                "urn:script:{name} is retired; publish it again to run it"
1137            )))
1138        }
1139    }
1140    let ceiling = (shared.ceiling)(name);
1141    let keep = authority::effective(
1142        &prepared.requires,
1143        &prepared.granted,
1144        &prepared.exclusions,
1145        &ceiling,
1146    );
1147    Ok((prepared, keep, ceiling))
1148}
1149
1150/// The Lisp evaluator sub-request: `in` is the program, `data` what it reads with `(input)`.
1151fn lisp_request(program: &str, data: Option<&str>) -> Result<Request> {
1152    let mut request = Request::new(Verb::Source, iri(LISP_EVAL)?).with_arg("in", inline(program));
1153    if let Some(data) = data {
1154        request = request.with_arg("data", inline(data));
1155    }
1156    Ok(request)
1157}
1158
1159/// `run_args`: the description of the run's input, shared by both run doors.
1160const DATA_SUMMARY: &str = "Optional data the script reads with `(input)` — data, never code.";
1161
1162/// Which door a run came through.
1163#[derive(Clone, Copy, PartialEq, Eq)]
1164enum Door {
1165    /// `…:result`: a read, answered with the script's value.
1166    Result,
1167    /// `…:runs`: a write, recorded.
1168    Runs,
1169}
1170
1171/// What a run issues, and exactly the scopes it issues it under (before the runner's own
1172/// capability is attenuated to them).
1173struct Planned {
1174    request: Request,
1175    keep: BTreeSet<String>,
1176}
1177
1178/// The run's sub-request, for whichever language the script is in.
1179async fn prepare_request(
1180    inv: &Invocation<'_>,
1181    shared: &SpaceConfig,
1182    prepared: &Prepared,
1183    keep: BTreeSet<String>,
1184    ceiling: &Ceiling,
1185    through: Door,
1186) -> Result<Planned> {
1187    match prepared.language {
1188        Language::Lisp => {
1189            let data = optional(
1190                inv,
1191                match through {
1192                    Door::Result => "data",
1193                    Door::Runs => "content",
1194                },
1195            )?;
1196            Ok(Planned {
1197                request: lisp_request(&prepared.program, data)?,
1198                keep,
1199            })
1200        }
1201        Language::Sparql => plan_sparql(inv, shared, prepared, keep, ceiling, through).await,
1202        Language::Plan => plan_eval_request(inv, prepared, keep, ceiling, through),
1203    }
1204}
1205
1206/// A plan run: refuse a write through the read door, take the plan's parameters, turn a
1207/// root publisher's derived families into exact grants, and address `urn:plan:eval`.
1208///
1209/// The plan's steps then run as `urn:plan:eval`'s sub-requests under exactly the narrowed
1210/// capability, and each meets its own target's floor there: a step the run may not take is
1211/// refused by the kernel at that step, typed, and arrives here unchanged.
1212fn plan_eval_request(
1213    inv: &Invocation<'_>,
1214    prepared: &Prepared,
1215    keep: BTreeSet<String>,
1216    ceiling: &Ceiling,
1217    through: Door,
1218) -> Result<Planned> {
1219    let name = &prepared.name;
1220    let analysis = prepared.plan.as_ref().ok_or_else(|| {
1221        Error::Endpoint(format!(
1222            "urn:script:{name}:compiled carries no plan analysis"
1223        ))
1224    })?;
1225    if through == Door::Result && analysis.mutates() {
1226        let writers: Vec<String> = analysis
1227            .steps
1228            .iter()
1229            .filter(|s| s.mutates())
1230            .map(|s| format!("<{}> ({} <{}>)", s.iri, s.verb, s.resolves))
1231            .collect();
1232        return Err(Error::InvalidArgument {
1233            name: "name".to_string(),
1234            detail: format!(
1235                "urn:script:{name} is a plan that writes ({}), so it is not a read: run it with \
1236                 a Sink to urn:script:{name}:runs",
1237                writers.join(", ")
1238            ),
1239        });
1240    }
1241    let declared: Vec<(&str, bool)> = analysis
1242        .parameters
1243        .iter()
1244        .map(|p| (p.name.as_str(), p.must_be_given()))
1245        .collect();
1246    let values = given_parameters(inv, name, &declared, through)?;
1247    let face = optional(inv, "as")?;
1248    Ok(Planned {
1249        request: plan::eval_request(&prepared.program, &values, face),
1250        keep: plan::expand_families(keep, inv.capability, ceiling),
1251    })
1252}
1253
1254/// A SPARQL run: bind the parameters into the parsed query, work out its dataset and the
1255/// exact store grants it needs, and address the host's store door for its form.
1256///
1257/// ★ **The dataset is never wider than the authority.** The graphs the text fixes need
1258/// their grants in the run's capability (the store refuses the whole read, naming the
1259/// grant, when one is missing). A graph only the run decides (`GRAPH ?g`, or a parameter
1260/// naming a graph) is admitted only under the derived family, and only when the
1261/// publisher held it (or was root), the host's ceiling allows it AND the runner holds it:
1262/// that set is "the caller's readable union", computed here per run and never more.
1263async fn plan_sparql(
1264    inv: &Invocation<'_>,
1265    shared: &SpaceConfig,
1266    prepared: &Prepared,
1267    mut keep: BTreeSet<String>,
1268    ceiling: &Ceiling,
1269    through: Door,
1270) -> Result<Planned> {
1271    let name = &prepared.name;
1272    let door = door(shared)?;
1273    let analysis = prepared.sparql.as_ref().ok_or_else(|| {
1274        Error::Endpoint(format!(
1275            "urn:script:{name}:compiled carries no SPARQL analysis"
1276        ))
1277    })?;
1278    if through == Door::Result && !analysis.form.is_read() {
1279        return Err(Error::InvalidArgument {
1280            name: "name".to_string(),
1281            detail: format!(
1282                "urn:script:{name} is a SPARQL UPDATE, which is a write: run it with a Sink to \
1283                 urn:script:{name}:runs"
1284            ),
1285        });
1286    }
1287    let values = parameter_values(inv, name, &analysis.parameters, through)?;
1288    let face = sparql_face(inv, analysis.form)?;
1289    let bound = sparql::bind(&prepared.program, door, &values)?;
1290
1291    let runner = inv.capability;
1292    // The root publisher's marker: expanded below into exact grants, never attenuated as
1293    // it stands (attenuation keeps grants by exact name).
1294    let root_marker = keep.remove(CAP_READ_GRAPH);
1295    let family = prepared.requires.contains(CAP_READ_GRAPH);
1296    let by_family = |scope: &str, keep: &BTreeSet<String>| {
1297        family
1298            && runner.allows(scope)
1299            && if root_marker {
1300                ceiling.allows(scope)
1301            } else {
1302                keep.contains(scope)
1303            }
1304    };
1305
1306    if bound.form == Form::Update {
1307        // An update's one graph is fixed by its text (a parameter cannot name it), so its
1308        // grants are exactly the derived ones, already in `keep`.
1309        let graph = bound.graphs.iter().next().cloned().ok_or_else(|| {
1310            Error::Endpoint(format!("urn:script:{name} names no graph to update"))
1311        })?;
1312        for scope in &prepared.requires {
1313            may_use(name, &graph, scope, &keep, runner)?;
1314        }
1315        let request = Request::new(Verb::Sink, iri(&door.query_iri(Form::Update))?)
1316            .with_arg("content", inline(&bound.text))
1317            .with_arg("graph", inline(&graph));
1318        return Ok(Planned { request, keep });
1319    }
1320
1321    let mut extra = BTreeSet::new();
1322    for graph in &bound.graphs {
1323        let scope = sparql::cap_read_graph(graph);
1324        if !keep.contains(&scope) && by_family(&scope, &keep) {
1325            extra.insert(scope);
1326        }
1327    }
1328    let mut dataset = bound.graphs.clone();
1329    if bound.any_graph {
1330        if !family {
1331            return Err(Error::Endpoint(format!(
1332                "urn:script:{name} reads a variable graph but its record derives no \
1333                 `{CAP_READ_GRAPH}`; republish it"
1334            )));
1335        }
1336        let under = |scopes: &mut dyn Iterator<Item = &String>| -> BTreeSet<String> {
1337            scopes
1338                .filter_map(|s| s.strip_prefix(sparql::READ_GRAPH_PREFIX))
1339                .filter(|g| !g.starts_with('-') && !g.ends_with('*'))
1340                .map(str::to_string)
1341                .collect()
1342        };
1343        let candidates = if !root_marker {
1344            under(&mut keep.iter())
1345        } else if let Some(held) = runner.scopes() {
1346            under(&mut held.iter())
1347        } else {
1348            // Root ran a script a root published: the readable union is every graph the
1349            // store holds, listed by the store itself under the broad read the runner holds.
1350            let listing = inv
1351                .issue_attenuated(
1352                    Request::new(Verb::Source, iri(&door.graphs_iri())?),
1353                    [sparql::CAP_STORE_READ.to_string()],
1354                )
1355                .await?;
1356            String::from_utf8_lossy(&listing.bytes)
1357                .lines()
1358                .map(str::trim)
1359                .filter(|l| !l.is_empty())
1360                .map(str::to_string)
1361                .collect()
1362        };
1363        for graph in candidates {
1364            let scope = sparql::cap_read_graph(&graph);
1365            if keep.contains(&scope) && runner.allows(&scope) || by_family(&scope, &keep) {
1366                extra.insert(scope);
1367                dataset.insert(graph);
1368            }
1369        }
1370    }
1371    if dataset.is_empty() {
1372        return Err(Error::Denied(format!(
1373            "urn:script:{name} reads the caller's readable graphs, and this run may read none: \
1374             it needs `{}` grants the publisher held, the host allows and the runner holds",
1375            sparql::READ_GRAPH_PREFIX
1376        )));
1377    }
1378    keep.extend(extra);
1379    for graph in &dataset {
1380        may_use(name, graph, &sparql::cap_read_graph(graph), &keep, runner)?;
1381    }
1382    let graphs = dataset.into_iter().collect::<Vec<_>>().join(" ");
1383    let request = Request::new(Verb::Source, iri(&door.query_iri(bound.form))?)
1384        .with_arg("query", inline(&bound.text))
1385        .with_arg("graph", inline(&graphs))
1386        .with_arg("as", inline(face));
1387    Ok(Planned { request, keep })
1388}
1389
1390/// Refused HERE, naming the exact grant and who withheld it, rather than by the store's
1391/// door: the kernel's floor there sees only the family a run holds, so its refusal would
1392/// name `urn:cap:store:read:graph:*` and not the graph.
1393fn may_use(
1394    name: &str,
1395    graph: &str,
1396    scope: &str,
1397    keep: &BTreeSet<String>,
1398    runner: &ikigai_core::Capability,
1399) -> Result<()> {
1400    if !runner.allows(scope) {
1401        return Err(Error::Denied(format!(
1402            "running urn:script:{name} reads or writes <{graph}>, which needs `{scope}`, and the \
1403             runner does not hold it"
1404        )));
1405    }
1406    if !keep.contains(scope) {
1407        return Err(Error::Denied(format!(
1408            "running urn:script:{name} reads or writes <{graph}>, which needs `{scope}`, and \
1409             this script may not have it: its publisher did not hold it, or the host's ceiling \
1410             for it does not allow it"
1411        )));
1412    }
1413    Ok(())
1414}
1415
1416/// The face a SPARQL run answers in: `as=`, one its form can serve, or the form's default.
1417/// Refused, never substituted.
1418fn sparql_face(inv: &Invocation<'_>, form: Form) -> Result<&'static str> {
1419    let faces = form.faces();
1420    match optional(inv, "as")? {
1421        None => Ok(faces[0]),
1422        Some(asked) => {
1423            let bare = asked.split(';').next().unwrap_or(asked).trim();
1424            faces
1425                .iter()
1426                .find(|f| **f == bare)
1427                .copied()
1428                .ok_or_else(|| Error::InvalidArgument {
1429                    name: "as".to_string(),
1430                    detail: format!(
1431                        "`{asked}` is not a face a SPARQL {} answers in; one of {}",
1432                        form.as_str().to_uppercase(),
1433                        faces.join(", ")
1434                    ),
1435                })
1436        }
1437    }
1438}
1439
1440/// The run's parameter values, each checked against its declared type.
1441///
1442/// What was given is [`given_parameters`]'s; a parameter not given takes its default, and
1443/// one with neither stays unbound.
1444fn parameter_values(
1445    inv: &Invocation<'_>,
1446    name: &str,
1447    parameters: &[Parameter],
1448    through: Door,
1449) -> Result<BTreeMap<String, Value>> {
1450    let declared: Vec<(&str, bool)> = parameters
1451        .iter()
1452        .map(|p| (p.name.as_str(), p.required && p.default.is_none()))
1453        .collect();
1454    let mut given = given_parameters(inv, name, &declared, through)?;
1455    let mut values = BTreeMap::new();
1456    for parameter in parameters {
1457        if let Some(lexical) = given
1458            .remove(&parameter.name)
1459            .or_else(|| parameter.default.clone())
1460        {
1461            values.insert(parameter.name.clone(), parameter.value(&lexical)?);
1462        }
1463    }
1464    Ok(values)
1465}
1466
1467/// The argument names a TRANSPORT owns, which a run never reads as a script's parameters
1468/// (ledger #1173).
1469///
1470/// `ikigai-web` stamps a write with its provenance, `received`, `client` and `principal`,
1471/// read off the connection, and with the body's `content-type`; `ikigai-quic` stamps
1472/// `principal` on every verb. Each is the door's statement about the request, never the
1473/// caller's, and none is an input to a script: who a request is from reaches a run in its
1474/// CAPABILITY (`Capability::with_principal`, read with [`authority::principal_of`]), which
1475/// is what every run and publish records.
1476///
1477/// So the doors of this crate ignore these names wherever a script's parameters are read
1478/// (`…:result` and `…:runs`, for a query and a plan), instead of refusing them as arguments
1479/// the script does not declare — which made every run for effects through the HTTP door a
1480/// `400` — and no script may declare a parameter by one of them (refused at publish; see
1481/// [`sparql::RESERVED_PARAMETERS`] and [`plan::RESERVED_PARAMETERS`]). A value a CALLER
1482/// supplies under one of them (where a door passes it through) is ignored the same way, so
1483/// it can neither reach a script nor stand in for the principal.
1484///
1485/// ```
1486/// use ikigai_script::TRANSPORT_ARGUMENTS;
1487/// for owned in TRANSPORT_ARGUMENTS {
1488///     assert!(ikigai_script::sparql::RESERVED_PARAMETERS.contains(&owned), "{owned}");
1489///     assert!(ikigai_script::plan::RESERVED_PARAMETERS.contains(&owned), "{owned}");
1490/// }
1491/// ```
1492pub const TRANSPORT_ARGUMENTS: [&str; 4] = ["received", "client", "principal", "content-type"];
1493
1494/// The parameters a run was GIVEN, as text, for a script that declares `declared` (each
1495/// parameter's name, and whether a run must give it).
1496///
1497/// Named arguments, or (through `…:runs`) a JSON object piped as `content`. A missing
1498/// parameter a run must give is `MissingArgument`; a parameter given both ways and an
1499/// argument the script does not declare are `InvalidArgument`: a binding the script does not
1500/// mention is refused, never ignored, so a filter you thought was applied can never silently
1501/// not be. Refused here, before a run is recorded: nothing ran.
1502///
1503/// The one exception is [`TRANSPORT_ARGUMENTS`]: a door's own stamps, ignored, never bound.
1504/// `declared` never holds one: the parameters are read again from the source each time the
1505/// compiled form is prepared, and that read refuses a reserved name, so a script stored
1506/// before they were reserved that declares one fails there, naming it, and never runs with
1507/// the parameter silently unbound.
1508fn given_parameters(
1509    inv: &Invocation<'_>,
1510    name: &str,
1511    declared: &[(&str, bool)],
1512    through: Door,
1513) -> Result<BTreeMap<String, String>> {
1514    let listed = || {
1515        if declared.is_empty() {
1516            "it declares none".to_string()
1517        } else {
1518            format!(
1519                "its parameters are {}",
1520                declared
1521                    .iter()
1522                    .map(|(p, _)| *p)
1523                    .collect::<Vec<_>>()
1524                    .join(", ")
1525            )
1526        }
1527    };
1528    for arg in inv.request.args.keys() {
1529        let known = arg == "as"
1530            || TRANSPORT_ARGUMENTS.contains(&arg.as_str())
1531            || (through == Door::Runs && arg == "content")
1532            || declared.iter().any(|(p, _)| p == arg);
1533        if !known {
1534            return Err(Error::InvalidArgument {
1535                name: arg.clone(),
1536                detail: format!("is not a parameter of urn:script:{name}; {}", listed()),
1537            });
1538        }
1539    }
1540    let mut piped: BTreeMap<String, String> = BTreeMap::new();
1541    if through == Door::Runs {
1542        // An empty body is no parameters: a bare `sink …:runs` sends one.
1543        if let Some(content) = optional(inv, "content")?.filter(|c| !c.trim().is_empty()) {
1544            let object: serde_json::Map<String, serde_json::Value> = serde_json::from_str(content)
1545                .map_err(|e| Error::InvalidArgument {
1546                    name: "content".to_string(),
1547                    detail: format!(
1548                        "a script's piped content is its parameters as one JSON object ({e})"
1549                    ),
1550                })?;
1551            for (key, value) in object {
1552                let lexical = match value {
1553                    serde_json::Value::String(s) => s,
1554                    serde_json::Value::Number(n) => n.to_string(),
1555                    serde_json::Value::Bool(b) => b.to_string(),
1556                    other => {
1557                        return Err(Error::InvalidArgument {
1558                            name: "content".to_string(),
1559                            detail: format!(
1560                                "`{key}` is {other}; a parameter's value is a string, a number \
1561                                 or a boolean"
1562                            ),
1563                        })
1564                    }
1565                };
1566                piped.insert(key, lexical);
1567            }
1568        }
1569    }
1570    let mut given = BTreeMap::new();
1571    for (parameter, must) in declared {
1572        let named = optional(inv, parameter)?;
1573        let lexical = match (named, piped.remove(*parameter)) {
1574            (Some(_), Some(_)) => {
1575                return Err(Error::InvalidArgument {
1576                    name: parameter.to_string(),
1577                    detail: "is given both by name and in the piped content".to_string(),
1578                })
1579            }
1580            (Some(value), None) => Some(value.to_string()),
1581            (None, Some(value)) => Some(value),
1582            (None, None) => None,
1583        };
1584        match lexical {
1585            Some(lexical) => {
1586                given.insert(parameter.to_string(), lexical);
1587            }
1588            None if *must => return Err(Error::MissingArgument(parameter.to_string())),
1589            None => {}
1590        }
1591    }
1592    if let Some(stray) = piped.keys().next() {
1593        return Err(Error::InvalidArgument {
1594            name: "content".to_string(),
1595            detail: format!(
1596                "`{stray}` is not a parameter of urn:script:{name}; {}",
1597                listed()
1598            ),
1599        });
1600    }
1601    Ok(given)
1602}
1603
1604struct ResultEndpoint {
1605    shared: Arc<SpaceConfig>,
1606}
1607
1608#[async_trait]
1609impl Endpoint for ResultEndpoint {
1610    async fn invoke(&self, inv: &Invocation<'_>) -> Result<Representation> {
1611        if inv.request.verb != Verb::Source {
1612            return Err(unsupported("script-result", inv.request.verb));
1613        }
1614        let name = name::from_bindings(inv)?;
1615        let (prepared, keep, ceiling) = prepare_run(inv, &self.shared, &name).await?;
1616        let planned =
1617            prepare_request(inv, &self.shared, &prepared, keep, &ceiling, Door::Result).await?;
1618        // ★ The ONLY authority a run gets: the runner's own capability, narrowed. There is
1619        // no form that widens, so a script cannot reach past its runner whatever it says.
1620        let answer = inv.issue_attenuated(planned.request, planned.keep).await?;
1621        // Cacheable as far as this endpoint is concerned; the kernel folds in the
1622        // evaluator's expiry (a Lisp program is uncacheable unless it opts in with
1623        // `(cacheable …)`; a query is as cacheable as the store's answer, which hangs from
1624        // the store's write threads) and the compiled form's threads. The authority thread
1625        // is the host's to cut when it changes this script's ceiling.
1626        Ok(Representation::new(answer.repr_type, answer.bytes)
1627            .cacheable()
1628            .depends_on(name::authority_thread(&name)))
1629    }
1630
1631    fn name(&self) -> &str {
1632        "script-result"
1633    }
1634
1635    fn describe(&self) -> Description {
1636        Description::new("script-result")
1637            .title("A script's result")
1638            .summary(
1639                "Run the script as a READ and answer its value. It runs under the runner's \
1640                 capability narrowed to what the script declares, its publisher held and \
1641                 the host allows it — never more. Cacheable exactly as far as the script's \
1642                 own sub-requests are (a Lisp program opts in with `(cacheable …)`), and \
1643                 recomputed when the script is republished. No run record: a cached answer \
1644                 runs nothing; record a run with `…:runs`. A published SPARQL script is \
1645                 its own entry, with its parameters as arguments.",
1646            )
1647            .verb(Verb::Meta)
1648            .action(
1649                ActionSpec::new(Verb::Source)
1650                    .summary("The script's answer.")
1651                    .input(name_arg())
1652                    .input(data_arg("data", DATA_SUMMARY))
1653                    .output(PLAIN)
1654                    .requires(CAP_RUN)
1655                    .requires(CAP_LISP),
1656            )
1657    }
1658}
1659
1660struct RunsEndpoint {
1661    shared: Arc<SpaceConfig>,
1662}
1663
1664#[async_trait]
1665impl Endpoint for RunsEndpoint {
1666    async fn invoke(&self, inv: &Invocation<'_>) -> Result<Representation> {
1667        if inv.request.verb != Verb::Sink {
1668            return Err(unsupported("script-runs", inv.request.verb));
1669        }
1670        let name = name::from_bindings(inv)?;
1671        let shared = &self.shared;
1672        let (prepared, keep, ceiling) = prepare_run(inv, shared, &name).await?;
1673        // A caller's mistake (a missing or ill-typed parameter) is refused here, before a
1674        // run is recorded: nothing ran.
1675        let planned = prepare_request(inv, shared, &prepared, keep, &ceiling, Door::Runs).await?;
1676        let runs_as = inv.capability.attenuate(planned.keep.iter().cloned());
1677        let mut run = Run {
1678            schema: SCHEMA,
1679            name: name.clone(),
1680            id: 0,
1681            version: prepared.version.clone(),
1682            principal: principal_of(inv.capability),
1683            capability: runs_as.scopes().cloned().unwrap_or_default(),
1684            started: inv.now().map(|t| t.as_millis()),
1685            ended: None,
1686            outcome: Outcome::Running,
1687            result: None,
1688            truncated: false,
1689            trace_span: inv.trace_span(),
1690        };
1691        run.id = shared.backend.start_run(&name, &run)?;
1692        let answer = inv.issue_attenuated(planned.request, planned.keep).await;
1693        run.ended = inv.now().map(|t| t.as_millis());
1694        match answer {
1695            Ok(repr) => {
1696                let (text, truncated) = model::truncate(
1697                    String::from_utf8_lossy(&repr.bytes).into_owned(),
1698                    MAX_RECORDED_RESULT,
1699                );
1700                run.outcome = Outcome::Ok;
1701                run.result = Some(text);
1702                run.truncated = truncated;
1703                shared.backend.finish_run(&name, &run)?;
1704                Ok(plain(format!("{}\n", run.iri())))
1705            }
1706            Err(error) => {
1707                run.outcome = Outcome::Failed {
1708                    kind: kind(&error).to_string(),
1709                    message: error.to_string(),
1710                };
1711                shared.backend.finish_run(&name, &run)?;
1712                Err(annotate(error, &run.iri()))
1713            }
1714        }
1715    }
1716
1717    fn name(&self) -> &str {
1718        "script-runs"
1719    }
1720
1721    fn describe(&self) -> Description {
1722        Description::new("script-runs")
1723            .title("A script's runs")
1724            .summary(
1725                "Run the script for its EFFECTS and record the run: who (the principal \
1726                 the capability names), which version, under exactly what capability, when, and the \
1727                 outcome. Answers the run's IRI; a run that fails is recorded too, and its \
1728                 error names the record. A published SPARQL script is its own entry, with \
1729                 its parameters as arguments.",
1730            )
1731            .verb(Verb::Meta)
1732            .action(
1733                ActionSpec::new(Verb::Sink)
1734                    .summary("Run the script and record the run.")
1735                    .input(name_arg())
1736                    .input(data_arg("content", DATA_SUMMARY))
1737                    .output(PLAIN)
1738                    .requires(CAP_RUN)
1739                    .requires(CAP_LISP),
1740            )
1741    }
1742}
1743
1744// ---------------------------------------------------------------------------------------
1745// A published SPARQL script's own contract, and the space that offers it
1746// ---------------------------------------------------------------------------------------
1747
1748/// A SPARQL script's or a plan's own endpoints, `…:result` and `…:runs`, each the
1749/// template's endpoint behind the script's OWN description.
1750#[derive(Clone)]
1751struct PerScript {
1752    result: Arc<dyn Endpoint>,
1753    runs: Arc<dyn Endpoint>,
1754    /// Whether its `…:result` is a read it offers (a query, not an update).
1755    reads: bool,
1756    /// Whether it is published, and so listed in the catalog. A draft of content that was
1757    /// published before, or a retired script, still answers under its own contract (its run
1758    /// is refused for its state, not for a language capability it never needed), but is not
1759    /// offered. A draft never published has no contract of its own (see `build`).
1760    listed: bool,
1761}
1762
1763/// The template's endpoint, behind one script's contract.
1764///
1765/// ★ **Why a script is its own entry.** A description is the contract the engine routes
1766/// arguments by, selection matches on, MCP projects and the Emacs aliases are generated
1767/// from, and the kernel answers it per ENDPOINT, never per IRI. A query's or a plan's
1768/// parameters are real arguments only if they are in a description, so each gets one. And
1769/// the template's `requires` is Lisp's (`urn:cap:lisp`): a query or a plan behind it would be
1770/// refused at the floor for a language grant it never needs, so a plan with no parameters
1771/// still gets its own.
1772/// It is built once per head (the kernel memoizes floors by this allocation) and dropped
1773/// by the next publish or retire.
1774struct Described {
1775    inner: Arc<dyn Endpoint>,
1776    id: String,
1777    description: Description,
1778}
1779
1780#[async_trait]
1781impl Endpoint for Described {
1782    async fn invoke(&self, inv: &Invocation<'_>) -> Result<Representation> {
1783        self.inner.invoke(inv).await
1784    }
1785
1786    fn name(&self) -> &str {
1787        &self.id
1788    }
1789
1790    fn describe(&self) -> Description {
1791        self.description.clone()
1792    }
1793}
1794
1795/// The script resources as a space: [`space`]'s bindings, plus each published SPARQL
1796/// script and plan as its own `…:result` and `…:runs` entry, carrying its parameters.
1797pub struct ScriptSpace {
1798    inner: EndpointSpace,
1799    shared: Arc<SpaceConfig>,
1800}
1801
1802impl ScriptSpace {
1803    /// The script's own endpoints, when it is a SPARQL script this host can run or a plan.
1804    ///
1805    /// A Lisp script has none (the template's contract IS its contract), but finding that
1806    /// out costs one head and version read per name, remembered until the next publish.
1807    fn per_script(&self, name: &str) -> Option<PerScript> {
1808        let shared = &self.shared;
1809        if let Some(known) = shared
1810            .described
1811            .lock()
1812            .expect("the described-script memo")
1813            .get(name)
1814        {
1815            return known.clone();
1816        }
1817        let built = self.build(name);
1818        // ⚠ Remember only scripts that exist: a name nobody published is a miss every
1819        // time, never an entry, so resolving arbitrary names cannot grow this map.
1820        if built.is_some() || matches!(shared.backend.head(name), Ok(Some(_))) {
1821            shared
1822                .described
1823                .lock()
1824                .expect("the described-script memo")
1825                .insert(name.to_string(), built.clone());
1826        }
1827        built
1828    }
1829
1830    fn build(&self, name: &str) -> Option<PerScript> {
1831        let shared = &self.shared;
1832        let head = shared.backend.head(name).ok()??;
1833        // ★ A draft never published wears the TEMPLATE's contract. Meta is answered from the
1834        // description to anyone who can reach the door (the kernel's, before any endpoint
1835        // runs, so it cannot ask who is calling), and a script's own contract is made of its
1836        // text: its parameters, its leading comment, the graphs it names. Its own entry would
1837        // publish all three, and that the draft exists. Its run is still refused (for its
1838        // state, to its author; as absent, to everyone else), now at the template's floor.
1839        if !ever_published(&head, &head.version) {
1840            return None;
1841        }
1842        let version = shared.backend.version(name, &head.version).ok()??;
1843        match version.language {
1844            Language::Lisp => None,
1845            Language::Sparql => self.build_sparql(name, &head, &version),
1846            Language::Plan => self.build_plan(name, &head, &version),
1847        }
1848    }
1849
1850    /// A per-script endpoint: the template's, behind `description`.
1851    fn described(
1852        &self,
1853        inner: Arc<dyn Endpoint>,
1854        id: String,
1855        description: Description,
1856    ) -> Arc<dyn Endpoint> {
1857        Arc::new(Described {
1858            inner,
1859            id,
1860            description,
1861        }) as Arc<dyn Endpoint>
1862    }
1863
1864    fn result_endpoint(&self) -> Arc<dyn Endpoint> {
1865        Arc::new(ResultEndpoint {
1866            shared: Arc::clone(&self.shared),
1867        })
1868    }
1869
1870    fn runs_endpoint(&self) -> Arc<dyn Endpoint> {
1871        Arc::new(RunsEndpoint {
1872            shared: Arc::clone(&self.shared),
1873        })
1874    }
1875
1876    fn build_sparql(&self, name: &str, head: &Head, version: &Version) -> Option<PerScript> {
1877        let door = self.shared.sparql.as_ref()?;
1878        let analysis = sparql::analyze(&version.source, door).ok()?;
1879        let about = about(&version.source);
1880        let inputs: Vec<ArgSpec> = analysis
1881            .parameters
1882            .iter()
1883            .map(|p| {
1884                let mut arg = ArgSpec::new(p.name.clone())
1885                    .summary(
1886                        p.summary
1887                            .clone()
1888                            .unwrap_or_else(|| format!("The value of ?{} in the query.", p.name)),
1889                    )
1890                    .class(p.kind.iri().to_string());
1891                if let Some(default) = &p.default {
1892                    arg = arg.default_value(default.clone()).optional();
1893                } else if !p.required {
1894                    arg = arg.optional();
1895                }
1896                arg
1897            })
1898            .collect();
1899        let params = |spec: ActionSpec| contracted(spec, &inputs, name, head, version);
1900        let form = analysis.form;
1901        let faces = form.faces();
1902        let as_arg = || {
1903            ArgSpec::new("as")
1904                .summary(format!(
1905                    "The face: one of {}. Any other is refused, never substituted.",
1906                    faces.join(", ")
1907                ))
1908                .class(XSD_STRING)
1909                .one_of(faces.iter().copied())
1910                .default_value(faces[0])
1911                .optional()
1912        };
1913        let id = format!("script-{name}-result");
1914        let description = if form.is_read() {
1915            let mut spec = params(ActionSpec::new(Verb::Source))
1916                .summary(format!("Run the query {name} and answer its result."))
1917                .input(as_arg());
1918            for face in faces {
1919                spec = spec.output(*face);
1920            }
1921            Description::new(id.clone())
1922                .title(format!("{name}: a SPARQL {}", form.as_str().to_uppercase()))
1923                .summary(format!(
1924                    "{about}Runs as a READ under the runner's capability narrowed to the \
1925                     graphs the query names; cached as the store's answer is, and \
1926                     recomputed after a write to the store or a republish."
1927                ))
1928                .verb(Verb::Meta)
1929                .action(spec)
1930        } else {
1931            // An update is never a read: no action is offered here, and a Source that
1932            // arrives anyway is refused by the run, naming `…:runs`.
1933            Description::new(id.clone())
1934                .title(format!("{name}: a SPARQL UPDATE (run it at …:runs)"))
1935                .summary(format!(
1936                    "{about}A write: run it with a Sink to urn:script:{name}:runs."
1937                ))
1938                .verb(Verb::Meta)
1939        };
1940        let result = self.described(self.result_endpoint(), id, description);
1941        let id = format!("script-{name}-runs");
1942        let mut spec = params(ActionSpec::new(Verb::Sink))
1943            .summary(format!(
1944                "Run {name} for its effects and record the run; answers the run's IRI."
1945            ))
1946            .input(piped_parameters_arg())
1947            .output(PLAIN);
1948        if form.is_read() {
1949            spec = spec.input(as_arg());
1950        }
1951        let runs = self.described(
1952            self.runs_endpoint(),
1953            id.clone(),
1954            Description::new(id)
1955                .title(format!("{name}: runs"))
1956                .summary(format!(
1957                    "{about}Each run is recorded: who, which version, under exactly what \
1958                     capability, when, and the outcome."
1959                ))
1960                .verb(Verb::Meta)
1961                .action(spec),
1962        );
1963        Some(PerScript {
1964            result,
1965            runs,
1966            reads: form.is_read(),
1967            listed: head.state == State::Published,
1968        })
1969    }
1970
1971    /// A plan's own contract: its declared parameters as arguments, and the capability
1972    /// derived from its steps as what the floor checks.
1973    fn build_plan(&self, name: &str, head: &Head, version: &Version) -> Option<PerScript> {
1974        let analysis = plan::analyze(&version.source).ok()?;
1975        let about = about(&version.source);
1976        let inputs: Vec<ArgSpec> = analysis
1977            .parameters
1978            .iter()
1979            .map(|p| {
1980                let mut arg = ArgSpec::new(p.name.clone())
1981                    .summary(
1982                        p.summary
1983                            .clone()
1984                            .unwrap_or_else(|| format!("The plan's parameter `{}`.", p.name)),
1985                    )
1986                    .class(p.class.clone().unwrap_or_else(|| XSD_STRING.to_string()));
1987                if let Some(default) = &p.default {
1988                    arg = arg.default_value(default.clone()).optional();
1989                } else if !p.required {
1990                    arg = arg.optional();
1991                }
1992                arg
1993            })
1994            .collect();
1995        let params = |spec: ActionSpec| contracted(spec, &inputs, name, head, version);
1996        // A plan's answer is its result step's own representation, so no list of faces can
1997        // be declared in advance: `as` is passed to the evaluator, which transrepts or
1998        // refuses.
1999        let as_arg = || {
2000            ArgSpec::new("as")
2001                .summary(
2002                    "The face of the plan's result: when its result step served another \
2003                     media type it is transrepted, and refused when nothing converts it.",
2004                )
2005                .class(XSD_STRING)
2006                .optional()
2007        };
2008        let reads = !analysis.mutates();
2009        let id = format!("script-{name}-result");
2010        let description = if reads {
2011            Description::new(id.clone())
2012                .title(format!("{name}: a plan"))
2013                .summary(format!(
2014                    "{about}Runs as a READ (every step reads) under the runner's capability \
2015                     narrowed to what the plan's steps require; as cacheable as its least \
2016                     cacheable step, and recomputed after a republish."
2017                ))
2018                .verb(Verb::Meta)
2019                .action(
2020                    params(ActionSpec::new(Verb::Source))
2021                        .summary(format!("Run the plan {name} and answer its result."))
2022                        .input(as_arg())
2023                        .output(PLAIN),
2024                )
2025        } else {
2026            // A plan with a Sink or Delete step is never a read: no action is offered here,
2027            // and a Source that arrives anyway is refused by the run, naming `…:runs`.
2028            Description::new(id.clone())
2029                .title(format!("{name}: a plan that writes (run it at …:runs)"))
2030                .summary(format!(
2031                    "{about}A write: run it with a Sink to urn:script:{name}:runs."
2032                ))
2033                .verb(Verb::Meta)
2034        };
2035        let result = self.described(self.result_endpoint(), id, description);
2036        let id = format!("script-{name}-runs");
2037        let runs = self.described(
2038            self.runs_endpoint(),
2039            id.clone(),
2040            Description::new(id)
2041                .title(format!("{name}: runs"))
2042                .summary(format!(
2043                    "{about}Each run is recorded: who, which version, under exactly what \
2044                     capability, when, and the outcome."
2045                ))
2046                .verb(Verb::Meta)
2047                .action(
2048                    params(ActionSpec::new(Verb::Sink))
2049                        .summary(format!(
2050                            "Run the plan {name} and record the run; answers the run's IRI."
2051                        ))
2052                        .input(piped_parameters_arg())
2053                        .input(as_arg())
2054                        .output(PLAIN),
2055                ),
2056        );
2057        Some(PerScript {
2058            result,
2059            runs,
2060            reads,
2061            listed: head.state == State::Published,
2062        })
2063    }
2064}
2065
2066/// `spec` with a script's own `inputs`, the run gate and every scope its version requires.
2067///
2068/// The run gate, as the kernel can check it before the endpoint is entered: the script's own
2069/// grant, or the family of its top-level namespace when it is in one, so a namespace grant
2070/// is not refused at the floor ([`authority::run_floor`]); for a public one, the family of
2071/// every run grant (its own grant OR the public one, which `requires` cannot say any other
2072/// way: it is all-of). The exact rule is checked inside, by [`prepare_run`].
2073fn contracted(
2074    mut spec: ActionSpec,
2075    inputs: &[ArgSpec],
2076    name: &str,
2077    head: &Head,
2078    version: &Version,
2079) -> ActionSpec {
2080    for input in inputs {
2081        spec = spec.input(input.clone());
2082    }
2083    spec = spec.requires(if head.public {
2084        CAP_RUN.to_string()
2085    } else {
2086        authority::run_floor(name)
2087    });
2088    for scope in &version.requires {
2089        spec = spec.requires(scope.clone());
2090    }
2091    spec
2092}
2093
2094/// `…:runs`' piped body, for a script with parameters.
2095fn piped_parameters_arg() -> ArgSpec {
2096    ArgSpec::new("content")
2097        .summary(
2098            "The parameters as one JSON object, for a pipe (a parameter given both here and \
2099             by name is refused).",
2100        )
2101        .class(XSD_STRING)
2102        .optional()
2103}
2104
2105/// A script's own words for the catalog: its leading comment lines that declare nothing.
2106fn about(source: &str) -> String {
2107    let mut lines = Vec::new();
2108    for line in source.lines() {
2109        let trimmed = line.trim();
2110        let Some(body) = trimmed.strip_prefix('#') else {
2111            if trimmed.is_empty() {
2112                continue;
2113            }
2114            break;
2115        };
2116        let body = body.trim();
2117        if !body.is_empty() && !body.starts_with("@param") {
2118            lines.push(body);
2119        }
2120    }
2121    if lines.is_empty() {
2122        String::new()
2123    } else {
2124        format!("{} ", lines.join(" "))
2125    }
2126}
2127
2128impl Space for ScriptSpace {
2129    fn resolve(&self, request: &Request, scope: &Scope) -> Resolution {
2130        let resolution = self.inner.resolve(request, scope);
2131        let (name, part) = match &resolution {
2132            Resolution::Hit(hit) => {
2133                let part = match hit.endpoint.name() {
2134                    "script-result" => Door::Result,
2135                    "script-runs" => Door::Runs,
2136                    _ => return resolution,
2137                };
2138                match hit.bindings.get("name") {
2139                    Some(name) if name::validate(name).is_ok() => (name.to_string(), part),
2140                    _ => return resolution,
2141                }
2142            }
2143            Resolution::Miss => return resolution,
2144        };
2145        match self.per_script(&name) {
2146            Some(per) => resolution.map_endpoint(|_| match part {
2147                Door::Result => per.result,
2148                Door::Runs => per.runs,
2149            }),
2150            None => resolution,
2151        }
2152    }
2153
2154    fn entries(&self) -> Option<Vec<SpaceEntry>> {
2155        let mut entries = self.inner.entries().unwrap_or_default();
2156        for name in self.shared.backend.names().unwrap_or_default() {
2157            let Some(per) = self.per_script(&name).filter(|per| per.listed) else {
2158                continue;
2159            };
2160            if per.reads {
2161                entries.push(SpaceEntry::new(
2162                    name::part_iri(&name, "result"),
2163                    per.result.name(),
2164                ));
2165            }
2166            entries.push(SpaceEntry::new(
2167                name::part_iri(&name, "runs"),
2168                per.runs.name(),
2169            ));
2170        }
2171        Some(entries)
2172    }
2173
2174    fn id(&self) -> Option<Iri> {
2175        self.inner.id()
2176    }
2177
2178    fn topology(&self) -> Topology {
2179        self.inner.topology()
2180    }
2181}
2182
2183/// An error's kind, as a run record spells it.
2184fn kind(error: &Error) -> &'static str {
2185    match error {
2186        Error::Unresolved(_) => "unresolved",
2187        Error::MissingArgument(_) => "missing-argument",
2188        Error::InvalidArgument { .. } => "invalid-argument",
2189        Error::Endpoint(_) => "endpoint",
2190        Error::Denied(_) => "denied",
2191        Error::NotFound(_) => "not-found",
2192        Error::Conflict(_) => "conflict",
2193        Error::Timeout(_) => "timeout",
2194        Error::Unavailable(_) => "unavailable",
2195        _ => "other",
2196    }
2197}
2198
2199/// The same error, of the same type, naming the run record it was written to.
2200fn annotate(error: Error, run: &str) -> Error {
2201    let note = |message: String| format!("{message} (run recorded at {run})");
2202    match error {
2203        Error::Endpoint(m) => Error::Endpoint(note(m)),
2204        Error::Denied(m) => Error::Denied(note(m)),
2205        Error::NotFound(m) => Error::NotFound(note(m)),
2206        Error::Conflict(m) => Error::Conflict(note(m)),
2207        Error::Timeout(m) => Error::Timeout(note(m)),
2208        Error::Unavailable(m) => Error::Unavailable(note(m)),
2209        Error::InvalidArgument { name, detail } => Error::InvalidArgument {
2210            name,
2211            detail: note(detail),
2212        },
2213        other => other,
2214    }
2215}
2216
2217// ---------------------------------------------------------------------------------------
2218// urn:script:{name}:run:{id}
2219// ---------------------------------------------------------------------------------------
2220
2221struct RunEndpoint {
2222    shared: Arc<SpaceConfig>,
2223}
2224
2225#[async_trait]
2226impl Endpoint for RunEndpoint {
2227    async fn invoke(&self, inv: &Invocation<'_>) -> Result<Representation> {
2228        let name = name::from_bindings(inv)?;
2229        // ★ Hung from the script's RUNS thread, which every run cuts (the kernel cuts the
2230        // thread named after a Sink's target, `urn:script:{name}:runs`), and named FIRST so a
2231        // NotFound carries it as well as a success (ledger #1079's shape): whether run `{id}`
2232        // exists is the state a run writes, never anything written through this record's own
2233        // name, so without it a cached fallback over "no run {id}" outlived the run that
2234        // recorded it. A FAILED run is recorded too, and cuts it as well: the kernel cuts a
2235        // Sink's target whenever the endpoint ran (ikigai-core 0.1.95; pinned in
2236        // `tests/lifecycle.rs`).
2237        inv.depends_on(name::part_iri(&name, "runs"));
2238        // A run record says who ran what: readable by the script's readers and its named
2239        // runners, never through the public grants.
2240        if !may(inv, Act::Read, &name) && !may(inv, Act::Run, &name) {
2241            return Err(Error::Denied(format!(
2242                "a run record of urn:script:{name} needs `{}` or `{}`. {GRANT_FORMS}",
2243                cap(Act::Read, &name),
2244                cap(Act::Run, &name)
2245            )));
2246        }
2247        let id_text = inv
2248            .bindings
2249            .get("id")
2250            .ok_or_else(|| Error::Endpoint("no `id` captured".to_string()))?;
2251        let id = id_text.parse::<u64>().map_err(|_| Error::InvalidArgument {
2252            name: "id".to_string(),
2253            detail: format!("`{id_text}` is not a run number"),
2254        });
2255        let run = match id {
2256            Ok(id) => self.shared.backend.run(&name, id)?,
2257            Err(_) if inv.request.verb == Verb::Exists => None,
2258            Err(e) => return Err(e),
2259        };
2260        match inv.request.verb {
2261            Verb::Exists => Ok(plain(if run.is_some() { "true\n" } else { "false\n" })),
2262            Verb::Source => {
2263                let want = face_of(inv, &RECORD_FACES)?;
2264                let run = run.ok_or_else(|| {
2265                    Error::NotFound(format!("urn:script:{name} has no run {id_text}"))
2266                })?;
2267                let finished = run.outcome != Outcome::Running;
2268                let repr = match want {
2269                    JSON => json(&run)?,
2270                    TURTLE => {
2271                        let mut graph = crate::graph::Graph::default();
2272                        graph.record(&run);
2273                        turtle(graph)?
2274                    }
2275                    _ => plain(run.render()),
2276                };
2277                // A finished run never changes again; one still running will.
2278                Ok(if finished { repr.cacheable() } else { repr })
2279            }
2280            other => Err(unsupported("script-run", other)),
2281        }
2282    }
2283
2284    fn name(&self) -> &str {
2285        "script-run"
2286    }
2287
2288    fn describe(&self) -> Description {
2289        let id = || {
2290            ArgSpec::new("id")
2291                .summary("The run's number, unique per script.")
2292                .class(XSD_INTEGER)
2293                .binding()
2294        };
2295        Description::new("script-run")
2296            .title("One run of a script")
2297            .summary(
2298                "A recorded run: principal, version, capability, start and end, outcome, the \
2299                 result (up to 64 KiB) and the host's trace span when it traced. Needs the \
2300                 script's read or run grant.",
2301            )
2302            .verb(Verb::Meta)
2303            .action(
2304                ActionSpec::new(Verb::Source)
2305                    .summary("The run record, as text, JSON, or a PROV-O graph (Turtle).")
2306                    .input(name_arg())
2307                    .input(id())
2308                    .input(record_as_arg())
2309                    .output(PLAIN)
2310                    .output(JSON)
2311                    .output(TURTLE)
2312                    .requires(CAP_ANY),
2313            )
2314            .action(
2315                ActionSpec::new(Verb::Exists)
2316                    .summary("Whether the run exists.")
2317                    .input(name_arg())
2318                    .input(id())
2319                    .output(PLAIN)
2320                    .requires(CAP_ANY),
2321            )
2322    }
2323}
2324
2325// ---------------------------------------------------------------------------------------
2326// urn:script:eval — the paste box
2327// ---------------------------------------------------------------------------------------
2328
2329struct EvalEndpoint;
2330
2331#[async_trait]
2332impl Endpoint for EvalEndpoint {
2333    async fn invoke(&self, inv: &Invocation<'_>) -> Result<Representation> {
2334        if inv.request.verb != Verb::Sink {
2335            return Err(unsupported("script-eval", inv.request.verb));
2336        }
2337        let code = inv.inline_str("content")?;
2338        let language_text = optional(inv, "language")?;
2339        let language = language_text
2340            .map(Language::parse)
2341            .transpose()?
2342            .unwrap_or(Language::Lisp);
2343        if language == Language::Sparql {
2344            return Err(Error::InvalidArgument {
2345                name: "language".to_string(),
2346                detail: "SPARQL through urn:script:eval is the SPARQL Protocol face (ledger \
2347                         #955), not in this version: publish the query as a script and read \
2348                         its `…:result`"
2349                    .to_string(),
2350            });
2351        }
2352        if language == Language::Plan {
2353            // Not a second door onto the same thing: the host's evaluator already runs a
2354            // supplied plan under the caller's own capability, which is all this door adds.
2355            return Err(Error::InvalidArgument {
2356                name: "language".to_string(),
2357                detail: format!(
2358                    "a plan supplied ad hoc runs at {} (`in` = the plan), under the caller's \
2359                     own capability; to keep it, publish it as a script",
2360                    plan::EVAL
2361                ),
2362            });
2363        }
2364        if let Some(save) = optional(inv, "save")? {
2365            let save = save.trim();
2366            name::validate(save)?;
2367            // Saved the way any writer saves: a Sink to the script, under the caller's own
2368            // capability (so it needs `urn:cap:script:write:{save}`), which cuts the script's
2369            // thread like every other write.
2370            let mut request = Request::new(Verb::Sink, iri(&name::script_iri(save))?)
2371                .with_arg("content", inline(code))
2372                .with_arg("language", inline(language.as_str()))
2373                .with_arg("state", inline("draft"));
2374            if let Some(requires) = optional(inv, "requires")? {
2375                request = request.with_arg("requires", inline(requires));
2376            }
2377            inv.issue(request).await?;
2378        }
2379        // ★ The caller's OWN capability, unchanged: `issue`, not `issue_attenuated`, and
2380        // nothing that could add to it exists.
2381        let answer = inv
2382            .issue(lisp_request(code, optional(inv, "data")?)?)
2383            .await?;
2384        Ok(Representation::new(answer.repr_type, answer.bytes))
2385    }
2386
2387    fn name(&self) -> &str {
2388        "script-eval"
2389    }
2390
2391    fn describe(&self) -> Description {
2392        Description::new("script-eval")
2393            .title("Run code you supply")
2394            .summary(
2395                "Run typed or pasted code as an anonymous script under the caller's OWN \
2396                 capability and nothing more; answers its value. `save=` keeps it as a draft \
2397                 of that script (which needs that script's write grant).",
2398            )
2399            .verb(Verb::Meta)
2400            .action(
2401                ActionSpec::new(Verb::Sink)
2402                    .summary("Run the code.")
2403                    .input(
2404                        ArgSpec::new("content")
2405                            .summary("The code (piped).")
2406                            .class(XSD_STRING),
2407                    )
2408                    .input(
2409                        ArgSpec::new("language")
2410                            .summary(
2411                                "The code's language: `lisp`, the one this door runs, so the \
2412                                 one its `requires` (`urn:cap:lisp`) is for. A plan runs at \
2413                                 urn:plan:eval, which declares no language capability; SPARQL \
2414                                 here is the Protocol face, not in this version.",
2415                            )
2416                            .class(XSD_STRING)
2417                            // ★ Only what this door runs (ledger #1174): offering `sparql` and
2418                            // `plan` here advertised values it always refuses, under a floor
2419                            // (`urn:cap:lisp`) that only Lisp needs.
2420                            .one_of([Language::Lisp.as_str()])
2421                            .default_value("lisp")
2422                            .optional(),
2423                    )
2424                    .input(data_arg("data", DATA_SUMMARY))
2425                    .input(
2426                        ArgSpec::new("save")
2427                            .summary(
2428                                "A script name: also keep the code as a draft at \
2429                                 `urn:script:{save}`. Needs `urn:cap:script:write:{save}`.",
2430                            )
2431                            .class(XSD_STRING)
2432                            .optional(),
2433                    )
2434                    .input(
2435                        ArgSpec::new("requires")
2436                            .summary("With `save=`: the draft's declared capability.")
2437                            .class(XSD_STRING)
2438                            .optional(),
2439                    )
2440                    .output(PLAIN)
2441                    .requires(CAP_LISP),
2442            )
2443    }
2444}
2445
2446// ---------------------------------------------------------------------------------------
2447// urn:script:catalog
2448// ---------------------------------------------------------------------------------------
2449
2450/// One row of the catalog.
2451#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
2452pub struct CatalogEntry {
2453    /// The script.
2454    pub name: String,
2455    /// `urn:script:{name}`.
2456    pub iri: String,
2457    /// Its state, when its head could be read.
2458    pub state: Option<State>,
2459    /// Whether it is public.
2460    pub public: Option<bool>,
2461    /// Its head version.
2462    pub version: Option<String>,
2463    /// Its latest run.
2464    #[serde(rename = "lastRun")]
2465    pub last_run: Option<LastRun>,
2466    /// Why its head could not be read, when it could not.
2467    pub error: Option<String>,
2468}
2469
2470/// A catalog row's latest run.
2471#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
2472pub struct LastRun {
2473    /// `urn:script:{name}:run:{id}`.
2474    pub iri: String,
2475    /// `running`, `ok` or `failed`.
2476    pub status: String,
2477    /// When it ended.
2478    pub ended: Option<u64>,
2479}
2480
2481/// The catalog's JSON face.
2482#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
2483pub struct Catalog {
2484    /// [`SCHEMA`].
2485    pub schema: u32,
2486    /// Every script the caller may read, by name.
2487    pub scripts: Vec<CatalogEntry>,
2488}
2489
2490struct CatalogEndpoint {
2491    shared: Arc<SpaceConfig>,
2492}
2493
2494#[async_trait]
2495impl Endpoint for CatalogEndpoint {
2496    async fn invoke(&self, inv: &Invocation<'_>) -> Result<Representation> {
2497        if inv.request.verb != Verb::Source {
2498            return Err(unsupported("script-catalog", inv.request.verb));
2499        }
2500        let want = face_of(inv, &RECORD_FACES)?;
2501        let backend = &self.shared.backend;
2502        let mut scripts = Vec::new();
2503        // Each row's last run in full, for the graph face (a catalog row keeps less).
2504        let mut last_runs = Vec::new();
2505        for name in backend.names()? {
2506            let own = may(inv, Act::Read, &name);
2507            let mut entry = CatalogEntry {
2508                iri: name::script_iri(&name),
2509                name: name.clone(),
2510                state: None,
2511                public: None,
2512                version: None,
2513                last_run: None,
2514                error: None,
2515            };
2516            let mut last = None;
2517            match backend.head(&name) {
2518                // A broken head is shown to whoever may read the script, so the dashboard
2519                // says what is wrong instead of losing the row (or the whole list).
2520                Err(e) if own => entry.error = Some(e.to_string()),
2521                // Someone else's draft is not listed: to this caller it does not exist.
2522                Ok(Some(head)) if sight(inv, &head, &head.version) == Sight::Hidden => continue,
2523                Ok(Some(head))
2524                    if own
2525                        || (is_public(&head)
2526                            && may_public(inv, Act::Read, CAP_READ_PUBLIC, &name)) =>
2527                {
2528                    entry.state = Some(head.state);
2529                    entry.public = Some(head.public);
2530                    entry.version = Some(head.version);
2531                    last = backend.last_run(&name).ok().flatten();
2532                    entry.last_run = last.as_ref().map(|run| LastRun {
2533                        iri: run.iri(),
2534                        status: match run.outcome {
2535                            Outcome::Running => "running",
2536                            Outcome::Ok => "ok",
2537                            Outcome::Failed { .. } => "failed",
2538                        }
2539                        .to_string(),
2540                        ended: run.ended,
2541                    });
2542                }
2543                _ => continue,
2544            }
2545            last_runs.push(last);
2546            scripts.push(entry);
2547        }
2548        if want == TURTLE {
2549            let mut graph = crate::graph::Graph::default();
2550            for (entry, last) in scripts.iter().zip(&last_runs) {
2551                graph.script(&entry.name, entry.version.as_deref(), last.as_ref());
2552            }
2553            return turtle(graph);
2554        }
2555        if want == JSON {
2556            // Live: a run that fails is recorded without a write through any name the
2557            // catalog could hang from, so this list is never cached.
2558            return json(&Catalog {
2559                schema: SCHEMA,
2560                scripts,
2561            });
2562        }
2563        let mut text = String::new();
2564        for entry in &scripts {
2565            match (&entry.error, entry.state) {
2566                (Some(error), _) => text.push_str(&format!("{}  BROKEN: {error}\n", entry.iri)),
2567                (None, Some(state)) => {
2568                    let version = entry.version.as_deref().unwrap_or("");
2569                    text.push_str(&format!(
2570                        "{}  {}{}  {}",
2571                        entry.iri,
2572                        state.as_str(),
2573                        if entry.public == Some(true) {
2574                            " public"
2575                        } else {
2576                            ""
2577                        },
2578                        &version[..version.len().min(19)],
2579                    ));
2580                    if let Some(run) = &entry.last_run {
2581                        text.push_str(&format!(
2582                            "  last run {} {} {}",
2583                            run.iri,
2584                            run.status,
2585                            model::when(run.ended)
2586                        ));
2587                    }
2588                    text.push('\n');
2589                }
2590                _ => {}
2591            }
2592        }
2593        if scripts.is_empty() {
2594            text.push_str("no scripts this capability may read\n");
2595        }
2596        Ok(plain(text))
2597    }
2598
2599    fn name(&self) -> &str {
2600        "script-catalog"
2601    }
2602
2603    fn describe(&self) -> Description {
2604        Description::new("script-catalog")
2605            .title("Scripts")
2606            .summary(
2607                "Every script the caller may read: state, public flag, head version and last \
2608                 run. Live (never cached). A host that wants `urn:host:scripts` aliases it \
2609                 here.",
2610            )
2611            .verb(Verb::Meta)
2612            .action(
2613                ActionSpec::new(Verb::Source)
2614                    .summary("The catalog, as text, JSON, or a graph (Turtle).")
2615                    .input(record_as_arg())
2616                    .output(PLAIN)
2617                    .output(JSON)
2618                    .output(TURTLE)
2619                    .requires(CAP_READ),
2620            )
2621    }
2622}
2623
2624fn unsupported(id: &str, verb: Verb) -> Error {
2625    Error::Endpoint(format!("{id} does not answer {verb:?}"))
2626}