Skip to main content

stateknot_runtime/
durable_admission.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Trusted control-plane preparation for atomic durable Agent admission.
5
6use std::fmt;
7
8use schemars::JsonSchema;
9use serde::{Deserialize, Deserializer, Serialize, de};
10use serde_json::json;
11use stateknot_core::{
12    AgentAdmissionAuthority, AgentAdmissionBudgetLayer, AgentAdmissionIntent,
13    AgentAdmissionIntentError, AgentDescriptor, AgentRequest, AgentResultProvenance,
14    AgentSubmissionKey, BoundedJson, BoundedJsonError, CanonicalJson, CanonicalJsonError,
15    Checkpoint, CheckpointId, CheckpointState, CheckpointWrite, CheckpointWriteError,
16    ChildRunAdmissionIntent, ChildRunAdmissionIntentError, ChildRunKey, ChildRunPolicyError,
17    Digest, EventId, GraphReference, GraphSchemaValidationError, InvocationId, JournalAppend,
18    JournalAppendError, JournalEventIntent, JournalEventKind, JournalEventKindError,
19    JournalExpectation, JournalIntentError, JournalPayload, JournalPayloadError, RunId, RunStatus,
20    TenantId, ThreadId, Timestamp,
21};
22use stateknot_store_postgres::{
23    AgentAdmissionCommitOutcome, AgentSubmissionCommitOutcome, PostgresStore, StoreError,
24    StoredAgentAdmission,
25};
26use thiserror::Error;
27
28use crate::{
29    ExecutableGraphRegistry, StandardAgentAdmissionSchemaError,
30    standard_agent_admission_event_schema,
31};
32
33/// Stable identities allocated once at trusted request ingress.
34///
35/// Retrying an ambiguous admission must reuse this exact value. Generating a
36/// replacement event or checkpoint identity after a lost acknowledgement is a
37/// conflicting submission, not an idempotent retry.
38#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
39#[serde(deny_unknown_fields)]
40#[allow(clippy::struct_field_names)]
41pub struct AgentRunIds {
42    run_id: RunId,
43    thread_id: ThreadId,
44    invocation_id: InvocationId,
45    admission_event_id: EventId,
46    initial_checkpoint_id: CheckpointId,
47}
48
49impl AgentRunIds {
50    /// Binds caller-retained `UUIDv7` identities for one root Agent run.
51    #[must_use]
52    pub const fn new(
53        run_id: RunId,
54        thread_id: ThreadId,
55        invocation_id: InvocationId,
56        admission_event_id: EventId,
57        initial_checkpoint_id: CheckpointId,
58    ) -> Self {
59        Self {
60            run_id,
61            thread_id,
62            invocation_id,
63            admission_event_id,
64            initial_checkpoint_id,
65        }
66    }
67
68    /// Generates one complete identity bundle for a new submission.
69    #[must_use]
70    pub fn generate() -> Self {
71        Self::new(
72            RunId::generate(),
73            ThreadId::generate(),
74            InvocationId::generate(),
75            EventId::generate(),
76            CheckpointId::generate(),
77        )
78    }
79
80    /// Returns the durable run identity.
81    #[must_use]
82    pub const fn run_id(self) -> RunId {
83        self.run_id
84    }
85
86    /// Returns the durable conversation identity.
87    #[must_use]
88    pub const fn thread_id(self) -> ThreadId {
89        self.thread_id
90    }
91
92    /// Returns the root logical Agent invocation identity.
93    #[must_use]
94    pub const fn invocation_id(self) -> InvocationId {
95        self.invocation_id
96    }
97
98    /// Returns the immutable sequence-one event identity.
99    #[must_use]
100    pub const fn admission_event_id(self) -> EventId {
101        self.admission_event_id
102    }
103
104    /// Returns the immutable superstep-zero checkpoint identity.
105    #[must_use]
106    pub const fn initial_checkpoint_id(self) -> CheckpointId {
107        self.initial_checkpoint_id
108    }
109}
110
111/// Fully retained input for an exact atomic Agent-admission retry.
112///
113/// The request carries no journal head or ready set. Those are derived from the
114/// empty journal and the frozen executable graph inside [`DurableAgentAdmission`].
115#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
116#[serde(deny_unknown_fields)]
117pub struct DurableAgentAdmissionRequest {
118    intent: AgentAdmissionIntent,
119    admission_event_id: EventId,
120    initial_checkpoint_id: CheckpointId,
121    initial_state: CheckpointState,
122}
123
124impl DurableAgentAdmissionRequest {
125    /// Constructs one complete request and resolves its immutable budget.
126    ///
127    /// # Errors
128    ///
129    /// Returns [`DurableAgentAdmissionRequestError`] for an invalid Agent,
130    /// request, policy, budget, provenance, graph, or initial-state binding.
131    #[allow(clippy::too_many_arguments)]
132    pub fn new<I>(
133        tenant_id: TenantId,
134        ids: AgentRunIds,
135        descriptor: AgentDescriptor,
136        request: AgentRequest,
137        budget_layers: I,
138        graph: GraphReference,
139        authority: AgentAdmissionAuthority,
140        initial_state: CheckpointState,
141    ) -> Result<Self, DurableAgentAdmissionRequestError>
142    where
143        I: IntoIterator<Item = AgentAdmissionBudgetLayer>,
144    {
145        let provenance = AgentResultProvenance::for_agent(
146            tenant_id,
147            ids.run_id,
148            ids.thread_id,
149            ids.invocation_id,
150            &descriptor,
151        );
152        let intent = AgentAdmissionIntent::new(
153            provenance,
154            descriptor,
155            request,
156            budget_layers,
157            graph,
158            authority,
159        )?;
160        Self::from_intent(
161            intent,
162            ids.admission_event_id,
163            ids.initial_checkpoint_id,
164            initial_state,
165        )
166    }
167
168    fn from_intent(
169        intent: AgentAdmissionIntent,
170        admission_event_id: EventId,
171        initial_checkpoint_id: CheckpointId,
172        initial_state: CheckpointState,
173    ) -> Result<Self, DurableAgentAdmissionRequestError> {
174        if initial_state.schema() != intent.graph().state_schema() {
175            return Err(DurableAgentAdmissionRequestError::InitialStateSchemaMismatch);
176        }
177        Ok(Self {
178            intent,
179            admission_event_id,
180            initial_checkpoint_id,
181            initial_state,
182        })
183    }
184
185    /// Returns the complete immutable caller-controlled admission intent.
186    #[must_use]
187    pub const fn intent(&self) -> &AgentAdmissionIntent {
188        &self.intent
189    }
190
191    /// Returns the stable first event identity.
192    #[must_use]
193    pub const fn admission_event_id(&self) -> EventId {
194        self.admission_event_id
195    }
196
197    /// Returns the stable initial checkpoint identity.
198    #[must_use]
199    pub const fn initial_checkpoint_id(&self) -> CheckpointId {
200        self.initial_checkpoint_id
201    }
202
203    /// Returns the exact schema-pinned initial graph state.
204    #[must_use]
205    pub const fn initial_state(&self) -> &CheckpointState {
206        &self.initial_state
207    }
208}
209
210impl fmt::Debug for DurableAgentAdmissionRequest {
211    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
212        formatter
213            .debug_struct("DurableAgentAdmissionRequest")
214            .field("intent", &self.intent)
215            .field("admission_event_id", &self.admission_event_id)
216            .field("initial_checkpoint_id", &self.initial_checkpoint_id)
217            .field("initial_state_schema", self.initial_state.schema())
218            .field("initial_state_digest", &self.initial_state.digest())
219            .finish_non_exhaustive()
220    }
221}
222
223impl<'de> Deserialize<'de> for DurableAgentAdmissionRequest {
224    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
225    where
226        D: Deserializer<'de>,
227    {
228        #[derive(Deserialize)]
229        #[serde(deny_unknown_fields)]
230        struct Wire {
231            intent: AgentAdmissionIntent,
232            admission_event_id: EventId,
233            initial_checkpoint_id: CheckpointId,
234            initial_state: CheckpointState,
235        }
236
237        let wire = Wire::deserialize(deserializer)?;
238        Self::from_intent(
239            wire.intent,
240            wire.admission_event_id,
241            wire.initial_checkpoint_id,
242            wire.initial_state,
243        )
244        .map_err(de::Error::custom)
245    }
246}
247
248/// Invalid retained admission request.
249#[derive(Clone, Debug, Eq, Error, PartialEq)]
250#[non_exhaustive]
251pub enum DurableAgentAdmissionRequestError {
252    /// The complete Agent admission intent was invalid.
253    #[error(transparent)]
254    Intent(#[from] AgentAdmissionIntentError),
255    /// Initial state named a schema other than the pinned graph state schema.
256    #[error("initial Agent state schema does not match the pinned graph")]
257    InitialStateSchemaMismatch,
258}
259
260/// Trusted runtime facade for one all-or-nothing durable Agent admission.
261#[derive(Clone)]
262pub struct DurableAgentAdmission {
263    store: PostgresStore,
264    registry: ExecutableGraphRegistry,
265    event_schema: stateknot_core::SchemaReference,
266}
267
268impl DurableAgentAdmission {
269    /// Binds one provider pool and the exact executable deployment snapshot.
270    ///
271    /// # Errors
272    ///
273    /// Rejects a malformed embedded release schema or a deployment registry
274    /// that omitted its exact digest-pinned reference before freezing.
275    pub fn new(
276        store: PostgresStore,
277        registry: ExecutableGraphRegistry,
278    ) -> Result<Self, DurableAgentAdmissionBuildError> {
279        let (event_schema, _) = standard_agent_admission_event_schema()?;
280        if !registry.schemas().contains(&event_schema) {
281            return Err(DurableAgentAdmissionBuildError::EventSchemaUnavailable);
282        }
283        Ok(Self {
284            store,
285            registry,
286            event_schema,
287        })
288    }
289
290    pub(crate) const fn event_schema(&self) -> &stateknot_core::SchemaReference {
291        &self.event_schema
292    }
293
294    /// Prepares an isolated child candidate from verified parent snapshots.
295    ///
296    /// This synchronous operation performs no writes, lease claims, or provider
297    /// I/O. It does not create a child Run or reserve budget. It binds the exact
298    /// executable child graph and rechecks parent activity, checkpoint, schemas,
299    /// authority shape, immutable budget narrowing, and the parent graph's exact
300    /// node-owned child Agent/graph declaration. A future atomic child
301    /// admission must recheck these snapshots and serialize budget/ownership;
302    /// calling [`Self::admit`] with the child candidate is not that operation.
303    ///
304    /// ```no_run
305    /// # use stateknot_core::*;
306    /// # use stateknot_runtime::DurableAgentAdmission;
307    /// # use stateknot_store_postgres::PostgresStore;
308    /// # async fn example(store: &PostgresStore, facade: &DurableAgentAdmission,
309    /// # tenant: &TenantId, parent_run: RunId, node: NodeId,
310    /// # child: AgentAdmissionIntent, state: CheckpointState)
311    /// # -> Result<(), Box<dyn std::error::Error>> {
312    /// // The registered parent graph must declare this node's "analysis" slot
313    /// // with the exact child descriptor and graph before parent admission.
314    /// let parent = store.load_agent_admission(tenant, parent_run).await?;
315    /// let checkpoint = store.load_current_checkpoint(tenant, parent_run)
316    ///     .await?.ok_or("parent has no checkpoint")?;
317    /// let key = ChildRunKey::new(
318    ///     NodeActivation::for_ready_root(&checkpoint, node)?,
319    ///     ChildRunSlot::new("analysis")?,
320    /// )?;
321    /// let candidate = facade.prepare_child(&parent, &checkpoint, key, child,
322    ///     state, store.observe_database_clock().await?)?;
323    /// let bytes = candidate.canonical_bytes()?;
324    /// let restored: ChildRunAdmissionIntent = serde_json::from_slice(&bytes)?;
325    /// facade.validate_child_preparation(&parent, &checkpoint, &restored,
326    ///     store.observe_database_clock().await?)?;
327    /// // This prepared value is not a durable child or an admission permit.
328    /// # Ok(()) }
329    /// ```
330    pub fn prepare_child(
331        &self,
332        parent: &StoredAgentAdmission,
333        checkpoint: &Checkpoint,
334        key: ChildRunKey,
335        child: AgentAdmissionIntent,
336        initial_state: CheckpointState,
337        observed_at: Timestamp,
338    ) -> Result<ChildRunAdmissionIntent, ChildAdmissionPreparationError> {
339        let executable = self
340            .registry
341            .resolve(child.graph())
342            .ok_or(ChildAdmissionPreparationError::ExecutableUnavailable)?;
343        let intent = ChildRunAdmissionIntent::new(
344            parent.admission(),
345            key,
346            child,
347            executable.graph().clone(),
348            initial_state,
349        )?;
350        self.validate_child_preparation(parent, checkpoint, &intent, observed_at)?;
351        Ok(intent)
352    }
353
354    /// Revalidates a restored preparation against freshly loaded parent data.
355    ///
356    /// Rejects cancelled/waiting/terminal/quarantined snapshots, mismatched
357    /// checkpoint pointers, undeclared or substituted child targets, deployment
358    /// drift, and core/schema failures. Even a
359    /// successful read-only validation can race a later lifecycle change; it
360    /// never acts as a durable admission permit or a lost-ACK commit lookup.
361    pub fn validate_child_preparation(
362        &self,
363        parent: &StoredAgentAdmission,
364        checkpoint: &Checkpoint,
365        intent: &ChildRunAdmissionIntent,
366        observed_at: Timestamp,
367    ) -> Result<(), ChildAdmissionPreparationError> {
368        if parent.run().is_quarantined() || parent.run().lifecycle().status() != RunStatus::Active {
369            return Err(ChildAdmissionPreparationError::ParentNotActive);
370        }
371        if !parent.run().checkpoint().is_some_and(|pointer| {
372            pointer.checkpoint_id() == checkpoint.checkpoint_id()
373                && pointer.superstep() == checkpoint.superstep()
374                && pointer.digest() == checkpoint.digest()
375        }) {
376            return Err(ChildAdmissionPreparationError::CurrentCheckpointMismatch);
377        }
378        let parent_graph = self
379            .registry
380            .resolve(parent.admission().intent().graph())
381            .ok_or(ChildAdmissionPreparationError::ExecutableUnavailable)?;
382        if self.registry.resolve(intent.child().graph()).is_none() {
383            return Err(ChildAdmissionPreparationError::ExecutableUnavailable);
384        }
385        intent.validate_declaration(parent_graph.graph())?;
386        intent.validate_for(
387            parent.admission(),
388            checkpoint,
389            self.registry.schemas(),
390            observed_at,
391        )?;
392        Ok(())
393    }
394
395    /// Validates and atomically commits one new executable Agent run.
396    ///
397    /// Exact retries recover durable admission evidence before time-sensitive
398    /// evaluation. The request, authorization evidence, initial state, standard
399    /// event data, graph input/output schemas, and complete executable graph are
400    /// all checked against the same immutable offline deployment snapshot before
401    /// the `PostgreSQL` transaction begins.
402    ///
403    /// # Errors
404    ///
405    /// Returns [`DurableAgentAdmissionError`] for deployment drift, schema
406    /// rejection, malformed retained input, durable conflict/corruption, or a
407    /// database failure.
408    pub async fn admit(
409        &self,
410        request: DurableAgentAdmissionRequest,
411    ) -> Result<AgentAdmissionCommitOutcome, DurableAgentAdmissionError> {
412        let prepared = self.prepare(request)?;
413        Box::pin(self.store.admit_agent_run(
414            prepared.intent,
415            prepared.append,
416            prepared.checkpoint,
417            self.registry.schemas(),
418        ))
419        .await
420        .map_err(DurableAgentAdmissionError::Store)
421    }
422
423    /// Resolves an ingress idempotency key to one atomic executable Agent run.
424    ///
425    /// Candidate IDs inside `request` are deliberately excluded from the
426    /// submission fingerprint. A retry may therefore create a fresh candidate
427    /// bundle: the same key and content return the original run, while changed
428    /// content fails closed. The raw key is never stored.
429    ///
430    /// # Errors
431    ///
432    /// Returns [`DurableAgentAdmissionError`] for deployment/schema failures,
433    /// conflicting key reuse, durable corruption, or database failure.
434    pub async fn submit(
435        &self,
436        key: &AgentSubmissionKey,
437        request: DurableAgentAdmissionRequest,
438    ) -> Result<AgentSubmissionCommitOutcome, DurableAgentAdmissionError> {
439        let prepared = self.prepare(request)?;
440        Box::pin(self.store.submit_agent_run(
441            key,
442            prepared.intent,
443            prepared.append,
444            prepared.checkpoint,
445            self.registry.schemas(),
446        ))
447        .await
448        .map_err(DurableAgentAdmissionError::Store)
449    }
450
451    fn prepare(
452        &self,
453        request: DurableAgentAdmissionRequest,
454    ) -> Result<PreparedDurableAgentAdmission, DurableAgentAdmissionError> {
455        let executable = self
456            .registry
457            .resolve(request.intent.graph())
458            .ok_or(DurableAgentAdmissionError::ExecutableGraphUnavailable)?;
459        let graph = executable.graph();
460        let descriptor = request.intent.descriptor();
461        if descriptor.input_schema() != graph.input_schema() {
462            return Err(DurableAgentAdmissionError::GraphInputSchemaMismatch);
463        }
464        if descriptor.output_schema() != graph.output_schema() {
465            return Err(DurableAgentAdmissionError::GraphOutputSchemaMismatch);
466        }
467
468        self.registry
469            .schemas()
470            .validate_bounded(
471                request.intent.request().input_schema(),
472                request.intent.request().input(),
473            )
474            .map_err(DurableAgentAdmissionError::input_schema)?;
475        self.registry
476            .schemas()
477            .validate_bounded(
478                request.intent.authority().evidence().schema(),
479                request.intent.authority().evidence().data(),
480            )
481            .map_err(DurableAgentAdmissionError::authority_schema)?;
482        self.registry
483            .schemas()
484            .validate_bounded(request.initial_state.schema(), request.initial_state.data())
485            .map_err(DurableAgentAdmissionError::initial_state_schema)?;
486
487        let input_digest = CanonicalJson::new(request.intent.request().input())
488            .map_err(DurableAgentAdmissionError::CanonicalInput)?
489            .digest();
490        let event_data = BoundedJson::try_from_value(json!({
491            "operation": "agent_admitted",
492            "intent_digest": digest_hex(request.intent.intent_digest()),
493            "graph_digest": digest_hex(request.intent.graph().definition_digest()),
494            "policy_digest": digest_hex(request.intent.authority().policy_digest()),
495            "input_digest": digest_hex(input_digest)
496        }))
497        .map_err(DurableAgentAdmissionError::EventData)?;
498        self.registry
499            .schemas()
500            .validate_bounded(&self.event_schema, &event_data)
501            .map_err(DurableAgentAdmissionError::event_schema)?;
502        let payload = JournalPayload::new(
503            self.event_schema.clone(),
504            JournalEventKind::new(stateknot_core::AgentAdmission::JOURNAL_EVENT_KIND)
505                .map_err(DurableAgentAdmissionError::EventKind)?,
506            event_data,
507        )
508        .map_err(DurableAgentAdmissionError::EventPayload)?;
509        let event = JournalEventIntent::control_plane(
510            request.intent.provenance().tenant_id().clone(),
511            request.intent.provenance().run_id(),
512            request.admission_event_id,
513            payload,
514        )
515        .map_err(DurableAgentAdmissionError::EventIntent)?;
516        let append = JournalAppend::new(JournalExpectation::empty(), event)
517            .map_err(DurableAgentAdmissionError::JournalAppend)?;
518        let checkpoint = CheckpointWrite::initial(
519            request.intent.provenance().tenant_id().clone(),
520            request.intent.provenance().run_id(),
521            request.initial_checkpoint_id,
522            request.intent.graph().clone(),
523            request.initial_state,
524            graph.entry_nodes().clone(),
525        )
526        .map_err(DurableAgentAdmissionError::Checkpoint)?;
527
528        Ok(PreparedDurableAgentAdmission {
529            intent: request.intent,
530            append,
531            checkpoint,
532        })
533    }
534}
535
536struct PreparedDurableAgentAdmission {
537    intent: AgentAdmissionIntent,
538    append: JournalAppend,
539    checkpoint: CheckpointWrite,
540}
541
542fn digest_hex(digest: Digest) -> String {
543    const HEX: &[u8; 16] = b"0123456789abcdef";
544    let mut value = String::with_capacity(Digest::SHA256_LEN * 2);
545    for byte in digest.as_bytes() {
546        value.push(char::from(HEX[usize::from(byte >> 4)]));
547        value.push(char::from(HEX[usize::from(byte & 0x0f)]));
548    }
549    value
550}
551
552impl fmt::Debug for DurableAgentAdmission {
553    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
554        formatter
555            .debug_struct("DurableAgentAdmission")
556            .field("registry", &self.registry)
557            .field("event_schema", &self.event_schema)
558            .finish_non_exhaustive()
559    }
560}
561
562/// Read-only child preparation failed; no admission or reservation was written.
563#[derive(Clone, Debug, Eq, Error, PartialEq)]
564#[non_exhaustive]
565pub enum ChildAdmissionPreparationError {
566    /// The parent does not declare this exact child Agent/graph selection.
567    #[error(transparent)]
568    Declaration(#[from] ChildRunPolicyError),
569    /// Only an active, non-quarantined parent snapshot may propose children.
570    #[error("child preparation requires an active non-quarantined parent")]
571    ParentNotActive,
572    /// The supplied checkpoint is not the current pointer of the parent snapshot.
573    #[error("child preparation current checkpoint mismatch")]
574    CurrentCheckpointMismatch,
575    /// The frozen registry lacks the exact parent or child executable closure.
576    #[error("child preparation executable graph unavailable")]
577    ExecutableUnavailable,
578    /// Core scope, integrity, narrowing, readiness, clock, or schema checks failed.
579    #[error(transparent)]
580    Intent(#[from] ChildRunAdmissionIntentError),
581}
582
583/// Startup failure while binding the durable admission facade.
584#[derive(Clone, Debug, Eq, Error, PartialEq)]
585#[non_exhaustive]
586pub enum DurableAgentAdmissionBuildError {
587    /// The embedded standard event schema was malformed.
588    #[error(transparent)]
589    EventSchema(#[from] StandardAgentAdmissionSchemaError),
590    /// The deployment registry omitted the exact embedded event schema.
591    #[error("standard Agent-admission event schema is unavailable")]
592    EventSchemaUnavailable,
593}
594
595/// Payload-redacted failure while preparing or committing Agent admission.
596#[derive(Debug, Error)]
597#[non_exhaustive]
598pub enum DurableAgentAdmissionError {
599    /// The intent's exact graph and executable closure are absent locally.
600    #[error("Agent admission graph is unavailable in the executable registry")]
601    ExecutableGraphUnavailable,
602    /// The Agent input contract and graph input contract differ.
603    #[error("Agent input schema does not match the executable graph input schema")]
604    GraphInputSchemaMismatch,
605    /// The Agent output contract and graph terminal contract differ.
606    #[error("Agent output schema does not match the executable graph output schema")]
607    GraphOutputSchemaMismatch,
608    /// The typed request failed its exact local input schema.
609    #[error("Agent admission input schema validation failed: {source}")]
610    InputSchema {
611        /// Closed schema result.
612        #[source]
613        source: GraphSchemaValidationError,
614    },
615    /// Authorization evidence failed its exact local schema.
616    #[error("Agent admission authorization evidence validation failed: {source}")]
617    AuthoritySchema {
618        /// Closed schema result.
619        #[source]
620        source: GraphSchemaValidationError,
621    },
622    /// Initial graph state failed its exact local schema.
623    #[error("Agent admission initial state validation failed: {source}")]
624    InitialStateSchema {
625        /// Closed schema result.
626        #[source]
627        source: GraphSchemaValidationError,
628    },
629    /// The framework-owned event data failed its embedded schema.
630    #[error("Agent admission standard event schema validation failed: {source}")]
631    EventSchema {
632        /// Closed schema result.
633        #[source]
634        source: GraphSchemaValidationError,
635    },
636    /// Input JSON could not be represented in the canonical audit digest.
637    #[error("Agent admission input canonicalization failed: {0}")]
638    CanonicalInput(#[source] CanonicalJsonError),
639    /// Framework-owned event data unexpectedly exceeded JSON bounds.
640    #[error("Agent admission event data is invalid: {0}")]
641    EventData(#[source] BoundedJsonError),
642    /// The framework-owned stable event kind was malformed.
643    #[error("Agent admission event kind is invalid: {0}")]
644    EventKind(#[source] JournalEventKindError),
645    /// The framework-owned payload envelope was malformed.
646    #[error("Agent admission event payload is invalid: {0}")]
647    EventPayload(#[source] JournalPayloadError),
648    /// The control-plane event intent could not be constructed.
649    #[error("Agent admission event intent is invalid: {0}")]
650    EventIntent(#[source] JournalIntentError),
651    /// The empty-head append could not be constructed.
652    #[error("Agent admission journal append is invalid: {0}")]
653    JournalAppend(#[source] JournalAppendError),
654    /// The initial checkpoint intent could not be constructed.
655    #[error("Agent admission initial checkpoint is invalid: {0}")]
656    Checkpoint(#[source] CheckpointWriteError),
657    /// Durable commit, conflict, or integrity failure.
658    #[error(transparent)]
659    Store(#[from] StoreError),
660}
661
662impl DurableAgentAdmissionError {
663    const fn input_schema(source: GraphSchemaValidationError) -> Self {
664        Self::InputSchema { source }
665    }
666
667    const fn authority_schema(source: GraphSchemaValidationError) -> Self {
668        Self::AuthoritySchema { source }
669    }
670
671    const fn initial_state_schema(source: GraphSchemaValidationError) -> Self {
672        Self::InitialStateSchema { source }
673    }
674
675    const fn event_schema(source: GraphSchemaValidationError) -> Self {
676        Self::EventSchema { source }
677    }
678}
679
680#[cfg(test)]
681mod tests {
682    use super::*;
683
684    #[test]
685    fn audit_digest_data_uses_schema_hex_without_algorithm_prefix() {
686        let value = digest_hex(Digest::sha256(b"agent admission"));
687        assert_eq!(value.len(), Digest::SHA256_LEN * 2);
688        assert!(value.bytes().all(|byte| byte.is_ascii_hexdigit()));
689        assert!(!value.contains(':'));
690    }
691}