stateknot-runtime 0.1.0-alpha.1

Executable registries and durable graph driving for StateKnot
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
// Copyright 2026 StateKnot contributors
// SPDX-License-Identifier: Apache-2.0

//! Trusted control-plane preparation for atomic durable Agent admission.

use std::fmt;

use schemars::JsonSchema;
use serde::{Deserialize, Deserializer, Serialize, de};
use serde_json::json;
use stateknot_core::{
    AgentAdmissionAuthority, AgentAdmissionBudgetLayer, AgentAdmissionIntent,
    AgentAdmissionIntentError, AgentDescriptor, AgentRequest, AgentResultProvenance,
    AgentSubmissionKey, BoundedJson, BoundedJsonError, CanonicalJson, CanonicalJsonError,
    Checkpoint, CheckpointId, CheckpointState, CheckpointWrite, CheckpointWriteError,
    ChildRunAdmissionIntent, ChildRunAdmissionIntentError, ChildRunKey, ChildRunPolicyError,
    Digest, EventId, GraphReference, GraphSchemaValidationError, InvocationId, JournalAppend,
    JournalAppendError, JournalEventIntent, JournalEventKind, JournalEventKindError,
    JournalExpectation, JournalIntentError, JournalPayload, JournalPayloadError, RunId, RunStatus,
    TenantId, ThreadId, Timestamp,
};
use stateknot_store_postgres::{
    AgentAdmissionCommitOutcome, AgentSubmissionCommitOutcome, PostgresStore, StoreError,
    StoredAgentAdmission,
};
use thiserror::Error;

use crate::{
    ExecutableGraphRegistry, StandardAgentAdmissionSchemaError,
    standard_agent_admission_event_schema,
};

/// Stable identities allocated once at trusted request ingress.
///
/// Retrying an ambiguous admission must reuse this exact value. Generating a
/// replacement event or checkpoint identity after a lost acknowledgement is a
/// conflicting submission, not an idempotent retry.
#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
#[allow(clippy::struct_field_names)]
pub struct AgentRunIds {
    run_id: RunId,
    thread_id: ThreadId,
    invocation_id: InvocationId,
    admission_event_id: EventId,
    initial_checkpoint_id: CheckpointId,
}

impl AgentRunIds {
    /// Binds caller-retained `UUIDv7` identities for one root Agent run.
    #[must_use]
    pub const fn new(
        run_id: RunId,
        thread_id: ThreadId,
        invocation_id: InvocationId,
        admission_event_id: EventId,
        initial_checkpoint_id: CheckpointId,
    ) -> Self {
        Self {
            run_id,
            thread_id,
            invocation_id,
            admission_event_id,
            initial_checkpoint_id,
        }
    }

    /// Generates one complete identity bundle for a new submission.
    #[must_use]
    pub fn generate() -> Self {
        Self::new(
            RunId::generate(),
            ThreadId::generate(),
            InvocationId::generate(),
            EventId::generate(),
            CheckpointId::generate(),
        )
    }

    /// Returns the durable run identity.
    #[must_use]
    pub const fn run_id(self) -> RunId {
        self.run_id
    }

    /// Returns the durable conversation identity.
    #[must_use]
    pub const fn thread_id(self) -> ThreadId {
        self.thread_id
    }

    /// Returns the root logical Agent invocation identity.
    #[must_use]
    pub const fn invocation_id(self) -> InvocationId {
        self.invocation_id
    }

    /// Returns the immutable sequence-one event identity.
    #[must_use]
    pub const fn admission_event_id(self) -> EventId {
        self.admission_event_id
    }

    /// Returns the immutable superstep-zero checkpoint identity.
    #[must_use]
    pub const fn initial_checkpoint_id(self) -> CheckpointId {
        self.initial_checkpoint_id
    }
}

/// Fully retained input for an exact atomic Agent-admission retry.
///
/// The request carries no journal head or ready set. Those are derived from the
/// empty journal and the frozen executable graph inside [`DurableAgentAdmission`].
#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct DurableAgentAdmissionRequest {
    intent: AgentAdmissionIntent,
    admission_event_id: EventId,
    initial_checkpoint_id: CheckpointId,
    initial_state: CheckpointState,
}

impl DurableAgentAdmissionRequest {
    /// Constructs one complete request and resolves its immutable budget.
    ///
    /// # Errors
    ///
    /// Returns [`DurableAgentAdmissionRequestError`] for an invalid Agent,
    /// request, policy, budget, provenance, graph, or initial-state binding.
    #[allow(clippy::too_many_arguments)]
    pub fn new<I>(
        tenant_id: TenantId,
        ids: AgentRunIds,
        descriptor: AgentDescriptor,
        request: AgentRequest,
        budget_layers: I,
        graph: GraphReference,
        authority: AgentAdmissionAuthority,
        initial_state: CheckpointState,
    ) -> Result<Self, DurableAgentAdmissionRequestError>
    where
        I: IntoIterator<Item = AgentAdmissionBudgetLayer>,
    {
        let provenance = AgentResultProvenance::for_agent(
            tenant_id,
            ids.run_id,
            ids.thread_id,
            ids.invocation_id,
            &descriptor,
        );
        let intent = AgentAdmissionIntent::new(
            provenance,
            descriptor,
            request,
            budget_layers,
            graph,
            authority,
        )?;
        Self::from_intent(
            intent,
            ids.admission_event_id,
            ids.initial_checkpoint_id,
            initial_state,
        )
    }

    fn from_intent(
        intent: AgentAdmissionIntent,
        admission_event_id: EventId,
        initial_checkpoint_id: CheckpointId,
        initial_state: CheckpointState,
    ) -> Result<Self, DurableAgentAdmissionRequestError> {
        if initial_state.schema() != intent.graph().state_schema() {
            return Err(DurableAgentAdmissionRequestError::InitialStateSchemaMismatch);
        }
        Ok(Self {
            intent,
            admission_event_id,
            initial_checkpoint_id,
            initial_state,
        })
    }

    /// Returns the complete immutable caller-controlled admission intent.
    #[must_use]
    pub const fn intent(&self) -> &AgentAdmissionIntent {
        &self.intent
    }

    /// Returns the stable first event identity.
    #[must_use]
    pub const fn admission_event_id(&self) -> EventId {
        self.admission_event_id
    }

    /// Returns the stable initial checkpoint identity.
    #[must_use]
    pub const fn initial_checkpoint_id(&self) -> CheckpointId {
        self.initial_checkpoint_id
    }

    /// Returns the exact schema-pinned initial graph state.
    #[must_use]
    pub const fn initial_state(&self) -> &CheckpointState {
        &self.initial_state
    }
}

impl fmt::Debug for DurableAgentAdmissionRequest {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("DurableAgentAdmissionRequest")
            .field("intent", &self.intent)
            .field("admission_event_id", &self.admission_event_id)
            .field("initial_checkpoint_id", &self.initial_checkpoint_id)
            .field("initial_state_schema", self.initial_state.schema())
            .field("initial_state_digest", &self.initial_state.digest())
            .finish_non_exhaustive()
    }
}

impl<'de> Deserialize<'de> for DurableAgentAdmissionRequest {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct Wire {
            intent: AgentAdmissionIntent,
            admission_event_id: EventId,
            initial_checkpoint_id: CheckpointId,
            initial_state: CheckpointState,
        }

        let wire = Wire::deserialize(deserializer)?;
        Self::from_intent(
            wire.intent,
            wire.admission_event_id,
            wire.initial_checkpoint_id,
            wire.initial_state,
        )
        .map_err(de::Error::custom)
    }
}

/// Invalid retained admission request.
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum DurableAgentAdmissionRequestError {
    /// The complete Agent admission intent was invalid.
    #[error(transparent)]
    Intent(#[from] AgentAdmissionIntentError),
    /// Initial state named a schema other than the pinned graph state schema.
    #[error("initial Agent state schema does not match the pinned graph")]
    InitialStateSchemaMismatch,
}

/// Trusted runtime facade for one all-or-nothing durable Agent admission.
#[derive(Clone)]
pub struct DurableAgentAdmission {
    store: PostgresStore,
    registry: ExecutableGraphRegistry,
    event_schema: stateknot_core::SchemaReference,
}

impl DurableAgentAdmission {
    /// Binds one provider pool and the exact executable deployment snapshot.
    ///
    /// # Errors
    ///
    /// Rejects a malformed embedded release schema or a deployment registry
    /// that omitted its exact digest-pinned reference before freezing.
    pub fn new(
        store: PostgresStore,
        registry: ExecutableGraphRegistry,
    ) -> Result<Self, DurableAgentAdmissionBuildError> {
        let (event_schema, _) = standard_agent_admission_event_schema()?;
        if !registry.schemas().contains(&event_schema) {
            return Err(DurableAgentAdmissionBuildError::EventSchemaUnavailable);
        }
        Ok(Self {
            store,
            registry,
            event_schema,
        })
    }

    pub(crate) const fn event_schema(&self) -> &stateknot_core::SchemaReference {
        &self.event_schema
    }

    /// Prepares an isolated child candidate from verified parent snapshots.
    ///
    /// This synchronous operation performs no writes, lease claims, or provider
    /// I/O. It does not create a child Run or reserve budget. It binds the exact
    /// executable child graph and rechecks parent activity, checkpoint, schemas,
    /// authority shape, immutable budget narrowing, and the parent graph's exact
    /// node-owned child Agent/graph declaration. A future atomic child
    /// admission must recheck these snapshots and serialize budget/ownership;
    /// calling [`Self::admit`] with the child candidate is not that operation.
    ///
    /// ```no_run
    /// # use stateknot_core::*;
    /// # use stateknot_runtime::DurableAgentAdmission;
    /// # use stateknot_store_postgres::PostgresStore;
    /// # async fn example(store: &PostgresStore, facade: &DurableAgentAdmission,
    /// # tenant: &TenantId, parent_run: RunId, node: NodeId,
    /// # child: AgentAdmissionIntent, state: CheckpointState)
    /// # -> Result<(), Box<dyn std::error::Error>> {
    /// // The registered parent graph must declare this node's "analysis" slot
    /// // with the exact child descriptor and graph before parent admission.
    /// let parent = store.load_agent_admission(tenant, parent_run).await?;
    /// let checkpoint = store.load_current_checkpoint(tenant, parent_run)
    ///     .await?.ok_or("parent has no checkpoint")?;
    /// let key = ChildRunKey::new(
    ///     NodeActivation::for_ready_root(&checkpoint, node)?,
    ///     ChildRunSlot::new("analysis")?,
    /// )?;
    /// let candidate = facade.prepare_child(&parent, &checkpoint, key, child,
    ///     state, store.observe_database_clock().await?)?;
    /// let bytes = candidate.canonical_bytes()?;
    /// let restored: ChildRunAdmissionIntent = serde_json::from_slice(&bytes)?;
    /// facade.validate_child_preparation(&parent, &checkpoint, &restored,
    ///     store.observe_database_clock().await?)?;
    /// // This prepared value is not a durable child or an admission permit.
    /// # Ok(()) }
    /// ```
    pub fn prepare_child(
        &self,
        parent: &StoredAgentAdmission,
        checkpoint: &Checkpoint,
        key: ChildRunKey,
        child: AgentAdmissionIntent,
        initial_state: CheckpointState,
        observed_at: Timestamp,
    ) -> Result<ChildRunAdmissionIntent, ChildAdmissionPreparationError> {
        let executable = self
            .registry
            .resolve(child.graph())
            .ok_or(ChildAdmissionPreparationError::ExecutableUnavailable)?;
        let intent = ChildRunAdmissionIntent::new(
            parent.admission(),
            key,
            child,
            executable.graph().clone(),
            initial_state,
        )?;
        self.validate_child_preparation(parent, checkpoint, &intent, observed_at)?;
        Ok(intent)
    }

    /// Revalidates a restored preparation against freshly loaded parent data.
    ///
    /// Rejects cancelled/waiting/terminal/quarantined snapshots, mismatched
    /// checkpoint pointers, undeclared or substituted child targets, deployment
    /// drift, and core/schema failures. Even a
    /// successful read-only validation can race a later lifecycle change; it
    /// never acts as a durable admission permit or a lost-ACK commit lookup.
    pub fn validate_child_preparation(
        &self,
        parent: &StoredAgentAdmission,
        checkpoint: &Checkpoint,
        intent: &ChildRunAdmissionIntent,
        observed_at: Timestamp,
    ) -> Result<(), ChildAdmissionPreparationError> {
        if parent.run().is_quarantined() || parent.run().lifecycle().status() != RunStatus::Active {
            return Err(ChildAdmissionPreparationError::ParentNotActive);
        }
        if !parent.run().checkpoint().is_some_and(|pointer| {
            pointer.checkpoint_id() == checkpoint.checkpoint_id()
                && pointer.superstep() == checkpoint.superstep()
                && pointer.digest() == checkpoint.digest()
        }) {
            return Err(ChildAdmissionPreparationError::CurrentCheckpointMismatch);
        }
        let parent_graph = self
            .registry
            .resolve(parent.admission().intent().graph())
            .ok_or(ChildAdmissionPreparationError::ExecutableUnavailable)?;
        if self.registry.resolve(intent.child().graph()).is_none() {
            return Err(ChildAdmissionPreparationError::ExecutableUnavailable);
        }
        intent.validate_declaration(parent_graph.graph())?;
        intent.validate_for(
            parent.admission(),
            checkpoint,
            self.registry.schemas(),
            observed_at,
        )?;
        Ok(())
    }

    /// Validates and atomically commits one new executable Agent run.
    ///
    /// Exact retries recover durable admission evidence before time-sensitive
    /// evaluation. The request, authorization evidence, initial state, standard
    /// event data, graph input/output schemas, and complete executable graph are
    /// all checked against the same immutable offline deployment snapshot before
    /// the `PostgreSQL` transaction begins.
    ///
    /// # Errors
    ///
    /// Returns [`DurableAgentAdmissionError`] for deployment drift, schema
    /// rejection, malformed retained input, durable conflict/corruption, or a
    /// database failure.
    pub async fn admit(
        &self,
        request: DurableAgentAdmissionRequest,
    ) -> Result<AgentAdmissionCommitOutcome, DurableAgentAdmissionError> {
        let prepared = self.prepare(request)?;
        Box::pin(self.store.admit_agent_run(
            prepared.intent,
            prepared.append,
            prepared.checkpoint,
            self.registry.schemas(),
        ))
        .await
        .map_err(DurableAgentAdmissionError::Store)
    }

    /// Resolves an ingress idempotency key to one atomic executable Agent run.
    ///
    /// Candidate IDs inside `request` are deliberately excluded from the
    /// submission fingerprint. A retry may therefore create a fresh candidate
    /// bundle: the same key and content return the original run, while changed
    /// content fails closed. The raw key is never stored.
    ///
    /// # Errors
    ///
    /// Returns [`DurableAgentAdmissionError`] for deployment/schema failures,
    /// conflicting key reuse, durable corruption, or database failure.
    pub async fn submit(
        &self,
        key: &AgentSubmissionKey,
        request: DurableAgentAdmissionRequest,
    ) -> Result<AgentSubmissionCommitOutcome, DurableAgentAdmissionError> {
        let prepared = self.prepare(request)?;
        Box::pin(self.store.submit_agent_run(
            key,
            prepared.intent,
            prepared.append,
            prepared.checkpoint,
            self.registry.schemas(),
        ))
        .await
        .map_err(DurableAgentAdmissionError::Store)
    }

    fn prepare(
        &self,
        request: DurableAgentAdmissionRequest,
    ) -> Result<PreparedDurableAgentAdmission, DurableAgentAdmissionError> {
        let executable = self
            .registry
            .resolve(request.intent.graph())
            .ok_or(DurableAgentAdmissionError::ExecutableGraphUnavailable)?;
        let graph = executable.graph();
        let descriptor = request.intent.descriptor();
        if descriptor.input_schema() != graph.input_schema() {
            return Err(DurableAgentAdmissionError::GraphInputSchemaMismatch);
        }
        if descriptor.output_schema() != graph.output_schema() {
            return Err(DurableAgentAdmissionError::GraphOutputSchemaMismatch);
        }

        self.registry
            .schemas()
            .validate_bounded(
                request.intent.request().input_schema(),
                request.intent.request().input(),
            )
            .map_err(DurableAgentAdmissionError::input_schema)?;
        self.registry
            .schemas()
            .validate_bounded(
                request.intent.authority().evidence().schema(),
                request.intent.authority().evidence().data(),
            )
            .map_err(DurableAgentAdmissionError::authority_schema)?;
        self.registry
            .schemas()
            .validate_bounded(request.initial_state.schema(), request.initial_state.data())
            .map_err(DurableAgentAdmissionError::initial_state_schema)?;

        let input_digest = CanonicalJson::new(request.intent.request().input())
            .map_err(DurableAgentAdmissionError::CanonicalInput)?
            .digest();
        let event_data = BoundedJson::try_from_value(json!({
            "operation": "agent_admitted",
            "intent_digest": digest_hex(request.intent.intent_digest()),
            "graph_digest": digest_hex(request.intent.graph().definition_digest()),
            "policy_digest": digest_hex(request.intent.authority().policy_digest()),
            "input_digest": digest_hex(input_digest)
        }))
        .map_err(DurableAgentAdmissionError::EventData)?;
        self.registry
            .schemas()
            .validate_bounded(&self.event_schema, &event_data)
            .map_err(DurableAgentAdmissionError::event_schema)?;
        let payload = JournalPayload::new(
            self.event_schema.clone(),
            JournalEventKind::new(stateknot_core::AgentAdmission::JOURNAL_EVENT_KIND)
                .map_err(DurableAgentAdmissionError::EventKind)?,
            event_data,
        )
        .map_err(DurableAgentAdmissionError::EventPayload)?;
        let event = JournalEventIntent::control_plane(
            request.intent.provenance().tenant_id().clone(),
            request.intent.provenance().run_id(),
            request.admission_event_id,
            payload,
        )
        .map_err(DurableAgentAdmissionError::EventIntent)?;
        let append = JournalAppend::new(JournalExpectation::empty(), event)
            .map_err(DurableAgentAdmissionError::JournalAppend)?;
        let checkpoint = CheckpointWrite::initial(
            request.intent.provenance().tenant_id().clone(),
            request.intent.provenance().run_id(),
            request.initial_checkpoint_id,
            request.intent.graph().clone(),
            request.initial_state,
            graph.entry_nodes().clone(),
        )
        .map_err(DurableAgentAdmissionError::Checkpoint)?;

        Ok(PreparedDurableAgentAdmission {
            intent: request.intent,
            append,
            checkpoint,
        })
    }
}

struct PreparedDurableAgentAdmission {
    intent: AgentAdmissionIntent,
    append: JournalAppend,
    checkpoint: CheckpointWrite,
}

fn digest_hex(digest: Digest) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut value = String::with_capacity(Digest::SHA256_LEN * 2);
    for byte in digest.as_bytes() {
        value.push(char::from(HEX[usize::from(byte >> 4)]));
        value.push(char::from(HEX[usize::from(byte & 0x0f)]));
    }
    value
}

impl fmt::Debug for DurableAgentAdmission {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("DurableAgentAdmission")
            .field("registry", &self.registry)
            .field("event_schema", &self.event_schema)
            .finish_non_exhaustive()
    }
}

/// Read-only child preparation failed; no admission or reservation was written.
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum ChildAdmissionPreparationError {
    /// The parent does not declare this exact child Agent/graph selection.
    #[error(transparent)]
    Declaration(#[from] ChildRunPolicyError),
    /// Only an active, non-quarantined parent snapshot may propose children.
    #[error("child preparation requires an active non-quarantined parent")]
    ParentNotActive,
    /// The supplied checkpoint is not the current pointer of the parent snapshot.
    #[error("child preparation current checkpoint mismatch")]
    CurrentCheckpointMismatch,
    /// The frozen registry lacks the exact parent or child executable closure.
    #[error("child preparation executable graph unavailable")]
    ExecutableUnavailable,
    /// Core scope, integrity, narrowing, readiness, clock, or schema checks failed.
    #[error(transparent)]
    Intent(#[from] ChildRunAdmissionIntentError),
}

/// Startup failure while binding the durable admission facade.
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum DurableAgentAdmissionBuildError {
    /// The embedded standard event schema was malformed.
    #[error(transparent)]
    EventSchema(#[from] StandardAgentAdmissionSchemaError),
    /// The deployment registry omitted the exact embedded event schema.
    #[error("standard Agent-admission event schema is unavailable")]
    EventSchemaUnavailable,
}

/// Payload-redacted failure while preparing or committing Agent admission.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum DurableAgentAdmissionError {
    /// The intent's exact graph and executable closure are absent locally.
    #[error("Agent admission graph is unavailable in the executable registry")]
    ExecutableGraphUnavailable,
    /// The Agent input contract and graph input contract differ.
    #[error("Agent input schema does not match the executable graph input schema")]
    GraphInputSchemaMismatch,
    /// The Agent output contract and graph terminal contract differ.
    #[error("Agent output schema does not match the executable graph output schema")]
    GraphOutputSchemaMismatch,
    /// The typed request failed its exact local input schema.
    #[error("Agent admission input schema validation failed: {source}")]
    InputSchema {
        /// Closed schema result.
        #[source]
        source: GraphSchemaValidationError,
    },
    /// Authorization evidence failed its exact local schema.
    #[error("Agent admission authorization evidence validation failed: {source}")]
    AuthoritySchema {
        /// Closed schema result.
        #[source]
        source: GraphSchemaValidationError,
    },
    /// Initial graph state failed its exact local schema.
    #[error("Agent admission initial state validation failed: {source}")]
    InitialStateSchema {
        /// Closed schema result.
        #[source]
        source: GraphSchemaValidationError,
    },
    /// The framework-owned event data failed its embedded schema.
    #[error("Agent admission standard event schema validation failed: {source}")]
    EventSchema {
        /// Closed schema result.
        #[source]
        source: GraphSchemaValidationError,
    },
    /// Input JSON could not be represented in the canonical audit digest.
    #[error("Agent admission input canonicalization failed: {0}")]
    CanonicalInput(#[source] CanonicalJsonError),
    /// Framework-owned event data unexpectedly exceeded JSON bounds.
    #[error("Agent admission event data is invalid: {0}")]
    EventData(#[source] BoundedJsonError),
    /// The framework-owned stable event kind was malformed.
    #[error("Agent admission event kind is invalid: {0}")]
    EventKind(#[source] JournalEventKindError),
    /// The framework-owned payload envelope was malformed.
    #[error("Agent admission event payload is invalid: {0}")]
    EventPayload(#[source] JournalPayloadError),
    /// The control-plane event intent could not be constructed.
    #[error("Agent admission event intent is invalid: {0}")]
    EventIntent(#[source] JournalIntentError),
    /// The empty-head append could not be constructed.
    #[error("Agent admission journal append is invalid: {0}")]
    JournalAppend(#[source] JournalAppendError),
    /// The initial checkpoint intent could not be constructed.
    #[error("Agent admission initial checkpoint is invalid: {0}")]
    Checkpoint(#[source] CheckpointWriteError),
    /// Durable commit, conflict, or integrity failure.
    #[error(transparent)]
    Store(#[from] StoreError),
}

impl DurableAgentAdmissionError {
    const fn input_schema(source: GraphSchemaValidationError) -> Self {
        Self::InputSchema { source }
    }

    const fn authority_schema(source: GraphSchemaValidationError) -> Self {
        Self::AuthoritySchema { source }
    }

    const fn initial_state_schema(source: GraphSchemaValidationError) -> Self {
        Self::InitialStateSchema { source }
    }

    const fn event_schema(source: GraphSchemaValidationError) -> Self {
        Self::EventSchema { source }
    }
}

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

    #[test]
    fn audit_digest_data_uses_schema_hex_without_algorithm_prefix() {
        let value = digest_hex(Digest::sha256(b"agent admission"));
        assert_eq!(value.len(), Digest::SHA256_LEN * 2);
        assert!(value.bytes().all(|byte| byte.is_ascii_hexdigit()));
        assert!(!value.contains(':'));
    }
}