Skip to main content

stateknot_runtime/
admission_schema.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Versioned public-safe journal schema used by atomic Agent admission.
5
6use serde_json::Value;
7use stateknot_core::{Digest, SchemaId, SchemaIdError, SchemaReference, Version};
8use thiserror::Error;
9
10use crate::{JsonSchemaRegistryBuilder, JsonSchemaRegistryError};
11
12/// Stable identity of the v1 Agent-admission event-data schema.
13pub const STANDARD_AGENT_ADMISSION_EVENT_SCHEMA_ID: &str =
14    "https://stknot.com/schemas/runtime/agent-admission-event/1.0.0";
15
16const DOCUMENT: &str = include_str!("../schemas/agent-admission-event-1.0.0.json");
17
18/// Returns the immutable reference and owned JSON Schema document shipped with
19/// this runtime release.
20///
21/// # Errors
22///
23/// Returns [`StandardAgentAdmissionSchemaError`] only when the embedded release
24/// artifact is internally malformed.
25pub fn standard_agent_admission_event_schema()
26-> Result<(SchemaReference, Value), StandardAgentAdmissionSchemaError> {
27    let document = serde_json::from_str::<Value>(DOCUMENT)
28        .map_err(|_| StandardAgentAdmissionSchemaError::EmbeddedDocument)?;
29    let canonical = serde_json_canonicalizer::to_vec(&document)
30        .map_err(|_| StandardAgentAdmissionSchemaError::Canonicalization)?;
31    let id = STANDARD_AGENT_ADMISSION_EVENT_SCHEMA_ID
32        .parse::<SchemaId>()
33        .map_err(StandardAgentAdmissionSchemaError::identifier)?;
34    let reference = SchemaReference::new(id, Version::new(1, 0, 0), Digest::sha256(canonical));
35    Ok((reference, document))
36}
37
38/// Registers the standard Agent-admission event schema in a startup registry.
39///
40/// # Errors
41///
42/// Returns an embedded-definition error or the registry's duplicate, resource,
43/// dialect, digest, and reference-resolution failures.
44pub fn register_standard_agent_admission_event_schema(
45    builder: &mut JsonSchemaRegistryBuilder,
46) -> Result<SchemaReference, StandardAgentAdmissionSchemaRegistrationError> {
47    let (reference, document) = standard_agent_admission_event_schema()?;
48    builder.register(reference.clone(), document)?;
49    Ok(reference)
50}
51
52/// Internal release-artifact failure for the standard admission schema.
53#[derive(Clone, Debug, Eq, Error, PartialEq)]
54#[non_exhaustive]
55pub enum StandardAgentAdmissionSchemaError {
56    /// The embedded JSON document cannot be parsed.
57    #[error("embedded Agent-admission event schema is invalid JSON")]
58    EmbeddedDocument,
59    /// The embedded document cannot be represented as RFC 8785 bytes.
60    #[error("embedded Agent-admission event schema cannot be canonicalized")]
61    Canonicalization,
62    /// The embedded stable HTTPS identifier is invalid.
63    #[error("embedded Agent-admission event schema identifier is invalid: {source}")]
64    Identifier {
65        /// Exact identifier validation error.
66        #[source]
67        source: SchemaIdError,
68    },
69}
70
71impl StandardAgentAdmissionSchemaError {
72    const fn identifier(source: SchemaIdError) -> Self {
73        Self::Identifier { source }
74    }
75}
76
77/// Startup failure while adding the standard admission schema to a registry.
78#[derive(Clone, Debug, Eq, Error, PartialEq)]
79#[non_exhaustive]
80pub enum StandardAgentAdmissionSchemaRegistrationError {
81    /// The embedded release artifact was malformed.
82    #[error(transparent)]
83    Definition(#[from] StandardAgentAdmissionSchemaError),
84    /// The target registry rejected the immutable resource.
85    #[error(transparent)]
86    Registry(#[from] JsonSchemaRegistryError),
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92    use crate::JsonSchemaRegistryLimits;
93    use serde_json::json;
94    use stateknot_core::BoundedJson;
95
96    #[test]
97    fn standard_schema_is_digest_pinned_registry_valid_and_closed() {
98        let (reference, document) = standard_agent_admission_event_schema().unwrap();
99        assert_eq!(
100            reference.id().as_str(),
101            STANDARD_AGENT_ADMISSION_EVENT_SCHEMA_ID
102        );
103        assert_eq!(reference.version(), Version::new(1, 0, 0));
104
105        let mut builder = JsonSchemaRegistryBuilder::new(JsonSchemaRegistryLimits::default());
106        builder.register(reference.clone(), document).unwrap();
107        let registry = builder.build().unwrap();
108        let valid = json!({
109            "operation": "agent_admitted",
110            "intent_digest": "a".repeat(64),
111            "graph_digest": "b".repeat(64),
112            "policy_digest": "c".repeat(64),
113            "input_digest": "d".repeat(64)
114        });
115        registry
116            .validate_bounded(
117                &reference,
118                &BoundedJson::try_from_value(valid.clone()).unwrap(),
119            )
120            .unwrap();
121
122        let mut extra = valid;
123        extra["request"] = json!({"secret": true});
124        assert!(
125            registry
126                .validate_bounded(&reference, &BoundedJson::try_from_value(extra).unwrap())
127                .is_err()
128        );
129    }
130}