Skip to main content

stateknot_core/
agent_runtime.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Runtime-neutral agent admission requests and successful terminal results.
5
6use std::fmt;
7
8use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
9use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
10use thiserror::Error;
11
12use crate::{
13    AgentDescriptor, ArtifactRef, BoundedJson, BudgetEvaluationError, BudgetLimits,
14    BudgetResolutionError, BudgetUsage, ByteCount, CapabilityIdentity, CapabilityLifecycleState,
15    InvocationId, MAX_BUDGET_LAYERS, ResolvedBudget, RunId, SchemaReference, TenantId, ThreadId,
16    Timestamp,
17};
18
19/// Schema-bound input and request-local budget constraints for one agent run.
20///
21/// A request deliberately contains no tenant, run, thread, or invocation ID;
22/// those trusted identifiers are assigned by run admission. `budget_limits` is
23/// another restrictive layer and can never widen system, tenant, policy, or
24/// immutable agent limits. Input JSON is structurally bounded here, while a
25/// trusted local schema registry performs digest-pinned schema evaluation.
26#[derive(Clone, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
27#[serde(deny_unknown_fields)]
28pub struct AgentRequest {
29    input_schema: SchemaReference,
30    input: BoundedJson,
31    budget_limits: BudgetLimits,
32}
33
34impl AgentRequest {
35    /// Constructs an intrinsically bounded agent request.
36    #[must_use]
37    pub const fn new(
38        input_schema: SchemaReference,
39        input: BoundedJson,
40        budget_limits: BudgetLimits,
41    ) -> Self {
42        Self {
43            input_schema,
44            input,
45            budget_limits,
46        }
47    }
48
49    /// Returns the exact input schema identity.
50    #[must_use]
51    pub const fn input_schema(&self) -> &SchemaReference {
52        &self.input_schema
53    }
54
55    /// Returns the bounded input without permitting mutation.
56    #[must_use]
57    pub const fn input(&self) -> &BoundedJson {
58        &self.input
59    }
60
61    /// Returns the optional request-local budget layer.
62    #[must_use]
63    pub const fn budget_limits(&self) -> &BudgetLimits {
64        &self.budget_limits
65    }
66
67    /// Consumes this request into schema, input, and budget components.
68    #[must_use]
69    pub fn into_parts(self) -> (SchemaReference, BoundedJson, BudgetLimits) {
70        (self.input_schema, self.input, self.budget_limits)
71    }
72
73    /// Validates a new invocation and resolves its complete finite budget.
74    ///
75    /// `base_budget_layers` contains only the already selected system, tenant,
76    /// and policy layers. This method appends the immutable agent layer and this
77    /// request layer, evaluates the supplied durable clock observation, and
78    /// checks the materialized input against the resulting byte ceiling.
79    /// Deprecated agents remain invocable; retired agents remain readable for
80    /// recovery but cannot be admitted as new work.
81    ///
82    /// Digest-pinned JSON Schema evaluation remains a separate trusted-registry
83    /// operation and must complete before the returned budget is committed.
84    ///
85    /// # Errors
86    ///
87    /// Returns [`AgentRequestValidationError`] for retirement, schema
88    /// substitution, excessive layer count, incomplete/invalid budget
89    /// resolution, an already expired deadline, or oversized input.
90    pub fn resolve_for(
91        &self,
92        descriptor: &AgentDescriptor,
93        base_budget_layers: &[BudgetLimits],
94        observed_at: Timestamp,
95    ) -> Result<ResolvedBudget, AgentRequestValidationError> {
96        if descriptor.metadata().lifecycle().state() == CapabilityLifecycleState::Retired {
97            return Err(AgentRequestValidationError::RetiredAgent {
98                identity: Box::new(descriptor.metadata().identity().clone()),
99            });
100        }
101
102        self.validate_schema_for(descriptor)?;
103
104        let additional_layers = usize::from(!descriptor.budget_limits().is_empty())
105            + usize::from(!self.budget_limits.is_empty());
106        let actual_layers = base_budget_layers
107            .len()
108            .checked_add(additional_layers)
109            .unwrap_or(usize::MAX);
110        if actual_layers > MAX_BUDGET_LAYERS {
111            return Err(AgentRequestValidationError::TooManyBudgetLayers {
112                maximum: MAX_BUDGET_LAYERS,
113                actual: actual_layers,
114            });
115        }
116
117        let mut layers = Vec::with_capacity(actual_layers);
118        layers.extend_from_slice(base_budget_layers);
119        if !descriptor.budget_limits().is_empty() {
120            layers.push(descriptor.budget_limits().clone());
121        }
122        if !self.budget_limits.is_empty() {
123            layers.push(self.budget_limits.clone());
124        }
125
126        let budget = ResolvedBudget::resolve(&layers)
127            .map_err(AgentRequestValidationError::budget_resolution)?;
128        budget
129            .remaining(&BudgetUsage::zero(), observed_at)
130            .map_err(AgentRequestValidationError::budget_evaluation)?;
131        self.validate_with_resolved_budget(descriptor, &budget)?;
132        Ok(budget)
133    }
134
135    /// Revalidates schema identity and input bytes against a trusted budget.
136    ///
137    /// This is intended for recovery after the exact resolved budget was
138    /// durably snapshotted by [`Self::resolve_for`]. It intentionally permits a
139    /// now-retired descriptor because retirement cannot invalidate old runs.
140    ///
141    /// # Errors
142    ///
143    /// Returns [`AgentRequestValidationError`] for schema substitution or input
144    /// beyond the snapshotted budget ceiling.
145    pub fn validate_with_resolved_budget(
146        &self,
147        descriptor: &AgentDescriptor,
148        budget: &ResolvedBudget,
149    ) -> Result<(), AgentRequestValidationError> {
150        self.validate_schema_for(descriptor)?;
151        let actual = byte_count_from_usize(self.input.stats().compact_bytes());
152        let maximum = budget.input_bytes();
153        if actual > maximum {
154            return Err(AgentRequestValidationError::InputLimitExceeded { maximum, actual });
155        }
156        Ok(())
157    }
158
159    fn validate_schema_for(
160        &self,
161        descriptor: &AgentDescriptor,
162    ) -> Result<(), AgentRequestValidationError> {
163        if &self.input_schema != descriptor.input_schema() {
164            return Err(AgentRequestValidationError::SchemaMismatch {
165                expected: Box::new(descriptor.input_schema().clone()),
166                actual: Box::new(self.input_schema.clone()),
167            });
168        }
169        Ok(())
170    }
171}
172
173impl fmt::Debug for AgentRequest {
174    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
175        formatter
176            .debug_struct("AgentRequest")
177            .field("input_schema", &self.input_schema)
178            .field("input_stats", &self.input.stats())
179            .field("has_budget_limits", &!self.budget_limits.is_empty())
180            .finish_non_exhaustive()
181    }
182}
183
184/// Invalid relationship between an agent request and an admission snapshot.
185#[derive(Clone, Debug, Eq, Error, PartialEq)]
186#[non_exhaustive]
187pub enum AgentRequestValidationError {
188    /// Historical descriptors cannot be selected for new work.
189    #[error("agent {identity:?} is retired and cannot accept a new request")]
190    RetiredAgent {
191        /// Retired owner-qualified agent identity.
192        identity: Box<CapabilityIdentity>,
193    },
194    /// Input named a schema other than the descriptor snapshot.
195    #[error("agent input schema {actual:?} does not match descriptor {expected:?}")]
196    SchemaMismatch {
197        /// Exact descriptor input schema.
198        expected: Box<SchemaReference>,
199        /// Rejected request input schema.
200        actual: Box<SchemaReference>,
201    },
202    /// Base, agent, and request layers exceeded the resolution hard bound.
203    #[error("agent admission has {actual} budget layers; maximum is {maximum}")]
204    TooManyBudgetLayers {
205        /// Core layer-count ceiling.
206        maximum: usize,
207        /// Total non-empty layers that would be resolved.
208        actual: usize,
209    },
210    /// Layered budget resolution failed closed.
211    #[error("agent request budget resolution failed: {source}")]
212    BudgetResolution {
213        /// Underlying finite-budget failure.
214        #[source]
215        source: BudgetResolutionError,
216    },
217    /// The resolved budget was already exhausted at admission.
218    #[error("agent request budget is not admissible: {source}")]
219    BudgetEvaluation {
220        /// Underlying deadline or zero-usage evaluation failure.
221        #[source]
222        source: BudgetEvaluationError,
223    },
224    /// Compact request input exceeded the resolved run ceiling.
225    #[error("agent input is {actual} bytes; resolved budget maximum is {maximum}")]
226    InputLimitExceeded {
227        /// Resolved cumulative input-byte ceiling.
228        maximum: ByteCount,
229        /// Exact compact request size.
230        actual: ByteCount,
231    },
232}
233
234impl AgentRequestValidationError {
235    const fn budget_resolution(source: BudgetResolutionError) -> Self {
236        Self::BudgetResolution { source }
237    }
238
239    const fn budget_evaluation(source: BudgetEvaluationError) -> Self {
240        Self::BudgetEvaluation { source }
241    }
242}
243
244/// Trusted execution identity attached to one successful agent result.
245#[derive(Clone, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
246#[serde(deny_unknown_fields)]
247pub struct AgentResultProvenance {
248    tenant_id: TenantId,
249    run_id: RunId,
250    thread_id: ThreadId,
251    invocation_id: InvocationId,
252    agent: CapabilityIdentity,
253}
254
255impl AgentResultProvenance {
256    /// Constructs exact agent-invocation provenance from trusted admission IDs.
257    #[must_use]
258    pub const fn new(
259        tenant_id: TenantId,
260        run_id: RunId,
261        thread_id: ThreadId,
262        invocation_id: InvocationId,
263        agent: CapabilityIdentity,
264    ) -> Self {
265        Self {
266            tenant_id,
267            run_id,
268            thread_id,
269            invocation_id,
270            agent,
271        }
272    }
273
274    /// Constructs provenance bound to an immutable agent descriptor.
275    #[must_use]
276    pub fn for_agent(
277        tenant_id: TenantId,
278        run_id: RunId,
279        thread_id: ThreadId,
280        invocation_id: InvocationId,
281        descriptor: &AgentDescriptor,
282    ) -> Self {
283        Self::new(
284            tenant_id,
285            run_id,
286            thread_id,
287            invocation_id,
288            descriptor.metadata().identity().clone(),
289        )
290    }
291
292    /// Returns the tenant boundary for storage and authorization.
293    #[must_use]
294    pub const fn tenant_id(&self) -> &TenantId {
295        &self.tenant_id
296    }
297
298    /// Returns the enclosing durable run identifier.
299    #[must_use]
300    pub const fn run_id(&self) -> RunId {
301        self.run_id
302    }
303
304    /// Returns the enclosing conversation thread identifier.
305    #[must_use]
306    pub const fn thread_id(&self) -> ThreadId {
307        self.thread_id
308    }
309
310    /// Returns the logical root or nested-agent invocation identifier.
311    #[must_use]
312    pub const fn invocation_id(&self) -> InvocationId {
313        self.invocation_id
314    }
315
316    /// Returns the exact owner-qualified agent version.
317    #[must_use]
318    pub const fn agent(&self) -> &CapabilityIdentity {
319        &self.agent
320    }
321
322    /// Rebinds this provenance to an immutable descriptor snapshot.
323    ///
324    /// # Errors
325    ///
326    /// Returns [`AgentResultProvenanceError`] when the agent identity differs.
327    pub fn validate_for(
328        &self,
329        descriptor: &AgentDescriptor,
330    ) -> Result<(), AgentResultProvenanceError> {
331        let expected = descriptor.metadata().identity();
332        if &self.agent != expected {
333            return Err(AgentResultProvenanceError::AgentIdentityMismatch {
334                expected: Box::new(expected.clone()),
335                actual: Box::new(self.agent.clone()),
336            });
337        }
338        Ok(())
339    }
340}
341
342impl fmt::Debug for AgentResultProvenance {
343    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
344        formatter
345            .debug_struct("AgentResultProvenance")
346            .field("tenant_id", &self.tenant_id)
347            .field("run_id", &self.run_id)
348            .field("thread_id", &self.thread_id)
349            .field("invocation_id", &self.invocation_id)
350            .field("agent", &self.agent)
351            .finish_non_exhaustive()
352    }
353}
354
355/// Descriptor-binding failure for trusted agent result provenance.
356#[derive(Clone, Debug, Eq, Error, PartialEq)]
357#[non_exhaustive]
358pub enum AgentResultProvenanceError {
359    /// Provenance named another owner-qualified agent version.
360    #[error("agent result identity {actual:?} does not match descriptor {expected:?}")]
361    AgentIdentityMismatch {
362        /// Exact descriptor identity.
363        expected: Box<CapabilityIdentity>,
364        /// Rejected provenance identity.
365        actual: Box<CapabilityIdentity>,
366    },
367}
368
369/// Canonical bounded final artifact references returned by one agent invocation.
370///
371/// Artifact bytes remain external. Values retain semantic output order while
372/// tenant-qualified identities must be unique. The hard count protects generic
373/// deserialization before a run budget is available; the budget can only
374/// narrow aggregate artifact bytes.
375#[derive(Clone, Default, Eq, PartialEq)]
376pub struct AgentArtifacts {
377    values: Box<[ArtifactRef]>,
378    total_bytes: ByteCount,
379}
380
381impl AgentArtifacts {
382    /// Absolute v1 artifact-reference count for one successful agent result.
383    pub const MAX_LEN: usize = 64;
384
385    /// Constructs an empty final artifact set.
386    #[must_use]
387    pub fn empty() -> Self {
388        Self::default()
389    }
390
391    /// Validates count, identity uniqueness, and byte arithmetic.
392    ///
393    /// # Errors
394    ///
395    /// Returns [`AgentArtifactsError`] for too many references, duplicate
396    /// tenant-qualified identities, or aggregate byte overflow.
397    pub fn try_new<I>(values: I) -> Result<Self, AgentArtifactsError>
398    where
399        I: IntoIterator<Item = ArtifactRef>,
400    {
401        let mut collected = Vec::new();
402        let mut total_bytes = ByteCount::ZERO;
403        for value in values {
404            if collected.len() == Self::MAX_LEN {
405                return Err(AgentArtifactsError::TooMany {
406                    maximum: Self::MAX_LEN,
407                    actual: Self::MAX_LEN + 1,
408                });
409            }
410            if collected
411                .iter()
412                .any(|existing: &ArtifactRef| existing.identity() == value.identity())
413            {
414                return Err(AgentArtifactsError::DuplicateIdentity);
415            }
416            total_bytes = total_bytes
417                .checked_add(value.representation().byte_length())
418                .ok_or(AgentArtifactsError::TotalBytesOverflow)?;
419            collected.push(value);
420        }
421        Ok(Self {
422            values: collected.into_boxed_slice(),
423            total_bytes,
424        })
425    }
426
427    /// Returns the number of final artifact references.
428    #[must_use]
429    pub const fn len(&self) -> usize {
430        self.values.len()
431    }
432
433    /// Returns whether the result has no final artifact references.
434    #[must_use]
435    pub const fn is_empty(&self) -> bool {
436        self.values.is_empty()
437    }
438
439    /// Returns checked aggregate immutable representation bytes.
440    #[must_use]
441    pub const fn total_bytes(&self) -> ByteCount {
442        self.total_bytes
443    }
444
445    /// Iterates in semantic result order.
446    pub fn iter(&self) -> impl ExactSizeIterator<Item = &ArtifactRef> {
447        self.values.iter()
448    }
449
450    /// Consumes this set into ordered artifact references.
451    #[must_use]
452    pub fn into_vec(self) -> Vec<ArtifactRef> {
453        self.values.into_vec()
454    }
455}
456
457impl fmt::Debug for AgentArtifacts {
458    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
459        formatter
460            .debug_struct("AgentArtifacts")
461            .field("count", &self.len())
462            .field("total_bytes", &self.total_bytes)
463            .finish_non_exhaustive()
464    }
465}
466
467impl Serialize for AgentArtifacts {
468    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
469    where
470        S: Serializer,
471    {
472        self.values.serialize(serializer)
473    }
474}
475
476impl<'de> Deserialize<'de> for AgentArtifacts {
477    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
478    where
479        D: Deserializer<'de>,
480    {
481        deserializer.deserialize_seq(AgentArtifactsVisitor)
482    }
483}
484
485struct AgentArtifactsVisitor;
486
487impl<'de> de::Visitor<'de> for AgentArtifactsVisitor {
488    type Value = AgentArtifacts;
489
490    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
491        write!(
492            formatter,
493            "at most {} unique final agent artifact references",
494            AgentArtifacts::MAX_LEN
495        )
496    }
497
498    fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
499    where
500        A: de::SeqAccess<'de>,
501    {
502        let mut values = Vec::with_capacity(
503            sequence
504                .size_hint()
505                .unwrap_or_default()
506                .min(AgentArtifacts::MAX_LEN),
507        );
508        while let Some(value) = sequence.next_element::<ArtifactRef>()? {
509            if values.len() == AgentArtifacts::MAX_LEN {
510                return Err(de::Error::custom(AgentArtifactsError::TooMany {
511                    maximum: AgentArtifacts::MAX_LEN,
512                    actual: AgentArtifacts::MAX_LEN + 1,
513                }));
514            }
515            if values
516                .iter()
517                .any(|existing: &ArtifactRef| existing.identity() == value.identity())
518            {
519                return Err(de::Error::custom(AgentArtifactsError::DuplicateIdentity));
520            }
521            values.push(value);
522        }
523        AgentArtifacts::try_new(values).map_err(de::Error::custom)
524    }
525}
526
527impl JsonSchema for AgentArtifacts {
528    fn schema_name() -> std::borrow::Cow<'static, str> {
529        "AgentArtifacts".into()
530    }
531
532    fn schema_id() -> std::borrow::Cow<'static, str> {
533        concat!(module_path!(), "::AgentArtifacts").into()
534    }
535
536    fn json_schema(generator: &mut SchemaGenerator) -> Schema {
537        json_schema!({
538            "type": "array",
539            "items": generator.subschema_for::<ArtifactRef>(),
540            "maxItems": 64,
541            "uniqueItems": true,
542            "description": "Ordered final agent artifact references with unique tenant-qualified identities. Identity uniqueness is enforced at runtime."
543        })
544    }
545}
546
547/// Invalid final artifact collection for one successful agent invocation.
548#[derive(Clone, Debug, Eq, Error, PartialEq)]
549#[non_exhaustive]
550pub enum AgentArtifactsError {
551    /// The global pre-budget artifact count ceiling was exceeded.
552    #[error("agent result has {actual} artifacts; hard maximum is {maximum}")]
553    TooMany {
554        /// Absolute v1 count ceiling.
555        maximum: usize,
556        /// First observed count beyond the ceiling.
557        actual: usize,
558    },
559    /// The same tenant-qualified artifact identity appeared more than once.
560    #[error("agent result artifact identities must be unique")]
561    DuplicateIdentity,
562    /// Aggregate representation byte arithmetic overflowed.
563    #[error("agent result aggregate artifact bytes overflowed")]
564    TotalBytesOverflow,
565}
566
567/// Successful, schema-bound terminal result of one agent invocation.
568///
569/// This compact value does not duplicate model responses, messages, tool
570/// ledgers, approval records, or handoff history; those remain ordered durable
571/// events. Construction validates intrinsic accounting and artifact binding.
572/// Before commit, a runtime must additionally call [`Self::validate_for`] and
573/// validate `output` against the digest-pinned local output schema.
574#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
575#[serde(deny_unknown_fields)]
576pub struct AgentResult {
577    provenance: AgentResultProvenance,
578    completed_at: Timestamp,
579    output_schema: SchemaReference,
580    output: BoundedJson,
581    artifacts: AgentArtifacts,
582    usage: BudgetUsage,
583}
584
585impl AgentResult {
586    /// Constructs an intrinsically valid successful terminal result.
587    ///
588    /// # Errors
589    ///
590    /// Returns [`AgentResultError`] when the run has no accountable model turn,
591    /// attempts are lower than turns, materialized output/artifact bytes are
592    /// underreported, or an artifact belongs to another tenant or run.
593    pub fn new(
594        provenance: AgentResultProvenance,
595        completed_at: Timestamp,
596        output_schema: SchemaReference,
597        output: BoundedJson,
598        artifacts: AgentArtifacts,
599        usage: BudgetUsage,
600    ) -> Result<Self, AgentResultError> {
601        if usage.model_turns() == crate::ExecutionCount::ZERO {
602            return Err(AgentResultError::MissingModelTurn);
603        }
604        if usage.model_attempts() < usage.model_turns() {
605            return Err(AgentResultError::ModelAttemptsBelowTurns {
606                attempts: usage.model_attempts(),
607                turns: usage.model_turns(),
608            });
609        }
610
611        let output_bytes = byte_count_from_usize(output.stats().compact_bytes());
612        if output_bytes > usage.output_bytes() {
613            return Err(AgentResultError::OutputBytesUnderreported {
614                minimum: output_bytes,
615                actual: usage.output_bytes(),
616            });
617        }
618        if artifacts.total_bytes() > usage.artifact_bytes() {
619            return Err(AgentResultError::ArtifactBytesUnderreported {
620                minimum: artifacts.total_bytes(),
621                actual: usage.artifact_bytes(),
622            });
623        }
624
625        for (index, artifact) in artifacts.iter().enumerate() {
626            if artifact.identity().tenant_id() != provenance.tenant_id() {
627                return Err(AgentResultError::ArtifactTenantMismatch {
628                    index,
629                    expected: Box::new(provenance.tenant_id().clone()),
630                    actual: Box::new(artifact.identity().tenant_id().clone()),
631                });
632            }
633            if artifact.provenance().run_id() != provenance.run_id() {
634                return Err(AgentResultError::ArtifactRunMismatch {
635                    index,
636                    expected: provenance.run_id(),
637                    actual: artifact.provenance().run_id(),
638                });
639            }
640        }
641
642        Ok(Self {
643            provenance,
644            completed_at,
645            output_schema,
646            output,
647            artifacts,
648            usage,
649        })
650    }
651
652    /// Constructs a result whose output schema comes from the agent snapshot.
653    ///
654    /// # Errors
655    ///
656    /// Returns [`AgentResultError`] under the same conditions as [`Self::new`].
657    pub fn for_invocation(
658        provenance: AgentResultProvenance,
659        completed_at: Timestamp,
660        descriptor: &AgentDescriptor,
661        output: BoundedJson,
662        artifacts: AgentArtifacts,
663        usage: BudgetUsage,
664    ) -> Result<Self, AgentResultError> {
665        Self::new(
666            provenance,
667            completed_at,
668            descriptor.output_schema().clone(),
669            output,
670            artifacts,
671            usage,
672        )
673    }
674
675    /// Returns exact invocation provenance.
676    #[must_use]
677    pub const fn provenance(&self) -> &AgentResultProvenance {
678        &self.provenance
679    }
680
681    /// Returns the durable clock observation at successful completion.
682    #[must_use]
683    pub const fn completed_at(&self) -> Timestamp {
684        self.completed_at
685    }
686
687    /// Returns the exact final-output schema identity.
688    #[must_use]
689    pub const fn output_schema(&self) -> &SchemaReference {
690        &self.output_schema
691    }
692
693    /// Returns bounded final output without permitting mutation.
694    #[must_use]
695    pub const fn output(&self) -> &BoundedJson {
696        &self.output
697    }
698
699    /// Returns bounded final artifact references in semantic order.
700    #[must_use]
701    pub const fn artifacts(&self) -> &AgentArtifacts {
702        &self.artifacts
703    }
704
705    /// Returns complete cumulative run usage at this terminal event.
706    #[must_use]
707    pub const fn usage(&self) -> &BudgetUsage {
708        &self.usage
709    }
710
711    /// Consumes this result into its durable components.
712    #[must_use]
713    pub fn into_parts(
714        self,
715    ) -> (
716        AgentResultProvenance,
717        Timestamp,
718        SchemaReference,
719        BoundedJson,
720        AgentArtifacts,
721        BudgetUsage,
722    ) {
723        (
724            self.provenance,
725            self.completed_at,
726            self.output_schema,
727            self.output,
728            self.artifacts,
729            self.usage,
730        )
731    }
732
733    /// Revalidates a successful result before its terminal commit.
734    ///
735    /// `expected_provenance` must come from trusted run admission, never from
736    /// this result. `budget` must be the exact snapshot returned by
737    /// [`AgentRequest::resolve_for`]. The method verifies request and result
738    /// schema binding, all trusted execution IDs, input accounting, and every
739    /// finite budget dimension at `completed_at`.
740    ///
741    /// # Errors
742    ///
743    /// Returns [`AgentResultValidationError`] for any substituted identity or
744    /// schema, unaccounted input, invalid recovered request, or exhausted budget.
745    pub fn validate_for(
746        &self,
747        expected_provenance: &AgentResultProvenance,
748        request: &AgentRequest,
749        descriptor: &AgentDescriptor,
750        budget: &ResolvedBudget,
751    ) -> Result<(), AgentResultValidationError> {
752        expected_provenance
753            .validate_for(descriptor)
754            .map_err(AgentResultValidationError::expected_provenance)?;
755
756        if self.provenance.tenant_id != expected_provenance.tenant_id {
757            return Err(AgentResultValidationError::TenantMismatch {
758                expected: Box::new(expected_provenance.tenant_id.clone()),
759                actual: Box::new(self.provenance.tenant_id.clone()),
760            });
761        }
762        if self.provenance.run_id != expected_provenance.run_id {
763            return Err(AgentResultValidationError::RunMismatch {
764                expected: expected_provenance.run_id,
765                actual: self.provenance.run_id,
766            });
767        }
768        if self.provenance.thread_id != expected_provenance.thread_id {
769            return Err(AgentResultValidationError::ThreadMismatch {
770                expected: expected_provenance.thread_id,
771                actual: self.provenance.thread_id,
772            });
773        }
774        if self.provenance.invocation_id != expected_provenance.invocation_id {
775            return Err(AgentResultValidationError::InvocationMismatch {
776                expected: expected_provenance.invocation_id,
777                actual: self.provenance.invocation_id,
778            });
779        }
780        if self.provenance.agent != expected_provenance.agent {
781            return Err(AgentResultValidationError::AgentIdentityMismatch {
782                expected: Box::new(expected_provenance.agent.clone()),
783                actual: Box::new(self.provenance.agent.clone()),
784            });
785        }
786
787        request
788            .validate_with_resolved_budget(descriptor, budget)
789            .map_err(AgentResultValidationError::request)?;
790        let input_bytes = byte_count_from_usize(request.input.stats().compact_bytes());
791        if input_bytes > self.usage.input_bytes() {
792            return Err(AgentResultValidationError::InputBytesUnderreported {
793                minimum: input_bytes,
794                actual: self.usage.input_bytes(),
795            });
796        }
797
798        if &self.output_schema != descriptor.output_schema() {
799            return Err(AgentResultValidationError::OutputSchemaMismatch {
800                expected: Box::new(descriptor.output_schema().clone()),
801                actual: Box::new(self.output_schema.clone()),
802            });
803        }
804
805        budget
806            .remaining(&self.usage, self.completed_at)
807            .map_err(AgentResultValidationError::budget)?;
808        Ok(())
809    }
810}
811
812impl fmt::Debug for AgentResult {
813    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
814        formatter
815            .debug_struct("AgentResult")
816            .field("provenance", &self.provenance)
817            .field("completed_at", &self.completed_at)
818            .field("output_schema", &self.output_schema)
819            .field("output_stats", &self.output.stats())
820            .field("artifacts", &self.artifacts)
821            .field("usage_recorded", &true)
822            .finish_non_exhaustive()
823    }
824}
825
826impl<'de> Deserialize<'de> for AgentResult {
827    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
828    where
829        D: Deserializer<'de>,
830    {
831        #[derive(Deserialize)]
832        #[serde(deny_unknown_fields)]
833        struct Wire {
834            provenance: AgentResultProvenance,
835            completed_at: Timestamp,
836            output_schema: SchemaReference,
837            output: BoundedJson,
838            artifacts: AgentArtifacts,
839            usage: BudgetUsage,
840        }
841
842        let wire = Wire::deserialize(deserializer)?;
843        Self::new(
844            wire.provenance,
845            wire.completed_at,
846            wire.output_schema,
847            wire.output,
848            wire.artifacts,
849            wire.usage,
850        )
851        .map_err(de::Error::custom)
852    }
853}
854
855/// Intrinsic invalidity in a successful terminal agent result.
856#[derive(Clone, Debug, Eq, Error, PartialEq)]
857#[non_exhaustive]
858pub enum AgentResultError {
859    /// A successful model-backed agent reported no logical turn.
860    #[error("successful agent result must account for at least one model turn")]
861    MissingModelTurn,
862    /// Physical model attempts cannot be fewer than logical turns.
863    #[error("agent result reports {attempts} model attempts for {turns} model turns")]
864    ModelAttemptsBelowTurns {
865        /// Reported physical attempts.
866        attempts: crate::ExecutionCount,
867        /// Reported logical turns.
868        turns: crate::ExecutionCount,
869    },
870    /// Final inline output was not fully included in cumulative byte usage.
871    #[error("agent result records {actual} output bytes; at least {minimum} are required")]
872    OutputBytesUnderreported {
873        /// Compact final-output bytes.
874        minimum: ByteCount,
875        /// Reported cumulative output bytes.
876        actual: ByteCount,
877    },
878    /// Returned run-created artifacts were not fully included in byte usage.
879    #[error("agent result records {actual} artifact bytes; at least {minimum} are required")]
880    ArtifactBytesUnderreported {
881        /// Aggregate returned artifact representation bytes.
882        minimum: ByteCount,
883        /// Reported cumulative artifact bytes.
884        actual: ByteCount,
885    },
886    /// A final artifact belongs to another tenant.
887    #[error("agent artifact at index {index} tenant {actual} does not match {expected}")]
888    ArtifactTenantMismatch {
889        /// Zero-based final artifact position.
890        index: usize,
891        /// Exact invocation tenant.
892        expected: Box<TenantId>,
893        /// Rejected artifact tenant.
894        actual: Box<TenantId>,
895    },
896    /// A final artifact was not created by this durable run.
897    #[error("agent artifact at index {index} run {actual} does not match {expected}")]
898    ArtifactRunMismatch {
899        /// Zero-based final artifact position.
900        index: usize,
901        /// Exact invocation run.
902        expected: RunId,
903        /// Rejected artifact run.
904        actual: RunId,
905    },
906}
907
908/// Invalid relationship between a terminal result and trusted run snapshots.
909#[derive(Clone, Debug, Eq, Error, PartialEq)]
910#[non_exhaustive]
911pub enum AgentResultValidationError {
912    /// Trusted expected provenance itself named another agent descriptor.
913    #[error("expected agent result provenance is invalid: {source}")]
914    ExpectedProvenance {
915        /// Underlying descriptor-binding failure.
916        #[source]
917        source: AgentResultProvenanceError,
918    },
919    /// Result provenance named another tenant.
920    #[error("agent result tenant {actual} does not match expected {expected}")]
921    TenantMismatch {
922        /// Trusted invocation tenant.
923        expected: Box<TenantId>,
924        /// Rejected result tenant.
925        actual: Box<TenantId>,
926    },
927    /// Result provenance named another run.
928    #[error("agent result run {actual} does not match expected {expected}")]
929    RunMismatch {
930        /// Trusted run identifier.
931        expected: RunId,
932        /// Rejected run identifier.
933        actual: RunId,
934    },
935    /// Result provenance named another thread.
936    #[error("agent result thread {actual} does not match expected {expected}")]
937    ThreadMismatch {
938        /// Trusted thread identifier.
939        expected: ThreadId,
940        /// Rejected thread identifier.
941        actual: ThreadId,
942    },
943    /// Result provenance named another logical invocation.
944    #[error("agent result invocation {actual} does not match expected {expected}")]
945    InvocationMismatch {
946        /// Trusted invocation identifier.
947        expected: InvocationId,
948        /// Rejected invocation identifier.
949        actual: InvocationId,
950    },
951    /// Result provenance named another agent snapshot.
952    #[error("agent result identity {actual:?} does not match expected {expected:?}")]
953    AgentIdentityMismatch {
954        /// Trusted owner-qualified agent identity.
955        expected: Box<CapabilityIdentity>,
956        /// Rejected result identity.
957        actual: Box<CapabilityIdentity>,
958    },
959    /// Recovered request did not match descriptor or budget snapshots.
960    #[error("agent result request binding is invalid: {source}")]
961    Request {
962        /// Underlying request validation failure.
963        #[source]
964        source: AgentRequestValidationError,
965    },
966    /// Initial materialized input was absent from cumulative run accounting.
967    #[error("agent result records {actual} input bytes; at least {minimum} are required")]
968    InputBytesUnderreported {
969        /// Compact initial request bytes.
970        minimum: ByteCount,
971        /// Reported cumulative input bytes.
972        actual: ByteCount,
973    },
974    /// Result named another final-output schema.
975    #[error("agent output schema {actual:?} does not match descriptor {expected:?}")]
976    OutputSchemaMismatch {
977        /// Exact descriptor output schema.
978        expected: Box<SchemaReference>,
979        /// Rejected result output schema.
980        actual: Box<SchemaReference>,
981    },
982    /// Terminal usage or completion time exceeded the resolved budget.
983    #[error("agent terminal result exceeds its resolved budget: {source}")]
984    Budget {
985        /// Exact failed budget dimension.
986        #[source]
987        source: BudgetEvaluationError,
988    },
989}
990
991impl AgentResultValidationError {
992    const fn expected_provenance(source: AgentResultProvenanceError) -> Self {
993        Self::ExpectedProvenance { source }
994    }
995
996    const fn request(source: AgentRequestValidationError) -> Self {
997        Self::Request { source }
998    }
999
1000    const fn budget(source: BudgetEvaluationError) -> Self {
1001        Self::Budget { source }
1002    }
1003}
1004
1005fn byte_count_from_usize(value: usize) -> ByteCount {
1006    ByteCount::new(u64::try_from(value).unwrap_or(u64::MAX))
1007}
1008
1009#[cfg(test)]
1010mod tests {
1011    use serde_json::{Value, from_value, json, to_value};
1012
1013    use super::*;
1014    use crate::{ArtifactId, BudgetUsageBuilder, CostLimits, ExecutionCount, TokenCount};
1015
1016    const RUN_ID: &str = "01912345-6789-7abc-8def-0123456789ae";
1017    const OTHER_RUN_ID: &str = "01912345-6789-7abc-8def-0123456789ad";
1018    const THREAD_ID: &str = "01912345-6789-7abc-8def-0123456789af";
1019    const INVOCATION_ID: &str = "01912345-6789-7abc-8def-0123456789b0";
1020    const COMPLETED_AT: &str = "2029-12-31T23:59:59.000000Z";
1021
1022    fn descriptor() -> AgentDescriptor {
1023        let fixture: Value =
1024            serde_json::from_str(include_str!("../tests/fixtures/core-agent-v1.json")).unwrap();
1025        from_value(fixture["descriptors"]["valid"][0].clone()).unwrap()
1026    }
1027
1028    fn request() -> AgentRequest {
1029        let descriptor = descriptor();
1030        AgentRequest::new(
1031            descriptor.input_schema().clone(),
1032            BoundedJson::try_from_value(json!({
1033                "incident_id": "INC-42",
1034                "question": "Summarize the evidence"
1035            }))
1036            .unwrap(),
1037            BudgetLimits::empty().with_output_bytes(ByteCount::new(4096)),
1038        )
1039    }
1040
1041    fn base_budget() -> BudgetLimits {
1042        let fixture: Value =
1043            serde_json::from_str(include_str!("../tests/fixtures/core-budget-v1.json")).unwrap();
1044        let value = from_value::<ResolvedBudget>(fixture["resolved"]["valid"][0].clone()).unwrap();
1045        BudgetLimits::empty()
1046            .with_deadline(value.deadline())
1047            .with_graph_depth(value.graph_depth())
1048            .with_graph_steps(value.graph_steps())
1049            .with_model_attempts(value.model_attempts())
1050            .with_model_turns(value.model_turns())
1051            .with_input_tokens(value.input_tokens())
1052            .with_cached_input_tokens(value.cached_input_tokens())
1053            .with_reasoning_tokens(value.reasoning_tokens())
1054            .with_output_tokens(value.output_tokens())
1055            .with_tool_calls(value.tool_calls())
1056            .with_write_calls(value.write_calls())
1057            .with_remote_agent_delegations(value.remote_agent_delegations())
1058            .with_retries(value.retries())
1059            .with_concurrent_branches(value.concurrent_branches())
1060            .with_fan_out(value.fan_out())
1061            .with_input_bytes(value.input_bytes())
1062            .with_output_bytes(value.output_bytes())
1063            .with_event_bytes(value.event_bytes())
1064            .with_checkpoint_bytes(value.checkpoint_bytes())
1065            .with_artifact_bytes(value.artifact_bytes())
1066            .with_costs(value.costs().clone())
1067    }
1068
1069    fn budget() -> ResolvedBudget {
1070        request()
1071            .resolve_for(
1072                &descriptor(),
1073                &[base_budget()],
1074                COMPLETED_AT.parse().unwrap(),
1075            )
1076            .unwrap()
1077    }
1078
1079    fn provenance() -> AgentResultProvenance {
1080        AgentResultProvenance::for_agent(
1081            "tenant-production".parse().unwrap(),
1082            RUN_ID.parse().unwrap(),
1083            THREAD_ID.parse().unwrap(),
1084            INVOCATION_ID.parse().unwrap(),
1085            &descriptor(),
1086        )
1087    }
1088
1089    fn output() -> BoundedJson {
1090        BoundedJson::try_from_value(json!({
1091            "summary": "Database latency caused the incident.",
1092            "severity": "high"
1093        }))
1094        .unwrap()
1095    }
1096
1097    fn usage_for(output: &BoundedJson, artifacts: &AgentArtifacts) -> BudgetUsage {
1098        BudgetUsage::builder()
1099            .model_attempts(ExecutionCount::new(3))
1100            .model_turns(ExecutionCount::new(2))
1101            .input_tokens(TokenCount::new(800))
1102            .output_tokens(TokenCount::new(200))
1103            .input_bytes(byte_count_from_usize(
1104                request().input().stats().compact_bytes(),
1105            ))
1106            .output_bytes(byte_count_from_usize(output.stats().compact_bytes()))
1107            .artifact_bytes(artifacts.total_bytes())
1108            .known_costs(crate::KnownCosts::empty())
1109            .build()
1110            .unwrap()
1111    }
1112
1113    fn result() -> AgentResult {
1114        let output = output();
1115        let artifacts = AgentArtifacts::empty();
1116        AgentResult::for_invocation(
1117            provenance(),
1118            COMPLETED_AT.parse().unwrap(),
1119            &descriptor(),
1120            output.clone(),
1121            artifacts.clone(),
1122            usage_for(&output, &artifacts),
1123        )
1124        .unwrap()
1125    }
1126
1127    fn bound_artifact(tenant: &str, run_id: &str, artifact_id: ArtifactId) -> ArtifactRef {
1128        let fixture: Value =
1129            serde_json::from_str(include_str!("../tests/fixtures/core-artifact-v1.json")).unwrap();
1130        let mut value = fixture["artifact_refs"]["valid"][0].clone();
1131        value["identity"]["tenant_id"] = Value::from(tenant);
1132        value["identity"]["artifact_id"] = Value::from(artifact_id.to_string());
1133        value["provenance"]["run_id"] = Value::from(run_id);
1134        from_value(value).unwrap()
1135    }
1136
1137    #[test]
1138    fn request_resolves_all_layers_and_redacts_content() {
1139        let request = request();
1140        let budget = request
1141            .resolve_for(
1142                &descriptor(),
1143                &[base_budget()],
1144                COMPLETED_AT.parse().unwrap(),
1145            )
1146            .unwrap();
1147        assert_eq!(budget.model_turns(), ExecutionCount::new(12));
1148        assert_eq!(budget.tool_calls(), ExecutionCount::new(24));
1149        assert_eq!(budget.write_calls(), ExecutionCount::new(1));
1150        assert_eq!(budget.output_bytes(), ByteCount::new(4096));
1151        assert!(!format!("{request:?}").contains("INC-42"));
1152
1153        let scalar = AgentRequest::new(
1154            descriptor().input_schema().clone(),
1155            BoundedJson::try_from_value(json!("INC-42")).unwrap(),
1156            BudgetLimits::empty(),
1157        );
1158        scalar
1159            .validate_with_resolved_budget(&descriptor(), &budget)
1160            .expect("agent input root shape belongs to the registered schema");
1161    }
1162
1163    #[test]
1164    fn request_rejects_schema_substitution_expiry_and_layer_exhaustion() {
1165        let descriptor = descriptor();
1166        let mut value = to_value(request()).unwrap();
1167        value["input_schema"] = to_value(descriptor.output_schema()).unwrap();
1168        let wrong_schema = from_value::<AgentRequest>(value).unwrap();
1169        assert!(matches!(
1170            wrong_schema.validate_with_resolved_budget(&descriptor, &budget()),
1171            Err(AgentRequestValidationError::SchemaMismatch { .. })
1172        ));
1173
1174        assert!(matches!(
1175            request().resolve_for(
1176                &descriptor,
1177                &[base_budget()],
1178                "2030-01-01T00:00:00.000000Z".parse().unwrap(),
1179            ),
1180            Err(AgentRequestValidationError::BudgetEvaluation { .. })
1181        ));
1182
1183        let too_many = vec![BudgetLimits::empty(); MAX_BUDGET_LAYERS];
1184        assert!(matches!(
1185            request().resolve_for(&descriptor, &too_many, COMPLETED_AT.parse().unwrap(),),
1186            Err(AgentRequestValidationError::TooManyBudgetLayers { .. })
1187        ));
1188    }
1189
1190    #[test]
1191    fn request_rejects_retired_agent_but_recovery_validation_remains_possible() {
1192        let fixture: Value =
1193            serde_json::from_str(include_str!("../tests/fixtures/core-agent-v1.json")).unwrap();
1194        let mut value = fixture["descriptors"]["valid"][0].clone();
1195        value["metadata"]["lifecycle"] = json!({
1196            "status": "retired",
1197            "retired_at": "2026-08-29T00:00:00.000000Z",
1198            "notice": "Historical agent version"
1199        });
1200        let retired = from_value::<AgentDescriptor>(value).unwrap();
1201        assert!(matches!(
1202            request().resolve_for(&retired, &[base_budget()], COMPLETED_AT.parse().unwrap(),),
1203            Err(AgentRequestValidationError::RetiredAgent { .. })
1204        ));
1205        request()
1206            .validate_with_resolved_budget(&retired, &budget())
1207            .unwrap();
1208    }
1209
1210    #[test]
1211    fn final_artifacts_are_bounded_unique_and_run_scoped() {
1212        let artifact = bound_artifact("tenant-production", RUN_ID, ArtifactId::generate());
1213        assert_eq!(
1214            AgentArtifacts::try_new([artifact.clone(), artifact]),
1215            Err(AgentArtifactsError::DuplicateIdentity)
1216        );
1217
1218        let too_many = (0..=AgentArtifacts::MAX_LEN)
1219            .map(|_| bound_artifact("tenant-production", RUN_ID, ArtifactId::generate()));
1220        assert!(matches!(
1221            AgentArtifacts::try_new(too_many),
1222            Err(AgentArtifactsError::TooMany { .. })
1223        ));
1224
1225        let foreign = AgentArtifacts::try_new([bound_artifact(
1226            "tenant-other",
1227            RUN_ID,
1228            ArtifactId::generate(),
1229        )])
1230        .unwrap();
1231        let output = output();
1232        assert!(matches!(
1233            AgentResult::for_invocation(
1234                provenance(),
1235                COMPLETED_AT.parse().unwrap(),
1236                &descriptor(),
1237                output.clone(),
1238                foreign.clone(),
1239                usage_for(&output, &foreign),
1240            ),
1241            Err(AgentResultError::ArtifactTenantMismatch { .. })
1242        ));
1243    }
1244
1245    #[test]
1246    fn result_requires_complete_accounting_and_exact_run_binding() {
1247        let descriptor = descriptor();
1248        let request = request();
1249        let budget = budget();
1250        let result = result();
1251        result
1252            .validate_for(&provenance(), &request, &descriptor, &budget)
1253            .unwrap();
1254
1255        let foreign = AgentResultProvenance::for_agent(
1256            "tenant-production".parse().unwrap(),
1257            OTHER_RUN_ID.parse().unwrap(),
1258            THREAD_ID.parse().unwrap(),
1259            INVOCATION_ID.parse().unwrap(),
1260            &descriptor,
1261        );
1262        assert!(matches!(
1263            result.validate_for(&foreign, &request, &descriptor, &budget),
1264            Err(AgentResultValidationError::RunMismatch { .. })
1265        ));
1266
1267        let output = output();
1268        let artifacts = AgentArtifacts::empty();
1269        let underreported = BudgetUsageBuilder::default()
1270            .model_attempts(ExecutionCount::new(1))
1271            .model_turns(ExecutionCount::new(1))
1272            .input_bytes(ByteCount::ZERO)
1273            .output_bytes(byte_count_from_usize(output.stats().compact_bytes()))
1274            .artifact_bytes(ByteCount::ZERO)
1275            .build()
1276            .unwrap();
1277        let result = AgentResult::for_invocation(
1278            provenance(),
1279            COMPLETED_AT.parse().unwrap(),
1280            &descriptor,
1281            output,
1282            artifacts,
1283            underreported,
1284        )
1285        .unwrap();
1286        assert!(matches!(
1287            result.validate_for(&provenance(), &request, &descriptor, &budget),
1288            Err(AgentResultValidationError::InputBytesUnderreported { .. })
1289        ));
1290    }
1291
1292    #[test]
1293    fn result_rejects_impossible_turn_and_output_accounting() {
1294        let output = output();
1295        assert_eq!(
1296            AgentResult::for_invocation(
1297                provenance(),
1298                COMPLETED_AT.parse().unwrap(),
1299                &descriptor(),
1300                output.clone(),
1301                AgentArtifacts::empty(),
1302                BudgetUsage::zero(),
1303            ),
1304            Err(AgentResultError::MissingModelTurn)
1305        );
1306
1307        let attempts_below_turns = BudgetUsage::builder()
1308            .model_attempts(ExecutionCount::new(1))
1309            .model_turns(ExecutionCount::new(2))
1310            .output_bytes(byte_count_from_usize(output.stats().compact_bytes()))
1311            .build()
1312            .unwrap();
1313        assert!(matches!(
1314            AgentResult::for_invocation(
1315                provenance(),
1316                COMPLETED_AT.parse().unwrap(),
1317                &descriptor(),
1318                output.clone(),
1319                AgentArtifacts::empty(),
1320                attempts_below_turns,
1321            ),
1322            Err(AgentResultError::ModelAttemptsBelowTurns { .. })
1323        ));
1324
1325        let output_underreported = BudgetUsage::builder()
1326            .model_attempts(ExecutionCount::new(1))
1327            .model_turns(ExecutionCount::new(1))
1328            .output_bytes(ByteCount::ZERO)
1329            .build()
1330            .unwrap();
1331        assert!(matches!(
1332            AgentResult::for_invocation(
1333                provenance(),
1334                COMPLETED_AT.parse().unwrap(),
1335                &descriptor(),
1336                output,
1337                AgentArtifacts::empty(),
1338                output_underreported,
1339            ),
1340            Err(AgentResultError::OutputBytesUnderreported { .. })
1341        ));
1342    }
1343
1344    #[test]
1345    fn result_wire_is_closed_and_redacts_output_and_usage_values() {
1346        fn assert_send_sync<T: Send + Sync>() {}
1347
1348        assert_send_sync::<AgentRequest>();
1349        assert_send_sync::<AgentResultProvenance>();
1350        assert_send_sync::<AgentArtifacts>();
1351        assert_send_sync::<AgentResult>();
1352
1353        let result = result();
1354        let value = to_value(&result).unwrap();
1355        let decoded = from_value::<AgentResult>(value.clone()).unwrap();
1356        assert_eq!(to_value(decoded).unwrap(), value);
1357        let debug = format!("{result:?}");
1358        assert!(!debug.contains("Database latency"));
1359        assert!(!debug.contains("800"));
1360
1361        let mut unknown = value;
1362        unknown["raw_responses"] = json!([]);
1363        assert!(from_value::<AgentResult>(unknown).is_err());
1364
1365        for schema in [
1366            to_value(schemars::schema_for!(AgentRequest)).unwrap(),
1367            to_value(schemars::schema_for!(AgentResultProvenance)).unwrap(),
1368            to_value(schemars::schema_for!(AgentResult)).unwrap(),
1369        ] {
1370            assert_eq!(schema["type"], "object");
1371            assert_eq!(schema["additionalProperties"], false);
1372        }
1373        let artifacts = to_value(schemars::schema_for!(AgentArtifacts)).unwrap();
1374        assert_eq!(artifacts["type"], "array");
1375        assert_eq!(artifacts["maxItems"], AgentArtifacts::MAX_LEN);
1376    }
1377
1378    #[test]
1379    fn request_budget_requires_a_complete_base_policy() {
1380        assert!(matches!(
1381            request().resolve_for(
1382                &descriptor(),
1383                &[BudgetLimits::empty().with_costs(CostLimits::default())],
1384                COMPLETED_AT.parse().unwrap(),
1385            ),
1386            Err(AgentRequestValidationError::BudgetResolution { .. })
1387        ));
1388    }
1389}