Skip to main content

stateknot_runtime/
durable_runs.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Public, integrity-verifying access to durable Agent runs and results.
5
6use std::fmt;
7
8use schemars::JsonSchema;
9use serde::{Deserialize, Deserializer, Serialize, de};
10use stateknot_core::{
11    AgentResult, AgentResultProvenance, AgentResultValidationError, AgentSubmissionKey,
12    BudgetUsage, Digest, Failure, FailureCategory, GraphReference, GraphSchemaValidationError,
13    RetryAdvice, RunId, RunRevision, RunStatus, TenantId, Timestamp,
14};
15use stateknot_store_postgres::{
16    AgentAdmissionCommitOutcome, AgentSubmissionCommitOutcome, PostgresStore, StoreError,
17    StoredAgentAdmission,
18};
19use thiserror::Error;
20
21use crate::{
22    DurableAgentAdmission, DurableAgentAdmissionBuildError, DurableAgentAdmissionError,
23    DurableAgentAdmissionRequest, ExecutableGraphRegistry,
24};
25
26/// A closed terminal outcome returned by the durable Agent run facade.
27///
28/// Successful output is the compact, schema-bound [`AgentResult`]. Failure and
29/// cancellation expose only the framework's public-safe [`Failure`] plus exact
30/// terminal accounting; private diagnostics remain outside this value.
31#[derive(Clone, Debug, JsonSchema, Serialize)]
32#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
33#[non_exhaustive]
34pub enum AgentRunTerminalOutcome {
35    /// The Agent committed a verified final output.
36    Succeeded {
37        /// Schema-bound output, artifacts, provenance, and cumulative usage.
38        result: AgentResult,
39    },
40    /// The Agent committed a non-cancellation terminal failure.
41    Failed {
42        /// Public-safe terminal failure occurrence.
43        failure: Failure,
44        /// Authoritative durable completion observation.
45        completed_at: Timestamp,
46        /// Complete cumulative run accounting.
47        usage: BudgetUsage,
48    },
49    /// A previously committed cancellation request reached acknowledgement.
50    Cancelled {
51        /// Public-safe cancellation occurrence.
52        failure: Failure,
53        /// Authoritative durable acknowledgement observation.
54        completed_at: Timestamp,
55        /// Complete cumulative run accounting.
56        usage: BudgetUsage,
57    },
58}
59
60impl AgentRunTerminalOutcome {
61    /// Returns the lifecycle status represented by this terminal value.
62    #[must_use]
63    pub const fn status(&self) -> RunStatus {
64        match self {
65            Self::Succeeded { .. } => RunStatus::Succeeded,
66            Self::Failed { .. } => RunStatus::Failed,
67            Self::Cancelled { .. } => RunStatus::Cancelled,
68        }
69    }
70
71    /// Returns the authoritative durable completion observation.
72    #[must_use]
73    pub const fn completed_at(&self) -> Timestamp {
74        match self {
75            Self::Succeeded { result } => result.completed_at(),
76            Self::Failed { completed_at, .. } | Self::Cancelled { completed_at, .. } => {
77                *completed_at
78            }
79        }
80    }
81
82    /// Returns complete cumulative run accounting.
83    #[must_use]
84    pub const fn usage(&self) -> &BudgetUsage {
85        match self {
86            Self::Succeeded { result } => result.usage(),
87            Self::Failed { usage, .. } | Self::Cancelled { usage, .. } => usage,
88        }
89    }
90
91    /// Returns the successful result, when this is a successful outcome.
92    #[must_use]
93    pub const fn result(&self) -> Option<&AgentResult> {
94        match self {
95            Self::Succeeded { result } => Some(result),
96            Self::Failed { .. } | Self::Cancelled { .. } => None,
97        }
98    }
99
100    /// Returns the public failure for failed or cancelled outcomes.
101    #[must_use]
102    pub const fn failure(&self) -> Option<&Failure> {
103        match self {
104            Self::Succeeded { .. } => None,
105            Self::Failed { failure, .. } | Self::Cancelled { failure, .. } => Some(failure),
106        }
107    }
108}
109
110impl<'de> Deserialize<'de> for AgentRunTerminalOutcome {
111    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
112    where
113        D: Deserializer<'de>,
114    {
115        #[derive(Deserialize)]
116        #[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
117        enum Wire {
118            Succeeded {
119                result: AgentResult,
120            },
121            Failed {
122                failure: Failure,
123                completed_at: Timestamp,
124                usage: BudgetUsage,
125            },
126            Cancelled {
127                failure: Failure,
128                completed_at: Timestamp,
129                usage: BudgetUsage,
130            },
131        }
132
133        let outcome = match Wire::deserialize(deserializer)? {
134            Wire::Succeeded { result } => Self::Succeeded { result },
135            Wire::Failed {
136                failure,
137                completed_at,
138                usage,
139            } => Self::Failed {
140                failure,
141                completed_at,
142                usage,
143            },
144            Wire::Cancelled {
145                failure,
146                completed_at,
147                usage,
148            } => Self::Cancelled {
149                failure,
150                completed_at,
151                usage,
152            },
153        };
154        if !terminal_failure_kind_matches(&outcome) {
155            return Err(de::Error::custom(
156                "Agent run failure does not match its terminal lifecycle path",
157            ));
158        }
159        Ok(outcome)
160    }
161}
162
163fn terminal_failure_kind_matches(outcome: &AgentRunTerminalOutcome) -> bool {
164    match outcome {
165        AgentRunTerminalOutcome::Succeeded { .. } => true,
166        AgentRunTerminalOutcome::Failed { failure, .. } => {
167            failure.category() != FailureCategory::Cancelled
168        }
169        AgentRunTerminalOutcome::Cancelled { failure, .. } => {
170            failure.category() == FailureCategory::Cancelled
171                && failure.retry_advice() == RetryAdvice::Never
172        }
173    }
174}
175
176/// Public, fully revalidated snapshot of one durably admitted Agent run.
177///
178/// The snapshot intentionally excludes authorization evidence, request input,
179/// graph state, leases, scheduler internals, and private diagnostics. Pollers
180/// can use `(run_id, revision)` as a monotonic observation key. A quarantined
181/// run remains visible but must not be represented as executable work.
182#[derive(Clone, JsonSchema, Serialize)]
183#[serde(deny_unknown_fields)]
184pub struct AgentRunSnapshot {
185    provenance: AgentResultProvenance,
186    graph: GraphReference,
187    admission_digest: Digest,
188    admitted_at: Timestamp,
189    revision: RunRevision,
190    status: RunStatus,
191    changed_at: Timestamp,
192    quarantined: bool,
193    #[schemars(required)]
194    outcome: Option<AgentRunTerminalOutcome>,
195}
196
197impl AgentRunSnapshot {
198    #[allow(clippy::too_many_arguments)]
199    fn from_parts(
200        provenance: AgentResultProvenance,
201        graph: GraphReference,
202        admission_digest: Digest,
203        admitted_at: Timestamp,
204        revision: RunRevision,
205        status: RunStatus,
206        changed_at: Timestamp,
207        quarantined: bool,
208        outcome: Option<AgentRunTerminalOutcome>,
209    ) -> Result<Self, AgentRunSnapshotError> {
210        if status == RunStatus::Pending {
211            return Err(AgentRunSnapshotError::PendingAtomicAdmission);
212        }
213        if revision == RunRevision::ZERO {
214            return Err(AgentRunSnapshotError::AdvancedAtZeroRevision);
215        }
216        if changed_at < admitted_at {
217            return Err(AgentRunSnapshotError::ClockRegression);
218        }
219        validate_outcome_shape(status, outcome.as_ref(), &provenance, changed_at)?;
220        Ok(Self {
221            provenance,
222            graph,
223            admission_digest,
224            admitted_at,
225            revision,
226            status,
227            changed_at,
228            quarantined,
229            outcome,
230        })
231    }
232
233    /// Returns trusted tenant, run, thread, invocation, and Agent identity.
234    #[must_use]
235    pub const fn provenance(&self) -> &AgentResultProvenance {
236        &self.provenance
237    }
238
239    /// Returns the immutable graph version pinned at admission.
240    #[must_use]
241    pub const fn graph(&self) -> &GraphReference {
242        &self.graph
243    }
244
245    /// Returns the complete immutable admission checksum.
246    #[must_use]
247    pub const fn admission_digest(&self) -> Digest {
248        self.admission_digest
249    }
250
251    /// Returns the authoritative database admission observation.
252    #[must_use]
253    pub const fn admitted_at(&self) -> Timestamp {
254        self.admitted_at
255    }
256
257    /// Returns the current monotonic lifecycle revision.
258    #[must_use]
259    pub const fn revision(&self) -> RunRevision {
260        self.revision
261    }
262
263    /// Returns the current protocol-neutral lifecycle status.
264    #[must_use]
265    pub const fn status(&self) -> RunStatus {
266        self.status
267    }
268
269    /// Returns the latest committed lifecycle observation.
270    #[must_use]
271    pub const fn changed_at(&self) -> Timestamp {
272        self.changed_at
273    }
274
275    /// Returns whether integrity or operator policy removed this run from execution.
276    #[must_use]
277    pub const fn is_quarantined(&self) -> bool {
278        self.quarantined
279    }
280
281    /// Returns a terminal outcome only after one has durably committed.
282    #[must_use]
283    pub const fn outcome(&self) -> Option<&AgentRunTerminalOutcome> {
284        self.outcome.as_ref()
285    }
286}
287
288impl fmt::Debug for AgentRunSnapshot {
289    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
290        formatter
291            .debug_struct("AgentRunSnapshot")
292            .field("provenance", &self.provenance)
293            .field("graph", &self.graph)
294            .field("admission_digest", &self.admission_digest)
295            .field("admitted_at", &self.admitted_at)
296            .field("revision", &self.revision)
297            .field("status", &self.status)
298            .field("changed_at", &self.changed_at)
299            .field("quarantined", &self.quarantined)
300            .field("has_outcome", &self.outcome.is_some())
301            .finish_non_exhaustive()
302    }
303}
304
305impl<'de> Deserialize<'de> for AgentRunSnapshot {
306    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
307    where
308        D: Deserializer<'de>,
309    {
310        #[derive(Deserialize)]
311        #[serde(deny_unknown_fields)]
312        struct Wire {
313            provenance: AgentResultProvenance,
314            graph: GraphReference,
315            admission_digest: Digest,
316            admitted_at: Timestamp,
317            revision: RunRevision,
318            status: RunStatus,
319            changed_at: Timestamp,
320            quarantined: bool,
321            #[serde(deserialize_with = "deserialize_nullable_outcome")]
322            outcome: Option<AgentRunTerminalOutcome>,
323        }
324
325        let wire = Wire::deserialize(deserializer)?;
326        Self::from_parts(
327            wire.provenance,
328            wire.graph,
329            wire.admission_digest,
330            wire.admitted_at,
331            wire.revision,
332            wire.status,
333            wire.changed_at,
334            wire.quarantined,
335            wire.outcome,
336        )
337        .map_err(de::Error::custom)
338    }
339}
340
341fn deserialize_nullable_outcome<'de, D>(
342    deserializer: D,
343) -> Result<Option<AgentRunTerminalOutcome>, D::Error>
344where
345    D: Deserializer<'de>,
346{
347    Option::<AgentRunTerminalOutcome>::deserialize(deserializer)
348}
349
350fn validate_outcome_shape(
351    status: RunStatus,
352    outcome: Option<&AgentRunTerminalOutcome>,
353    provenance: &AgentResultProvenance,
354    changed_at: Timestamp,
355) -> Result<(), AgentRunSnapshotError> {
356    match (status.is_terminal(), outcome) {
357        (false, None) => return Ok(()),
358        (true, Some(outcome)) if outcome.status() == status => {
359            if outcome.completed_at() != changed_at {
360                return Err(AgentRunSnapshotError::CompletionTimeMismatch);
361            }
362            if !terminal_failure_kind_matches(outcome) {
363                return Err(AgentRunSnapshotError::FailureKindMismatch);
364            }
365            if let Some(result) = outcome.result() {
366                if result.provenance() != provenance {
367                    return Err(AgentRunSnapshotError::ResultProvenanceMismatch);
368                }
369            }
370            return Ok(());
371        }
372        _ => {}
373    }
374    Err(AgentRunSnapshotError::OutcomeStatusMismatch)
375}
376
377/// Invalid public Agent run snapshot shape.
378#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
379#[non_exhaustive]
380pub enum AgentRunSnapshotError {
381    /// Atomic Agent admission cannot expose its internal pending precursor.
382    #[error("atomic Agent admission cannot expose a pending lifecycle")]
383    PendingAtomicAdmission,
384    /// Every visible atomic Agent run has advanced past revision zero.
385    #[error("visible Agent lifecycle cannot remain at revision zero")]
386    AdvancedAtZeroRevision,
387    /// A lifecycle observation preceded admission.
388    #[error("Agent run change observation precedes admission")]
389    ClockRegression,
390    /// Terminal status and outcome presence or kind differed.
391    #[error("Agent run terminal outcome does not match lifecycle status")]
392    OutcomeStatusMismatch,
393    /// The terminal outcome observation differed from lifecycle time.
394    #[error("Agent run terminal completion does not match lifecycle time")]
395    CompletionTimeMismatch,
396    /// A successful result named another trusted run identity.
397    #[error("Agent run result provenance does not match lifecycle provenance")]
398    ResultProvenanceMismatch,
399    /// Failure category or retry semantics did not match its terminal path.
400    #[error("Agent run failure does not match its terminal lifecycle path")]
401    FailureKindMismatch,
402}
403
404/// Result of public-facade Agent admission.
405#[derive(Clone, Debug)]
406#[non_exhaustive]
407pub enum AgentRunAdmissionOutcome {
408    /// A new atomic Agent run committed.
409    Committed(AgentRunSnapshot),
410    /// The exact retained admission or ingress-keyed submission had already committed.
411    Idempotent(AgentRunSnapshot),
412}
413
414impl AgentRunAdmissionOutcome {
415    /// Returns the public verified run snapshot in either case.
416    #[must_use]
417    pub const fn snapshot(&self) -> &AgentRunSnapshot {
418        match self {
419            Self::Committed(snapshot) | Self::Idempotent(snapshot) => snapshot,
420        }
421    }
422}
423
424/// Public durable Agent admission and run/result query facade.
425///
426/// This value keeps the exact executable/schema deployment registry beside the
427/// store. Every read reloads the immutable admission and current lifecycle in
428/// one repeatable-read snapshot, then revalidates request, authority, initial
429/// state, audit event, graph closure, terminal output, provenance, and budget
430/// before returning a public value.
431#[derive(Clone)]
432pub struct DurableAgentRuns {
433    admission: DurableAgentAdmission,
434    store: PostgresStore,
435    registry: ExecutableGraphRegistry,
436}
437
438impl DurableAgentRuns {
439    pub(crate) const fn executable_registry(&self) -> &ExecutableGraphRegistry {
440        &self.registry
441    }
442
443    /// Binds the durability provider to one immutable executable deployment.
444    ///
445    /// # Errors
446    ///
447    /// Rejects an unavailable or malformed standard Agent-admission schema.
448    pub fn new(
449        store: PostgresStore,
450        registry: ExecutableGraphRegistry,
451    ) -> Result<Self, DurableAgentRunsBuildError> {
452        let admission = DurableAgentAdmission::new(store.clone(), registry.clone())?;
453        Ok(Self {
454            admission,
455            store,
456            registry,
457        })
458    }
459
460    /// Validates, atomically admits, and returns a public run snapshot.
461    ///
462    /// Ambiguous retries must retain the exact [`DurableAgentAdmissionRequest`].
463    /// Ingress idempotency-key allocation is deliberately a stronger boundary
464    /// and is not emulated with process-local memory by this method.
465    ///
466    /// # Errors
467    ///
468    /// Returns a closed admission, storage, deployment, schema, integrity, or
469    /// terminal-accounting failure.
470    pub async fn admit(
471        &self,
472        request: DurableAgentAdmissionRequest,
473    ) -> Result<AgentRunAdmissionOutcome, DurableAgentRunsError> {
474        let outcome = self.admission.admit(request).await?;
475        let committed = match &outcome {
476            AgentAdmissionCommitOutcome::Committed(_) => true,
477            AgentAdmissionCommitOutcome::Idempotent(_) => false,
478            _ => return Err(DurableAgentRunsError::InvalidDurableSnapshot),
479        };
480        let snapshot = self.snapshot(outcome.stored())?;
481        Ok(if committed {
482            AgentRunAdmissionOutcome::Committed(snapshot)
483        } else {
484            AgentRunAdmissionOutcome::Idempotent(snapshot)
485        })
486    }
487
488    /// Submits one candidate under a durable tenant-scoped idempotency key.
489    ///
490    /// Unlike [`Self::admit`], callers do not retain candidate IDs after an
491    /// ambiguous response. They recreate the same caller content with the same
492    /// key; the provider returns the originally selected run even if the new
493    /// request contains a fresh [`crate::AgentRunIds`] bundle.
494    ///
495    /// # Errors
496    ///
497    /// Reusing a key for changed content returns a durable conflict. Deployment,
498    /// schema, integrity, and database failures remain closed and payload-safe.
499    pub async fn submit(
500        &self,
501        key: &AgentSubmissionKey,
502        request: DurableAgentAdmissionRequest,
503    ) -> Result<AgentRunAdmissionOutcome, DurableAgentRunsError> {
504        let outcome = self.admission.submit(key, request).await?;
505        let committed = match &outcome {
506            AgentSubmissionCommitOutcome::Committed(_) => true,
507            AgentSubmissionCommitOutcome::Idempotent(_) => false,
508            _ => return Err(DurableAgentRunsError::InvalidDurableSnapshot),
509        };
510        let snapshot = self.snapshot(outcome.stored().admission())?;
511        Ok(if committed {
512            AgentRunAdmissionOutcome::Committed(snapshot)
513        } else {
514            AgentRunAdmissionOutcome::Idempotent(snapshot)
515        })
516    }
517
518    /// Loads one tenant-scoped Agent run and fully revalidates its public view.
519    ///
520    /// Calling services remain responsible for authenticating and authorizing
521    /// the tenant/run lookup before invoking this trusted server-side method.
522    ///
523    /// # Errors
524    ///
525    /// Returns not-found, corruption, deployment drift, schema rejection,
526    /// invalid terminal accounting, or database failures.
527    pub async fn load(
528        &self,
529        tenant_id: &TenantId,
530        run_id: RunId,
531    ) -> Result<AgentRunSnapshot, DurableAgentRunsError> {
532        let stored = self.store.load_agent_admission(tenant_id, run_id).await?;
533        self.snapshot(&stored)
534    }
535
536    /// Resolves an ingress key and loads its current fully verified public run.
537    ///
538    /// # Errors
539    ///
540    /// Returns key-not-found, corruption, deployment drift, schema rejection,
541    /// invalid terminal result, or database failures.
542    pub async fn load_by_key(
543        &self,
544        tenant_id: &TenantId,
545        key: &AgentSubmissionKey,
546    ) -> Result<AgentRunSnapshot, DurableAgentRunsError> {
547        let stored = self.store.load_agent_submission(tenant_id, key).await?;
548        self.snapshot(stored.admission())
549    }
550
551    fn snapshot(
552        &self,
553        stored: &StoredAgentAdmission,
554    ) -> Result<AgentRunSnapshot, DurableAgentRunsError> {
555        let admission = stored.admission();
556        let intent = admission.intent();
557        let executable = self
558            .registry
559            .resolve(intent.graph())
560            .ok_or(DurableAgentRunsError::ExecutableGraphUnavailable)?;
561        if intent.descriptor().input_schema() != executable.graph().input_schema() {
562            return Err(DurableAgentRunsError::GraphInputSchemaMismatch);
563        }
564        if intent.descriptor().output_schema() != executable.graph().output_schema() {
565            return Err(DurableAgentRunsError::GraphOutputSchemaMismatch);
566        }
567
568        self.registry
569            .schemas()
570            .validate_bounded(intent.request().input_schema(), intent.request().input())
571            .map_err(DurableAgentRunsError::input_schema)?;
572        self.registry
573            .schemas()
574            .validate_bounded(
575                intent.authority().evidence().schema(),
576                intent.authority().evidence().data(),
577            )
578            .map_err(DurableAgentRunsError::authority_schema)?;
579        self.registry
580            .schemas()
581            .validate_bounded(
582                stored.checkpoint().state().schema(),
583                stored.checkpoint().state().data(),
584            )
585            .map_err(DurableAgentRunsError::initial_state_schema)?;
586
587        let event_schema = self.admission.event_schema();
588        if stored.event().payload().schema() != event_schema {
589            return Err(DurableAgentRunsError::AdmissionEventSchemaMismatch);
590        }
591        self.registry
592            .schemas()
593            .validate_bounded(event_schema, stored.event().payload().data())
594            .map_err(DurableAgentRunsError::event_schema)?;
595
596        let run = stored.run();
597        let lifecycle = run.lifecycle();
598        let outcome = match lifecycle.status() {
599            RunStatus::Succeeded => {
600                let result = lifecycle
601                    .result()
602                    .cloned()
603                    .ok_or(DurableAgentRunsError::InvalidDurableSnapshot)?;
604                result
605                    .validate_for(
606                        intent.provenance(),
607                        intent.request(),
608                        intent.descriptor(),
609                        intent.budget(),
610                    )
611                    .map_err(DurableAgentRunsError::result_validation)?;
612                self.registry
613                    .schemas()
614                    .validate_bounded(result.output_schema(), result.output())
615                    .map_err(DurableAgentRunsError::output_schema)?;
616                Some(AgentRunTerminalOutcome::Succeeded { result })
617            }
618            RunStatus::Failed | RunStatus::Cancelled => {
619                let failure = lifecycle
620                    .terminal_failure()
621                    .cloned()
622                    .ok_or(DurableAgentRunsError::InvalidDurableSnapshot)?;
623                let usage = lifecycle
624                    .terminal_usage()
625                    .cloned()
626                    .ok_or(DurableAgentRunsError::InvalidDurableSnapshot)?;
627                Some(if lifecycle.status() == RunStatus::Failed {
628                    AgentRunTerminalOutcome::Failed {
629                        failure,
630                        completed_at: lifecycle.changed_at(),
631                        usage,
632                    }
633                } else {
634                    AgentRunTerminalOutcome::Cancelled {
635                        failure,
636                        completed_at: lifecycle.changed_at(),
637                        usage,
638                    }
639                })
640            }
641            RunStatus::Pending
642            | RunStatus::Active
643            | RunStatus::Waiting
644            | RunStatus::CancellationRequested => None,
645        };
646
647        AgentRunSnapshot::from_parts(
648            lifecycle.provenance().clone(),
649            intent.graph().clone(),
650            admission.digest(),
651            admission.admitted_at(),
652            lifecycle.revision(),
653            lifecycle.status(),
654            lifecycle.changed_at(),
655            run.is_quarantined(),
656            outcome,
657        )
658        .map_err(DurableAgentRunsError::Snapshot)
659    }
660}
661
662impl fmt::Debug for DurableAgentRuns {
663    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
664        formatter
665            .debug_struct("DurableAgentRuns")
666            .field("registry", &self.registry)
667            .finish_non_exhaustive()
668    }
669}
670
671/// Startup failure for the public durable Agent run facade.
672#[derive(Clone, Debug, Eq, Error, PartialEq)]
673#[non_exhaustive]
674pub enum DurableAgentRunsBuildError {
675    /// The underlying atomic admission facade could not bind its standard schema.
676    #[error(transparent)]
677    Admission(#[from] DurableAgentAdmissionBuildError),
678}
679
680/// Payload-redacted failure from public durable Agent admission or reads.
681#[derive(Debug, Error)]
682#[non_exhaustive]
683pub enum DurableAgentRunsError {
684    /// Atomic Agent admission failed.
685    #[error(transparent)]
686    Admission(#[from] DurableAgentAdmissionError),
687    /// Durable storage or integrity verification failed.
688    #[error(transparent)]
689    Store(#[from] StoreError),
690    /// The exact graph and executable closure are absent from this deployment.
691    #[error("Agent run graph is unavailable in the executable registry")]
692    ExecutableGraphUnavailable,
693    /// The Agent and executable graph disagree about input schema.
694    #[error("Agent input schema does not match the executable graph input schema")]
695    GraphInputSchemaMismatch,
696    /// The Agent and executable graph disagree about output schema.
697    #[error("Agent output schema does not match the executable graph output schema")]
698    GraphOutputSchemaMismatch,
699    /// Durable request input no longer passes its pinned schema.
700    #[error("durable Agent input schema validation failed: {source}")]
701    InputSchema {
702        /// Closed schema validation result.
703        #[source]
704        source: GraphSchemaValidationError,
705    },
706    /// Durable authorization evidence no longer passes its pinned schema.
707    #[error("durable Agent authorization evidence validation failed: {source}")]
708    AuthoritySchema {
709        /// Closed schema validation result.
710        #[source]
711        source: GraphSchemaValidationError,
712    },
713    /// Durable initial state no longer passes its pinned schema.
714    #[error("durable Agent initial state schema validation failed: {source}")]
715    InitialStateSchema {
716        /// Closed schema validation result.
717        #[source]
718        source: GraphSchemaValidationError,
719    },
720    /// The immutable first event named another schema version.
721    #[error("durable Agent admission event schema does not match this runtime release")]
722    AdmissionEventSchemaMismatch,
723    /// Durable admission audit data no longer passes the standard schema.
724    #[error("durable Agent admission event schema validation failed: {source}")]
725    EventSchema {
726        /// Closed schema validation result.
727        #[source]
728        source: GraphSchemaValidationError,
729    },
730    /// A successful terminal output no longer passes its pinned schema.
731    #[error("durable Agent result schema validation failed: {source}")]
732    OutputSchema {
733        /// Closed schema validation result.
734        #[source]
735        source: GraphSchemaValidationError,
736    },
737    /// A successful result failed provenance, request, schema, or accounting binding.
738    #[error("durable Agent result integrity validation failed: {source}")]
739    ResultValidation {
740        /// Core result validation failure.
741        #[source]
742        source: AgentResultValidationError,
743    },
744    /// Durable facts formed a relationship the public snapshot cannot represent.
745    #[error("durable Agent run snapshot is inconsistent")]
746    InvalidDurableSnapshot,
747    /// Public snapshot fields formed an impossible lifecycle view.
748    #[error(transparent)]
749    Snapshot(#[from] AgentRunSnapshotError),
750}
751
752impl DurableAgentRunsError {
753    const fn input_schema(source: GraphSchemaValidationError) -> Self {
754        Self::InputSchema { source }
755    }
756
757    const fn authority_schema(source: GraphSchemaValidationError) -> Self {
758        Self::AuthoritySchema { source }
759    }
760
761    const fn initial_state_schema(source: GraphSchemaValidationError) -> Self {
762        Self::InitialStateSchema { source }
763    }
764
765    const fn event_schema(source: GraphSchemaValidationError) -> Self {
766        Self::EventSchema { source }
767    }
768
769    const fn output_schema(source: GraphSchemaValidationError) -> Self {
770        Self::OutputSchema { source }
771    }
772
773    const fn result_validation(source: AgentResultValidationError) -> Self {
774        Self::ResultValidation { source }
775    }
776}
777
778#[cfg(test)]
779mod tests {
780    use super::*;
781
782    #[test]
783    fn terminal_status_requires_the_matching_outcome_kind() {
784        assert_eq!(
785            validate_outcome_shape(
786                RunStatus::Succeeded,
787                None,
788                &test_provenance(),
789                test_timestamp(),
790            ),
791            Err(AgentRunSnapshotError::OutcomeStatusMismatch)
792        );
793        assert!(
794            validate_outcome_shape(
795                RunStatus::Active,
796                None,
797                &test_provenance(),
798                test_timestamp(),
799            )
800            .is_ok()
801        );
802    }
803
804    #[test]
805    fn snapshot_schema_is_a_closed_response_object() {
806        let schema = serde_json::to_value(schemars::schema_for!(AgentRunSnapshot)).unwrap();
807        assert_eq!(
808            schema["additionalProperties"],
809            serde_json::Value::Bool(false)
810        );
811        assert_eq!(schema["required"].as_array().map(Vec::len), Some(9));
812    }
813
814    #[test]
815    fn terminal_failure_kind_remains_bound_to_its_lifecycle_path() {
816        use stateknot_core::{FailureCode, FailureId, FailureMessage, FailureOrigin};
817
818        let failure = Failure::new(
819            FailureId::generate(),
820            FailureCategory::Internal,
821            FailureCode::new("agent.public_failed").unwrap(),
822            FailureOrigin::new("test.public-run").unwrap(),
823            FailureMessage::new("The public run failed safely.").unwrap(),
824            RetryAdvice::Never,
825        )
826        .unwrap();
827        let outcome = AgentRunTerminalOutcome::Cancelled {
828            failure,
829            completed_at: test_timestamp(),
830            usage: BudgetUsage::zero(),
831        };
832        assert_eq!(
833            validate_outcome_shape(
834                RunStatus::Cancelled,
835                Some(&outcome),
836                &test_provenance(),
837                test_timestamp(),
838            ),
839            Err(AgentRunSnapshotError::FailureKindMismatch)
840        );
841        assert!(
842            serde_json::from_value::<AgentRunTerminalOutcome>(
843                serde_json::to_value(&outcome).unwrap()
844            )
845            .is_err()
846        );
847    }
848
849    fn test_provenance() -> AgentResultProvenance {
850        use stateknot_core::{
851            CapabilityIdentity, CapabilityName, CapabilityReference, IssuerId, PrincipalIdentity,
852            SubjectId, Version,
853        };
854
855        AgentResultProvenance::new(
856            TenantId::new("tenant-public-run").unwrap(),
857            RunId::generate(),
858            stateknot_core::ThreadId::generate(),
859            stateknot_core::InvocationId::generate(),
860            CapabilityIdentity::new(
861                PrincipalIdentity::new(
862                    IssuerId::new("https://issuer.example.com").unwrap(),
863                    SubjectId::new("public-run-tests").unwrap(),
864                ),
865                CapabilityReference::new(
866                    CapabilityName::new("agent.public-run").unwrap(),
867                    Version::new(1, 0, 0),
868                ),
869            ),
870        )
871    }
872
873    fn test_timestamp() -> Timestamp {
874        "2026-09-01T00:00:00.000000Z".parse().unwrap()
875    }
876}