Skip to main content

stateknot_core/
capability.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Stable names for executable capabilities.
5
6use std::{borrow::Borrow, fmt, str::FromStr};
7
8use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
9use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
10use thiserror::Error;
11
12use crate::{Extensions, PrincipalIdentity, ScopeSet, Timestamp, Version};
13
14const CAPABILITY_NAME_PATTERN: &str = "^[A-Za-z0-9_.-]{1,128}$";
15const KIBIBYTE: usize = 1024;
16
17/// A stable, case-sensitive capability name.
18///
19/// Names contain 1 to 128 ASCII letters, digits, `_`, `-`, or `.`. This is
20/// the tool-name grammar from the MCP 2026-07-28 specification, made
21/// mandatory at the `StateKnot` domain boundary. A name is unique only within
22/// its owning registry; owner/provenance remains a separate identity field.
23#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
24pub struct CapabilityName(Box<str>);
25
26impl CapabilityName {
27    /// Maximum encoded length in bytes.
28    pub const MAX_LEN: usize = 128;
29
30    /// Validates and constructs a capability name without copying a `String`.
31    ///
32    /// # Errors
33    ///
34    /// Returns [`CapabilityNameError`] when `value` is empty, too long, or
35    /// contains a byte outside the stable ASCII grammar.
36    pub fn new(value: impl Into<String>) -> Result<Self, CapabilityNameError> {
37        let value = value.into();
38        validate_capability_name(&value)?;
39        Ok(Self(value.into_boxed_str()))
40    }
41
42    /// Returns the exact, case-sensitive name.
43    #[must_use]
44    pub fn as_str(&self) -> &str {
45        &self.0
46    }
47}
48
49impl AsRef<str> for CapabilityName {
50    fn as_ref(&self) -> &str {
51        self.as_str()
52    }
53}
54
55impl Borrow<str> for CapabilityName {
56    fn borrow(&self) -> &str {
57        self.as_str()
58    }
59}
60
61impl fmt::Debug for CapabilityName {
62    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
63        formatter
64            .debug_tuple("CapabilityName")
65            .field(&self.as_str())
66            .finish()
67    }
68}
69
70impl fmt::Display for CapabilityName {
71    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
72        formatter.write_str(self.as_str())
73    }
74}
75
76impl FromStr for CapabilityName {
77    type Err = CapabilityNameError;
78
79    fn from_str(value: &str) -> Result<Self, Self::Err> {
80        Self::new(value)
81    }
82}
83
84impl TryFrom<String> for CapabilityName {
85    type Error = CapabilityNameError;
86
87    fn try_from(value: String) -> Result<Self, Self::Error> {
88        Self::new(value)
89    }
90}
91
92impl TryFrom<&str> for CapabilityName {
93    type Error = CapabilityNameError;
94
95    fn try_from(value: &str) -> Result<Self, Self::Error> {
96        Self::new(value)
97    }
98}
99
100impl From<CapabilityName> for String {
101    fn from(value: CapabilityName) -> Self {
102        value.0.into()
103    }
104}
105
106impl Serialize for CapabilityName {
107    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
108    where
109        S: Serializer,
110    {
111        serializer.serialize_str(self.as_str())
112    }
113}
114
115impl<'de> Deserialize<'de> for CapabilityName {
116    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
117    where
118        D: Deserializer<'de>,
119    {
120        deserializer.deserialize_string(CapabilityNameVisitor)
121    }
122}
123
124struct CapabilityNameVisitor;
125
126impl de::Visitor<'_> for CapabilityNameVisitor {
127    type Value = CapabilityName;
128
129    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
130        formatter.write_str("a canonical StateKnot capability name")
131    }
132
133    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
134    where
135        E: de::Error,
136    {
137        CapabilityName::try_from(value).map_err(E::custom)
138    }
139
140    fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
141    where
142        E: de::Error,
143    {
144        CapabilityName::try_from(value).map_err(E::custom)
145    }
146}
147
148impl JsonSchema for CapabilityName {
149    fn schema_name() -> std::borrow::Cow<'static, str> {
150        "CapabilityName".into()
151    }
152
153    fn schema_id() -> std::borrow::Cow<'static, str> {
154        concat!(module_path!(), "::CapabilityName").into()
155    }
156
157    fn json_schema(_: &mut SchemaGenerator) -> Schema {
158        json_schema!({
159            "type": "string",
160            "minLength": 1,
161            "maxLength": 128,
162            "pattern": CAPABILITY_NAME_PATTERN
163        })
164    }
165
166    fn inline_schema() -> bool {
167        true
168    }
169}
170
171/// Validation failure for a [`CapabilityName`].
172#[derive(Clone, Debug, Eq, Error, PartialEq)]
173#[non_exhaustive]
174pub enum CapabilityNameError {
175    /// The name contained no bytes.
176    #[error("capability name must not be empty")]
177    Empty,
178
179    /// The name exceeded [`CapabilityName::MAX_LEN`].
180    #[error("capability name is {actual} bytes; maximum is {max}")]
181    TooLong {
182        /// Maximum accepted byte length.
183        max: usize,
184        /// Observed byte length.
185        actual: usize,
186    },
187
188    /// A byte did not belong to the allowed ASCII grammar.
189    #[error("capability name contains an invalid byte at offset {index}")]
190    InvalidByte {
191        /// Zero-based byte offset of the first invalid byte.
192        index: usize,
193    },
194}
195
196/// A version-pinned reference to a registered capability.
197///
198/// Names are unique only within their owning registry. Durable provenance must
199/// therefore pair this value with the owning principal or registry identity.
200#[derive(
201    Clone, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
202)]
203#[serde(deny_unknown_fields)]
204pub struct CapabilityReference {
205    name: CapabilityName,
206    version: Version,
207}
208
209impl CapabilityReference {
210    /// Constructs a reference from validated components.
211    #[must_use]
212    pub const fn new(name: CapabilityName, version: Version) -> Self {
213        Self { name, version }
214    }
215
216    /// Returns the registry-local capability name.
217    #[must_use]
218    pub const fn name(&self) -> &CapabilityName {
219        &self.name
220    }
221
222    /// Returns the pinned capability version.
223    #[must_use]
224    pub const fn version(&self) -> Version {
225        self.version
226    }
227}
228
229/// An owner-qualified, version-pinned capability identity.
230///
231/// [`CapabilityName`] is registry-local, so durable references use this pair
232/// whenever a surrounding record does not already pin the owning registry.
233/// The serialized owner is an auditable claim, not authentication or proof
234/// that the capability is registered.
235#[derive(
236    Clone, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
237)]
238#[serde(deny_unknown_fields)]
239pub struct CapabilityIdentity {
240    owner: PrincipalIdentity,
241    capability: CapabilityReference,
242}
243
244impl CapabilityIdentity {
245    /// Constructs an owner-qualified identity from validated components.
246    #[must_use]
247    pub const fn new(owner: PrincipalIdentity, capability: CapabilityReference) -> Self {
248        Self { owner, capability }
249    }
250
251    /// Returns the principal owning the registry namespace.
252    #[must_use]
253    pub const fn owner(&self) -> &PrincipalIdentity {
254        &self.owner
255    }
256
257    /// Returns the registry-local, version-pinned reference.
258    #[must_use]
259    pub const fn capability(&self) -> &CapabilityReference {
260        &self.capability
261    }
262
263    /// Returns the registry-local capability name.
264    #[must_use]
265    pub const fn name(&self) -> &CapabilityName {
266        self.capability.name()
267    }
268
269    /// Returns the pinned capability version.
270    #[must_use]
271    pub const fn version(&self) -> Version {
272        self.capability.version()
273    }
274}
275
276/// A bounded single-line display title for a capability.
277///
278/// Titles preserve exact UTF-8, reject boundary whitespace and formatting
279/// controls that make audit or UI rendering ambiguous, and redact their text
280/// from `Debug`. Renderers must still perform output-context escaping.
281#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
282pub struct CapabilityTitle(Box<str>);
283
284impl CapabilityTitle {
285    /// Maximum UTF-8 encoded length in bytes.
286    pub const MAX_BYTES: usize = 256;
287
288    /// Validates and constructs a capability title.
289    ///
290    /// # Errors
291    ///
292    /// Returns [`CapabilityTitleError`] for empty, oversized,
293    /// whitespace-ambiguous, control-bearing, or noncharacter-bearing text.
294    pub fn new(value: impl Into<String>) -> Result<Self, CapabilityTitleError> {
295        let value = value.into();
296        validate_capability_title(&value)?;
297        Ok(Self(value.into_boxed_str()))
298    }
299
300    /// Returns the exact title text.
301    #[must_use]
302    pub fn as_str(&self) -> &str {
303        &self.0
304    }
305
306    /// Returns the UTF-8 encoded length without disclosing the title.
307    #[must_use]
308    pub fn len_bytes(&self) -> usize {
309        self.0.len()
310    }
311}
312
313impl AsRef<str> for CapabilityTitle {
314    fn as_ref(&self) -> &str {
315        self.as_str()
316    }
317}
318
319impl Borrow<str> for CapabilityTitle {
320    fn borrow(&self) -> &str {
321        self.as_str()
322    }
323}
324
325impl fmt::Debug for CapabilityTitle {
326    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
327        formatter
328            .debug_struct("CapabilityTitle")
329            .field("utf8_bytes", &self.len_bytes())
330            .finish_non_exhaustive()
331    }
332}
333
334impl FromStr for CapabilityTitle {
335    type Err = CapabilityTitleError;
336
337    fn from_str(value: &str) -> Result<Self, Self::Err> {
338        Self::new(value)
339    }
340}
341
342impl TryFrom<String> for CapabilityTitle {
343    type Error = CapabilityTitleError;
344
345    fn try_from(value: String) -> Result<Self, Self::Error> {
346        Self::new(value)
347    }
348}
349
350impl TryFrom<&str> for CapabilityTitle {
351    type Error = CapabilityTitleError;
352
353    fn try_from(value: &str) -> Result<Self, Self::Error> {
354        Self::new(value)
355    }
356}
357
358impl From<CapabilityTitle> for String {
359    fn from(value: CapabilityTitle) -> Self {
360        value.0.into()
361    }
362}
363
364impl Serialize for CapabilityTitle {
365    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
366    where
367        S: Serializer,
368    {
369        serializer.serialize_str(self.as_str())
370    }
371}
372
373impl<'de> Deserialize<'de> for CapabilityTitle {
374    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
375    where
376        D: Deserializer<'de>,
377    {
378        deserializer.deserialize_string(CapabilityTitleVisitor)
379    }
380}
381
382struct CapabilityTitleVisitor;
383
384impl de::Visitor<'_> for CapabilityTitleVisitor {
385    type Value = CapabilityTitle;
386
387    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
388        formatter.write_str("a bounded single-line capability title")
389    }
390
391    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
392    where
393        E: de::Error,
394    {
395        CapabilityTitle::try_from(value).map_err(E::custom)
396    }
397
398    fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
399    where
400        E: de::Error,
401    {
402        CapabilityTitle::try_from(value).map_err(E::custom)
403    }
404}
405
406impl JsonSchema for CapabilityTitle {
407    fn schema_name() -> std::borrow::Cow<'static, str> {
408        "CapabilityTitle".into()
409    }
410
411    fn schema_id() -> std::borrow::Cow<'static, str> {
412        concat!(module_path!(), "::CapabilityTitle").into()
413    }
414
415    fn json_schema(_: &mut SchemaGenerator) -> Schema {
416        json_schema!({
417            "type": "string",
418            "minLength": 1,
419            "maxLength": 256,
420            "description": "A single-line display title bounded to 256 UTF-8 bytes. StateKnot additionally rejects boundary whitespace, controls, bidi formatting controls, Unicode line separators, and noncharacters at runtime."
421        })
422    }
423
424    fn inline_schema() -> bool {
425        true
426    }
427}
428
429/// Invalid capability title text.
430#[derive(Clone, Debug, Eq, Error, PartialEq)]
431#[non_exhaustive]
432pub enum CapabilityTitleError {
433    /// The title contained no bytes.
434    #[error("capability title must not be empty")]
435    Empty,
436
437    /// The title exceeded [`CapabilityTitle::MAX_BYTES`].
438    #[error("capability title is {actual} UTF-8 bytes; maximum is {max}")]
439    TooLong {
440        /// Maximum accepted UTF-8 byte length.
441        max: usize,
442        /// Observed UTF-8 byte length.
443        actual: usize,
444    },
445
446    /// The title began or ended with Unicode whitespace.
447    #[error("capability title must not have leading or trailing whitespace")]
448    BoundaryWhitespace,
449
450    /// A control, bidi formatting control, line separator, or noncharacter was present.
451    #[error("capability title contains a disallowed scalar at UTF-8 byte offset {byte_index}")]
452    DisallowedCodePoint {
453        /// Zero-based UTF-8 byte offset without disclosure of title text.
454        byte_index: usize,
455    },
456}
457
458fn validate_capability_title(value: &str) -> Result<(), CapabilityTitleError> {
459    if value.is_empty() {
460        return Err(CapabilityTitleError::Empty);
461    }
462    if value.len() > CapabilityTitle::MAX_BYTES {
463        return Err(CapabilityTitleError::TooLong {
464            max: CapabilityTitle::MAX_BYTES,
465            actual: value.len(),
466        });
467    }
468    if value.chars().next().is_some_and(char::is_whitespace)
469        || value.chars().next_back().is_some_and(char::is_whitespace)
470    {
471        return Err(CapabilityTitleError::BoundaryWhitespace);
472    }
473    if let Some((byte_index, _)) = value.char_indices().find(|(_, scalar)| {
474        scalar.is_control()
475            || is_bidi_formatting_control(*scalar)
476            || matches!(scalar, '\u{2028}' | '\u{2029}')
477            || is_unicode_noncharacter(*scalar)
478    }) {
479        return Err(CapabilityTitleError::DisallowedCodePoint { byte_index });
480    }
481    Ok(())
482}
483
484/// Bounded trusted-registry description text for a capability.
485///
486/// Descriptions preserve exact UTF-8 and may contain internal tabs and line
487/// breaks. Text is redacted from `Debug` because descriptions are commonly
488/// copied into model context. Shape validation does not make remote descriptor
489/// text trusted; only an authenticated, policy-approved registry may select it
490/// for discovery or prompt construction.
491#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
492pub struct CapabilityDescription(Box<str>);
493
494impl CapabilityDescription {
495    /// Maximum UTF-8 encoded length in bytes.
496    pub const MAX_BYTES: usize = 16 * KIBIBYTE;
497
498    /// Validates and constructs a capability description.
499    ///
500    /// # Errors
501    ///
502    /// Returns [`CapabilityDescriptionError`] for empty, oversized,
503    /// whitespace-ambiguous, control-bearing, or noncharacter-bearing text.
504    pub fn new(value: impl Into<String>) -> Result<Self, CapabilityDescriptionError> {
505        let value = value.into();
506        validate_capability_description(&value)?;
507        Ok(Self(value.into_boxed_str()))
508    }
509
510    /// Returns the exact description text.
511    #[must_use]
512    pub fn as_str(&self) -> &str {
513        &self.0
514    }
515
516    /// Returns the UTF-8 encoded length without disclosing the description.
517    #[must_use]
518    pub fn len_bytes(&self) -> usize {
519        self.0.len()
520    }
521}
522
523impl AsRef<str> for CapabilityDescription {
524    fn as_ref(&self) -> &str {
525        self.as_str()
526    }
527}
528
529impl Borrow<str> for CapabilityDescription {
530    fn borrow(&self) -> &str {
531        self.as_str()
532    }
533}
534
535impl fmt::Debug for CapabilityDescription {
536    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
537        formatter
538            .debug_struct("CapabilityDescription")
539            .field("utf8_bytes", &self.len_bytes())
540            .finish_non_exhaustive()
541    }
542}
543
544impl FromStr for CapabilityDescription {
545    type Err = CapabilityDescriptionError;
546
547    fn from_str(value: &str) -> Result<Self, Self::Err> {
548        Self::new(value)
549    }
550}
551
552impl TryFrom<String> for CapabilityDescription {
553    type Error = CapabilityDescriptionError;
554
555    fn try_from(value: String) -> Result<Self, Self::Error> {
556        Self::new(value)
557    }
558}
559
560impl TryFrom<&str> for CapabilityDescription {
561    type Error = CapabilityDescriptionError;
562
563    fn try_from(value: &str) -> Result<Self, Self::Error> {
564        Self::new(value)
565    }
566}
567
568impl From<CapabilityDescription> for String {
569    fn from(value: CapabilityDescription) -> Self {
570        value.0.into()
571    }
572}
573
574impl Serialize for CapabilityDescription {
575    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
576    where
577        S: Serializer,
578    {
579        serializer.serialize_str(self.as_str())
580    }
581}
582
583impl<'de> Deserialize<'de> for CapabilityDescription {
584    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
585    where
586        D: Deserializer<'de>,
587    {
588        deserializer.deserialize_string(CapabilityDescriptionVisitor)
589    }
590}
591
592struct CapabilityDescriptionVisitor;
593
594impl de::Visitor<'_> for CapabilityDescriptionVisitor {
595    type Value = CapabilityDescription;
596
597    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
598        formatter.write_str("a bounded capability description")
599    }
600
601    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
602    where
603        E: de::Error,
604    {
605        CapabilityDescription::try_from(value).map_err(E::custom)
606    }
607
608    fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
609    where
610        E: de::Error,
611    {
612        CapabilityDescription::try_from(value).map_err(E::custom)
613    }
614}
615
616impl JsonSchema for CapabilityDescription {
617    fn schema_name() -> std::borrow::Cow<'static, str> {
618        "CapabilityDescription".into()
619    }
620
621    fn schema_id() -> std::borrow::Cow<'static, str> {
622        concat!(module_path!(), "::CapabilityDescription").into()
623    }
624
625    fn json_schema(_: &mut SchemaGenerator) -> Schema {
626        json_schema!({
627            "type": "string",
628            "minLength": 1,
629            "maxLength": 16384,
630            "description": "Exact description text bounded to 16384 UTF-8 bytes. StateKnot additionally rejects boundary whitespace, disallowed controls, bidi formatting controls, and Unicode noncharacters at runtime. Shape validation does not establish descriptor trust."
631        })
632    }
633
634    fn inline_schema() -> bool {
635        true
636    }
637}
638
639/// Invalid capability description text.
640#[derive(Clone, Debug, Eq, Error, PartialEq)]
641#[non_exhaustive]
642pub enum CapabilityDescriptionError {
643    /// The description contained no bytes.
644    #[error("capability description must not be empty")]
645    Empty,
646
647    /// The description exceeded [`CapabilityDescription::MAX_BYTES`].
648    #[error("capability description is {actual} UTF-8 bytes; maximum is {max}")]
649    TooLong {
650        /// Maximum accepted UTF-8 byte length.
651        max: usize,
652        /// Observed UTF-8 byte length.
653        actual: usize,
654    },
655
656    /// The description began or ended with Unicode whitespace.
657    #[error("capability description must not have leading or trailing whitespace")]
658    BoundaryWhitespace,
659
660    /// A disallowed control, bidi formatting control, or noncharacter was present.
661    #[error(
662        "capability description contains a disallowed scalar at UTF-8 byte offset {byte_index}"
663    )]
664    DisallowedCodePoint {
665        /// Zero-based UTF-8 byte offset without disclosure of description text.
666        byte_index: usize,
667    },
668}
669
670fn validate_capability_description(value: &str) -> Result<(), CapabilityDescriptionError> {
671    if value.is_empty() {
672        return Err(CapabilityDescriptionError::Empty);
673    }
674    if value.len() > CapabilityDescription::MAX_BYTES {
675        return Err(CapabilityDescriptionError::TooLong {
676            max: CapabilityDescription::MAX_BYTES,
677            actual: value.len(),
678        });
679    }
680    if value.chars().next().is_some_and(char::is_whitespace)
681        || value.chars().next_back().is_some_and(char::is_whitespace)
682    {
683        return Err(CapabilityDescriptionError::BoundaryWhitespace);
684    }
685    if let Some((byte_index, _)) = value.char_indices().find(|(_, scalar)| {
686        (scalar.is_control() && !matches!(scalar, '\t' | '\n' | '\r'))
687            || is_bidi_formatting_control(*scalar)
688            || is_unicode_noncharacter(*scalar)
689    }) {
690        return Err(CapabilityDescriptionError::DisallowedCodePoint { byte_index });
691    }
692    Ok(())
693}
694
695const fn is_unicode_noncharacter(value: char) -> bool {
696    let value = value as u32;
697    (value >= 0xfdd0 && value <= 0xfdef) || (value & 0xfffe) == 0xfffe
698}
699
700const fn is_bidi_formatting_control(value: char) -> bool {
701    matches!(
702        value,
703        '\u{061c}'
704            | '\u{200e}'
705            | '\u{200f}'
706            | '\u{202a}'..='\u{202e}'
707            | '\u{2066}'..='\u{2069}'
708    )
709}
710
711/// Stable classification of a discoverable capability.
712#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
713#[serde(rename_all = "snake_case")]
714pub enum CapabilityKind {
715    /// A model invocation capability.
716    Model,
717    /// A callable tool capability.
718    Tool,
719    /// A collaborating local or remote agent capability.
720    Agent,
721    /// A versioned workflow or graph capability.
722    Workflow,
723    /// An application-defined non-tool producer capability.
724    Application,
725}
726
727/// Stable lifecycle classification for a capability version.
728#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
729pub enum CapabilityLifecycleState {
730    /// Available without a published retirement notice.
731    Active,
732    /// Still represented but carrying a migration notice.
733    Deprecated,
734    /// Retained for history but unavailable for new execution.
735    Retired,
736}
737
738#[derive(Clone, Eq, Hash, PartialEq)]
739enum CapabilityLifecycleValue {
740    Active,
741    Deprecated {
742        announced_at: Timestamp,
743        sunset_at: Option<Timestamp>,
744        notice: CapabilityDescription,
745        replacement: Option<CapabilityIdentity>,
746    },
747    Retired {
748        retired_at: Timestamp,
749        notice: CapabilityDescription,
750        replacement: Option<CapabilityIdentity>,
751    },
752}
753
754/// Validated lifecycle metadata for one pinned capability version.
755///
756/// Deprecation does not itself disable execution, and a future sunset does not
757/// act as a clock-driven policy. A registry snapshots and enforces availability
758/// separately. `Retired` records remain decodable for audit and recovery but
759/// must not be selected for new execution.
760#[derive(Clone, Eq, Hash, PartialEq)]
761pub struct CapabilityLifecycle(CapabilityLifecycleValue);
762
763impl CapabilityLifecycle {
764    /// Constructs an active lifecycle.
765    #[must_use]
766    pub const fn active() -> Self {
767        Self(CapabilityLifecycleValue::Active)
768    }
769
770    /// Constructs a deprecated lifecycle with migration guidance.
771    ///
772    /// # Errors
773    ///
774    /// Returns [`CapabilityLifecycleError`] when a sunset is not strictly
775    /// later than the deprecation announcement.
776    pub fn deprecated(
777        announced_at: Timestamp,
778        sunset_at: Option<Timestamp>,
779        notice: CapabilityDescription,
780        replacement: Option<CapabilityIdentity>,
781    ) -> Result<Self, CapabilityLifecycleError> {
782        if let Some(sunset_at) = sunset_at {
783            if sunset_at <= announced_at {
784                return Err(CapabilityLifecycleError::InvalidSunsetOrder {
785                    announced_at,
786                    sunset_at,
787                });
788            }
789        }
790        Ok(Self(CapabilityLifecycleValue::Deprecated {
791            announced_at,
792            sunset_at,
793            notice,
794            replacement,
795        }))
796    }
797
798    /// Constructs a retired lifecycle retained for durable history.
799    #[must_use]
800    pub fn retired(
801        retired_at: Timestamp,
802        notice: CapabilityDescription,
803        replacement: Option<CapabilityIdentity>,
804    ) -> Self {
805        Self(CapabilityLifecycleValue::Retired {
806            retired_at,
807            notice,
808            replacement,
809        })
810    }
811
812    /// Returns the stable lifecycle state.
813    #[must_use]
814    pub const fn state(&self) -> CapabilityLifecycleState {
815        match self.0 {
816            CapabilityLifecycleValue::Active => CapabilityLifecycleState::Active,
817            CapabilityLifecycleValue::Deprecated { .. } => CapabilityLifecycleState::Deprecated,
818            CapabilityLifecycleValue::Retired { .. } => CapabilityLifecycleState::Retired,
819        }
820    }
821
822    /// Returns the deprecation announcement time when applicable.
823    #[must_use]
824    pub const fn announced_at(&self) -> Option<Timestamp> {
825        match self.0 {
826            CapabilityLifecycleValue::Deprecated { announced_at, .. } => Some(announced_at),
827            CapabilityLifecycleValue::Active | CapabilityLifecycleValue::Retired { .. } => None,
828        }
829    }
830
831    /// Returns the optional published sunset time.
832    #[must_use]
833    pub const fn sunset_at(&self) -> Option<Timestamp> {
834        match self.0 {
835            CapabilityLifecycleValue::Deprecated { sunset_at, .. } => sunset_at,
836            CapabilityLifecycleValue::Active | CapabilityLifecycleValue::Retired { .. } => None,
837        }
838    }
839
840    /// Returns the retirement time when applicable.
841    #[must_use]
842    pub const fn retired_at(&self) -> Option<Timestamp> {
843        match self.0 {
844            CapabilityLifecycleValue::Retired { retired_at, .. } => Some(retired_at),
845            CapabilityLifecycleValue::Active | CapabilityLifecycleValue::Deprecated { .. } => None,
846        }
847    }
848
849    /// Returns migration guidance when deprecated or retired.
850    #[must_use]
851    pub const fn notice(&self) -> Option<&CapabilityDescription> {
852        match &self.0 {
853            CapabilityLifecycleValue::Deprecated { notice, .. }
854            | CapabilityLifecycleValue::Retired { notice, .. } => Some(notice),
855            CapabilityLifecycleValue::Active => None,
856        }
857    }
858
859    /// Returns the optional owner-qualified replacement capability.
860    #[must_use]
861    pub const fn replacement(&self) -> Option<&CapabilityIdentity> {
862        match &self.0 {
863            CapabilityLifecycleValue::Deprecated { replacement, .. }
864            | CapabilityLifecycleValue::Retired { replacement, .. } => replacement.as_ref(),
865            CapabilityLifecycleValue::Active => None,
866        }
867    }
868}
869
870impl Default for CapabilityLifecycle {
871    fn default() -> Self {
872        Self::active()
873    }
874}
875
876impl fmt::Debug for CapabilityLifecycle {
877    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
878        let mut debug = formatter.debug_struct("CapabilityLifecycle");
879        debug.field("state", &self.state());
880        if let Some(announced_at) = self.announced_at() {
881            debug.field("announced_at", &announced_at);
882        }
883        if let Some(sunset_at) = self.sunset_at() {
884            debug.field("sunset_at", &sunset_at);
885        }
886        if let Some(retired_at) = self.retired_at() {
887            debug.field("retired_at", &retired_at);
888        }
889        debug
890            .field("has_notice", &self.notice().is_some())
891            .field("has_replacement", &self.replacement().is_some())
892            .finish_non_exhaustive()
893    }
894}
895
896#[derive(Deserialize, JsonSchema)]
897#[serde(tag = "status", rename_all = "snake_case", deny_unknown_fields)]
898enum CapabilityLifecycleWire {
899    Active {},
900    Deprecated {
901        announced_at: Timestamp,
902        #[serde(default)]
903        sunset_at: Option<Timestamp>,
904        notice: CapabilityDescription,
905        #[serde(default)]
906        replacement: Option<CapabilityIdentity>,
907    },
908    Retired {
909        retired_at: Timestamp,
910        notice: CapabilityDescription,
911        #[serde(default)]
912        replacement: Option<CapabilityIdentity>,
913    },
914}
915
916#[derive(Serialize)]
917#[serde(tag = "status", rename_all = "snake_case")]
918enum CapabilityLifecycleWireRef<'a> {
919    Active {},
920    Deprecated {
921        announced_at: Timestamp,
922        #[serde(skip_serializing_if = "Option::is_none")]
923        sunset_at: Option<Timestamp>,
924        notice: &'a CapabilityDescription,
925        #[serde(skip_serializing_if = "Option::is_none")]
926        replacement: Option<&'a CapabilityIdentity>,
927    },
928    Retired {
929        retired_at: Timestamp,
930        notice: &'a CapabilityDescription,
931        #[serde(skip_serializing_if = "Option::is_none")]
932        replacement: Option<&'a CapabilityIdentity>,
933    },
934}
935
936impl Serialize for CapabilityLifecycle {
937    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
938    where
939        S: Serializer,
940    {
941        match &self.0 {
942            CapabilityLifecycleValue::Active => CapabilityLifecycleWireRef::Active {},
943            CapabilityLifecycleValue::Deprecated {
944                announced_at,
945                sunset_at,
946                notice,
947                replacement,
948            } => CapabilityLifecycleWireRef::Deprecated {
949                announced_at: *announced_at,
950                sunset_at: *sunset_at,
951                notice,
952                replacement: replacement.as_ref(),
953            },
954            CapabilityLifecycleValue::Retired {
955                retired_at,
956                notice,
957                replacement,
958            } => CapabilityLifecycleWireRef::Retired {
959                retired_at: *retired_at,
960                notice,
961                replacement: replacement.as_ref(),
962            },
963        }
964        .serialize(serializer)
965    }
966}
967
968impl<'de> Deserialize<'de> for CapabilityLifecycle {
969    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
970    where
971        D: Deserializer<'de>,
972    {
973        match CapabilityLifecycleWire::deserialize(deserializer)? {
974            CapabilityLifecycleWire::Active {} => Ok(Self::active()),
975            CapabilityLifecycleWire::Deprecated {
976                announced_at,
977                sunset_at,
978                notice,
979                replacement,
980            } => Self::deprecated(announced_at, sunset_at, notice, replacement)
981                .map_err(de::Error::custom),
982            CapabilityLifecycleWire::Retired {
983                retired_at,
984                notice,
985                replacement,
986            } => Ok(Self::retired(retired_at, notice, replacement)),
987        }
988    }
989}
990
991impl JsonSchema for CapabilityLifecycle {
992    fn schema_name() -> std::borrow::Cow<'static, str> {
993        "CapabilityLifecycle".into()
994    }
995
996    fn schema_id() -> std::borrow::Cow<'static, str> {
997        concat!(module_path!(), "::CapabilityLifecycle").into()
998    }
999
1000    fn json_schema(generator: &mut SchemaGenerator) -> Schema {
1001        CapabilityLifecycleWire::json_schema(generator)
1002    }
1003}
1004
1005/// Invalid capability lifecycle metadata.
1006#[derive(Clone, Debug, Eq, Error, PartialEq)]
1007#[non_exhaustive]
1008pub enum CapabilityLifecycleError {
1009    /// A sunset did not follow its deprecation announcement.
1010    #[error("capability sunset {sunset_at} must be later than announcement {announced_at}")]
1011    InvalidSunsetOrder {
1012        /// Time at which deprecation was announced.
1013        announced_at: Timestamp,
1014        /// Invalid proposed sunset time.
1015        sunset_at: Timestamp,
1016    },
1017}
1018
1019/// Common discovery metadata shared by specialized capability descriptors.
1020///
1021/// Model modalities, tool schemas, risk, and execution limits intentionally do
1022/// not live here; specialized descriptors make those required and type-safe.
1023/// The owner, lifecycle, scopes, and extensions are claims until a trusted
1024/// tenant registry authenticates the owner, pins this exact version, applies
1025/// policy, and snapshots the resulting descriptor for an execution attempt.
1026#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
1027#[serde(deny_unknown_fields)]
1028pub struct CapabilityMetadata {
1029    identity: CapabilityIdentity,
1030    kind: CapabilityKind,
1031    #[serde(skip_serializing_if = "Option::is_none")]
1032    title: Option<CapabilityTitle>,
1033    description: CapabilityDescription,
1034    lifecycle: CapabilityLifecycle,
1035    required_scopes: ScopeSet,
1036    extensions: Extensions,
1037}
1038
1039impl CapabilityMetadata {
1040    /// Constructs common metadata and checks cross-field lifecycle invariants.
1041    ///
1042    /// # Errors
1043    ///
1044    /// Returns [`CapabilityMetadataError`] when the lifecycle names the
1045    /// capability itself as its replacement.
1046    pub fn new(
1047        identity: CapabilityIdentity,
1048        kind: CapabilityKind,
1049        title: Option<CapabilityTitle>,
1050        description: CapabilityDescription,
1051        lifecycle: CapabilityLifecycle,
1052        required_scopes: ScopeSet,
1053        extensions: Extensions,
1054    ) -> Result<Self, CapabilityMetadataError> {
1055        if lifecycle.replacement() == Some(&identity) {
1056            return Err(CapabilityMetadataError::ReplacementIsSelf);
1057        }
1058        Ok(Self {
1059            identity,
1060            kind,
1061            title,
1062            description,
1063            lifecycle,
1064            required_scopes,
1065            extensions,
1066        })
1067    }
1068
1069    /// Returns the owner-qualified, version-pinned identity.
1070    #[must_use]
1071    pub const fn identity(&self) -> &CapabilityIdentity {
1072        &self.identity
1073    }
1074
1075    /// Returns the specialized descriptor classification.
1076    #[must_use]
1077    pub const fn kind(&self) -> CapabilityKind {
1078        self.kind
1079    }
1080
1081    /// Returns the optional human-readable display title.
1082    #[must_use]
1083    pub const fn title(&self) -> Option<&CapabilityTitle> {
1084        self.title.as_ref()
1085    }
1086
1087    /// Returns the exact registry-approved description text.
1088    #[must_use]
1089    pub const fn description(&self) -> &CapabilityDescription {
1090        &self.description
1091    }
1092
1093    /// Returns the validated lifecycle metadata.
1094    #[must_use]
1095    pub const fn lifecycle(&self) -> &CapabilityLifecycle {
1096        &self.lifecycle
1097    }
1098
1099    /// Returns scopes required before this capability can be selected.
1100    #[must_use]
1101    pub const fn required_scopes(&self) -> &ScopeSet {
1102        &self.required_scopes
1103    }
1104
1105    /// Returns bounded protocol/provider extension data.
1106    #[must_use]
1107    pub const fn extensions(&self) -> &Extensions {
1108        &self.extensions
1109    }
1110}
1111
1112impl fmt::Debug for CapabilityMetadata {
1113    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1114        formatter
1115            .debug_struct("CapabilityMetadata")
1116            .field("identity", &self.identity)
1117            .field("kind", &self.kind)
1118            .field("has_title", &self.title.is_some())
1119            .field("description_utf8_bytes", &self.description.len_bytes())
1120            .field("lifecycle", &self.lifecycle)
1121            .field("required_scopes", &self.required_scopes.len())
1122            .field("extensions", &self.extensions)
1123            .finish_non_exhaustive()
1124    }
1125}
1126
1127#[derive(Deserialize)]
1128#[serde(deny_unknown_fields)]
1129struct CapabilityMetadataWire {
1130    identity: CapabilityIdentity,
1131    kind: CapabilityKind,
1132    #[serde(default)]
1133    title: Option<CapabilityTitle>,
1134    description: CapabilityDescription,
1135    lifecycle: CapabilityLifecycle,
1136    required_scopes: ScopeSet,
1137    extensions: Extensions,
1138}
1139
1140impl<'de> Deserialize<'de> for CapabilityMetadata {
1141    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1142    where
1143        D: Deserializer<'de>,
1144    {
1145        let wire = CapabilityMetadataWire::deserialize(deserializer)?;
1146        Self::new(
1147            wire.identity,
1148            wire.kind,
1149            wire.title,
1150            wire.description,
1151            wire.lifecycle,
1152            wire.required_scopes,
1153            wire.extensions,
1154        )
1155        .map_err(de::Error::custom)
1156    }
1157}
1158
1159/// Invalid cross-field capability metadata.
1160#[derive(Clone, Debug, Eq, Error, PartialEq)]
1161#[non_exhaustive]
1162pub enum CapabilityMetadataError {
1163    /// A deprecated or retired capability pointed to itself as replacement.
1164    #[error("capability lifecycle replacement must not equal its own identity")]
1165    ReplacementIsSelf,
1166}
1167
1168fn validate_capability_name(value: &str) -> Result<(), CapabilityNameError> {
1169    if value.is_empty() {
1170        return Err(CapabilityNameError::Empty);
1171    }
1172    if value.len() > CapabilityName::MAX_LEN {
1173        return Err(CapabilityNameError::TooLong {
1174            max: CapabilityName::MAX_LEN,
1175            actual: value.len(),
1176        });
1177    }
1178
1179    if let Some((index, _)) = value
1180        .bytes()
1181        .enumerate()
1182        .find(|(_, byte)| !byte.is_ascii_alphanumeric() && !matches!(byte, b'_' | b'-' | b'.'))
1183    {
1184        return Err(CapabilityNameError::InvalidByte { index });
1185    }
1186
1187    Ok(())
1188}
1189
1190#[cfg(test)]
1191mod tests {
1192    use super::*;
1193    use proptest::prelude::*;
1194    use serde_json::{Value, from_value, json, to_value};
1195
1196    use crate::{BoundedJson, ExtensionKey, ExtensionValue, IssuerId, Scope, SubjectId};
1197
1198    fn principal(subject: &str) -> PrincipalIdentity {
1199        PrincipalIdentity::new(
1200            "https://issuer.example.com/tenant"
1201                .parse::<IssuerId>()
1202                .unwrap(),
1203            subject.parse::<SubjectId>().unwrap(),
1204        )
1205    }
1206
1207    fn identity(name: &str, version: Version) -> CapabilityIdentity {
1208        CapabilityIdentity::new(
1209            principal("registry-owner"),
1210            CapabilityReference::new(name.parse().unwrap(), version),
1211        )
1212    }
1213
1214    fn timestamp(value: &str) -> Timestamp {
1215        value.parse().unwrap()
1216    }
1217
1218    fn description(value: &str) -> CapabilityDescription {
1219        CapabilityDescription::new(value).unwrap()
1220    }
1221
1222    fn scopes(values: &[&str]) -> ScopeSet {
1223        ScopeSet::try_new(values.iter().map(|value| value.parse::<Scope>().unwrap())).unwrap()
1224    }
1225
1226    fn extensions(secret: &str) -> Extensions {
1227        Extensions::try_new([(
1228            ExtensionKey::new("com.example.discovery").unwrap(),
1229            ExtensionValue::opaque(
1230                BoundedJson::try_from_value(json!({ "secret": secret })).unwrap(),
1231            ),
1232        )])
1233        .unwrap()
1234    }
1235
1236    #[test]
1237    fn capability_names_preserve_all_valid_spellings() {
1238        let all_allowed = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.-";
1239        assert_eq!(
1240            all_allowed.parse::<CapabilityName>().unwrap().as_str(),
1241            all_allowed
1242        );
1243
1244        for value in [
1245            "getUser",
1246            "DATA_EXPORT_v2",
1247            "admin.tools.list",
1248            "ops.restart-service",
1249            ".",
1250            "-",
1251            "0",
1252        ] {
1253            let name = value.parse::<CapabilityName>().unwrap();
1254            assert_eq!(name.as_str(), value);
1255            assert_eq!(name.to_string(), value);
1256            assert_eq!(to_value(&name).unwrap(), Value::from(value));
1257        }
1258
1259        let maximum = "a".repeat(CapabilityName::MAX_LEN);
1260        assert_eq!(maximum.parse::<CapabilityName>().unwrap().as_str(), maximum);
1261    }
1262
1263    #[test]
1264    fn capability_names_are_case_sensitive() {
1265        let lower = "getuser".parse::<CapabilityName>().unwrap();
1266        let mixed = "getUser".parse::<CapabilityName>().unwrap();
1267        assert_ne!(lower, mixed);
1268    }
1269
1270    #[test]
1271    fn capability_names_reject_out_of_contract_input() {
1272        assert_eq!(
1273            "".parse::<CapabilityName>(),
1274            Err(CapabilityNameError::Empty)
1275        );
1276        assert_eq!(
1277            "a".repeat(CapabilityName::MAX_LEN + 1)
1278                .parse::<CapabilityName>(),
1279            Err(CapabilityNameError::TooLong {
1280                max: CapabilityName::MAX_LEN,
1281                actual: CapabilityName::MAX_LEN + 1,
1282            })
1283        );
1284
1285        for (value, index) in [
1286            ("restart service", 7),
1287            ("ops/restart", 3),
1288            ("ops:restart", 3),
1289            ("tool,name", 4),
1290            ("tool\\name", 4),
1291            ("tool\nname", 4),
1292            ("工具", 0),
1293        ] {
1294            assert_eq!(
1295                value.parse::<CapabilityName>(),
1296                Err(CapabilityNameError::InvalidByte { index }),
1297                "accepted {value:?}"
1298            );
1299        }
1300
1301        for byte in 0_u8..=0x7f {
1302            if byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.') {
1303                continue;
1304            }
1305            let value = String::from_utf8(vec![byte]).unwrap();
1306            assert_eq!(
1307                value.parse::<CapabilityName>(),
1308                Err(CapabilityNameError::InvalidByte { index: 0 }),
1309                "accepted ASCII byte 0x{byte:02x}"
1310            );
1311        }
1312    }
1313
1314    #[test]
1315    fn capability_name_serde_and_schema_enforce_the_wire_contract() {
1316        let name = "ops.restart-service".parse::<CapabilityName>().unwrap();
1317        assert_eq!(
1318            from_value::<CapabilityName>(json!(name.as_str())).unwrap(),
1319            name
1320        );
1321        assert!(from_value::<CapabilityName>(json!(42)).is_err());
1322        assert!(from_value::<CapabilityName>(Value::Null).is_err());
1323
1324        let schema = to_value(schemars::schema_for!(CapabilityName)).unwrap();
1325        assert_eq!(schema["type"], "string");
1326        assert_eq!(schema["minLength"], 1);
1327        assert_eq!(schema["maxLength"], CapabilityName::MAX_LEN);
1328        assert_eq!(schema["pattern"], CAPABILITY_NAME_PATTERN);
1329    }
1330
1331    #[test]
1332    fn capability_references_pin_name_and_version_in_a_closed_object() {
1333        let reference = CapabilityReference::new(
1334            "ops.restart-service".parse().unwrap(),
1335            Version::new(2, 3, 4),
1336        );
1337        let expected = json!({
1338            "name": "ops.restart-service",
1339            "version": "2.3.4"
1340        });
1341        assert_eq!(to_value(&reference).unwrap(), expected);
1342        assert_eq!(
1343            from_value::<CapabilityReference>(expected).unwrap(),
1344            reference
1345        );
1346
1347        assert!(
1348            from_value::<CapabilityReference>(json!({
1349                "name": "ops.restart-service",
1350                "version": "2.3.4",
1351                "extra": true
1352            }))
1353            .is_err()
1354        );
1355
1356        let schema = to_value(schemars::schema_for!(CapabilityReference)).unwrap();
1357        assert_eq!(schema["type"], "object");
1358        assert_eq!(schema["additionalProperties"], false);
1359        assert_eq!(schema["required"], json!(["name", "version"]));
1360    }
1361
1362    #[test]
1363    fn capability_identities_are_owner_qualified_and_closed() {
1364        let identity = identity("payments.capture", Version::new(2, 1, 0));
1365        assert_eq!(identity.owner(), &principal("registry-owner"));
1366        assert_eq!(identity.capability().name().as_str(), "payments.capture");
1367        assert_eq!(identity.name().as_str(), "payments.capture");
1368        assert_eq!(identity.version(), Version::new(2, 1, 0));
1369
1370        let encoded = to_value(&identity).unwrap();
1371        assert_eq!(
1372            encoded,
1373            json!({
1374                "owner": {
1375                    "issuer": "https://issuer.example.com/tenant",
1376                    "subject": "registry-owner"
1377                },
1378                "capability": {
1379                    "name": "payments.capture",
1380                    "version": "2.1.0"
1381                }
1382            })
1383        );
1384        assert_eq!(from_value::<CapabilityIdentity>(encoded).unwrap(), identity);
1385
1386        let other_owner =
1387            CapabilityIdentity::new(principal("other-owner"), identity.capability().clone());
1388        assert_ne!(other_owner, identity);
1389
1390        assert!(
1391            from_value::<CapabilityIdentity>(json!({
1392                "owner": {
1393                    "issuer": "https://issuer.example.com/tenant",
1394                    "subject": "registry-owner"
1395                },
1396                "capability": {
1397                    "name": "payments.capture",
1398                    "version": "2.1.0"
1399                },
1400                "trusted": true
1401            }))
1402            .is_err()
1403        );
1404
1405        let schema = to_value(schemars::schema_for!(CapabilityIdentity)).unwrap();
1406        assert_eq!(schema["type"], "object");
1407        assert_eq!(schema["additionalProperties"], false);
1408        assert_eq!(schema["required"], json!(["owner", "capability"]));
1409    }
1410
1411    #[test]
1412    fn capability_text_preserves_unicode_and_redacts_debug() {
1413        let title_secret = "财务付款工具 secret-title";
1414        let title = CapabilityTitle::new(title_secret).unwrap();
1415        assert_eq!(title.as_str(), title_secret);
1416        assert_eq!(title.len_bytes(), title_secret.len());
1417        assert!(!format!("{title:?}").contains(title_secret));
1418        assert_eq!(
1419            from_value::<CapabilityTitle>(to_value(&title).unwrap()).unwrap(),
1420            title
1421        );
1422
1423        let description_secret =
1424            "Create a payment only after approval.\n\tNever infer the currency. secret-description";
1425        let description = CapabilityDescription::new(description_secret).unwrap();
1426        assert_eq!(description.as_str(), description_secret);
1427        assert_eq!(description.len_bytes(), description_secret.len());
1428        assert!(!format!("{description:?}").contains(description_secret));
1429        assert_eq!(
1430            from_value::<CapabilityDescription>(to_value(&description).unwrap()).unwrap(),
1431            description
1432        );
1433
1434        assert_eq!(
1435            String::from(CapabilityTitle::new("Display title").unwrap()),
1436            "Display title"
1437        );
1438        assert_eq!(
1439            String::from(CapabilityDescription::new("Detailed description").unwrap()),
1440            "Detailed description"
1441        );
1442    }
1443
1444    #[test]
1445    fn capability_titles_enforce_single_line_unambiguous_bounds() {
1446        assert_eq!(CapabilityTitle::new(""), Err(CapabilityTitleError::Empty));
1447        assert_eq!(
1448            CapabilityTitle::new("a".repeat(CapabilityTitle::MAX_BYTES + 1)),
1449            Err(CapabilityTitleError::TooLong {
1450                max: CapabilityTitle::MAX_BYTES,
1451                actual: CapabilityTitle::MAX_BYTES + 1,
1452            })
1453        );
1454        let exact_multibyte = "é".repeat(CapabilityTitle::MAX_BYTES / 2);
1455        assert!(CapabilityTitle::new(exact_multibyte).is_ok());
1456
1457        for value in [" title", "title ", "\ttitle", "title\n"] {
1458            assert_eq!(
1459                CapabilityTitle::new(value),
1460                Err(CapabilityTitleError::BoundaryWhitespace),
1461                "accepted {value:?}"
1462            );
1463        }
1464
1465        for scalar in [
1466            '\u{0000}',
1467            '\u{001f}',
1468            '\u{007f}',
1469            '\u{0085}',
1470            '\u{061c}',
1471            '\u{200e}',
1472            '\u{200f}',
1473            '\u{2028}',
1474            '\u{2029}',
1475            '\u{202a}',
1476            '\u{202e}',
1477            '\u{2066}',
1478            '\u{2069}',
1479            '\u{fdd0}',
1480            '\u{10ffff}',
1481        ] {
1482            let value = format!("a{scalar}b");
1483            assert!(
1484                matches!(
1485                    CapabilityTitle::new(&value),
1486                    Err(CapabilityTitleError::DisallowedCodePoint { .. })
1487                ),
1488                "accepted U+{:04X}",
1489                u32::from(scalar)
1490            );
1491        }
1492
1493        assert!(from_value::<CapabilityTitle>(json!(42)).is_err());
1494        assert!(from_value::<CapabilityTitle>(Value::Null).is_err());
1495        let schema = to_value(schemars::schema_for!(CapabilityTitle)).unwrap();
1496        assert_eq!(schema["maxLength"], CapabilityTitle::MAX_BYTES);
1497    }
1498
1499    #[test]
1500    fn capability_descriptions_enforce_prompt_and_resource_safety() {
1501        assert_eq!(
1502            CapabilityDescription::new(""),
1503            Err(CapabilityDescriptionError::Empty)
1504        );
1505        assert_eq!(
1506            CapabilityDescription::new("a".repeat(CapabilityDescription::MAX_BYTES + 1)),
1507            Err(CapabilityDescriptionError::TooLong {
1508                max: CapabilityDescription::MAX_BYTES,
1509                actual: CapabilityDescription::MAX_BYTES + 1,
1510            })
1511        );
1512        assert!(CapabilityDescription::new("a".repeat(CapabilityDescription::MAX_BYTES)).is_ok());
1513        assert!(CapabilityDescription::new("line one\n\tline two\rline three").is_ok());
1514
1515        for value in [
1516            " description",
1517            "description ",
1518            "\ndescription",
1519            "description\r",
1520        ] {
1521            assert_eq!(
1522                CapabilityDescription::new(value),
1523                Err(CapabilityDescriptionError::BoundaryWhitespace),
1524                "accepted {value:?}"
1525            );
1526        }
1527
1528        for code_point in [0_u32..=0x1f, 0x7f..=0x9f].into_iter().flatten() {
1529            let scalar = char::from_u32(code_point).unwrap();
1530            let value = format!("a{scalar}b");
1531            if matches!(scalar, '\t' | '\n' | '\r') {
1532                assert!(CapabilityDescription::new(value).is_ok());
1533            } else {
1534                assert!(matches!(
1535                    CapabilityDescription::new(value),
1536                    Err(CapabilityDescriptionError::DisallowedCodePoint { .. })
1537                ));
1538            }
1539        }
1540
1541        for scalar in [
1542            '\u{061c}',
1543            '\u{200e}',
1544            '\u{200f}',
1545            '\u{202a}',
1546            '\u{202e}',
1547            '\u{2066}',
1548            '\u{2069}',
1549            '\u{fdd0}',
1550            '\u{10ffff}',
1551        ] {
1552            let value = format!("a{scalar}b");
1553            assert!(matches!(
1554                CapabilityDescription::new(value),
1555                Err(CapabilityDescriptionError::DisallowedCodePoint { .. })
1556            ));
1557        }
1558
1559        assert!(from_value::<CapabilityDescription>(json!(42)).is_err());
1560        let schema = to_value(schemars::schema_for!(CapabilityDescription)).unwrap();
1561        assert_eq!(schema["maxLength"], CapabilityDescription::MAX_BYTES);
1562    }
1563
1564    #[test]
1565    fn capability_kinds_have_closed_canonical_wire_values() {
1566        for (kind, expected) in [
1567            (CapabilityKind::Model, "model"),
1568            (CapabilityKind::Tool, "tool"),
1569            (CapabilityKind::Agent, "agent"),
1570            (CapabilityKind::Workflow, "workflow"),
1571            (CapabilityKind::Application, "application"),
1572        ] {
1573            assert_eq!(to_value(kind).unwrap(), Value::from(expected));
1574            assert_eq!(from_value::<CapabilityKind>(json!(expected)).unwrap(), kind);
1575        }
1576        assert!(from_value::<CapabilityKind>(json!("unknown")).is_err());
1577        assert!(from_value::<CapabilityKind>(Value::Null).is_err());
1578    }
1579
1580    #[test]
1581    fn capability_lifecycles_are_closed_and_time_ordered() {
1582        let active = CapabilityLifecycle::active();
1583        assert_eq!(active, CapabilityLifecycle::default());
1584        assert_eq!(active.state(), CapabilityLifecycleState::Active);
1585        assert_eq!(active.announced_at(), None);
1586        assert_eq!(active.sunset_at(), None);
1587        assert_eq!(active.retired_at(), None);
1588        assert!(active.notice().is_none());
1589        assert!(active.replacement().is_none());
1590        assert_eq!(to_value(&active).unwrap(), json!({ "status": "active" }));
1591
1592        let announced_at = timestamp("2026-08-29T00:00:00.000000Z");
1593        let sunset_at = timestamp("2027-02-28T00:00:00.000000Z");
1594        let replacement = identity("payments.capture", Version::new(3, 0, 0));
1595        let notice_secret = "Migrate to payments.capture 3.0.0 before retirement.";
1596        let deprecated = CapabilityLifecycle::deprecated(
1597            announced_at,
1598            Some(sunset_at),
1599            description(notice_secret),
1600            Some(replacement.clone()),
1601        )
1602        .unwrap();
1603        assert_eq!(deprecated.state(), CapabilityLifecycleState::Deprecated);
1604        assert_eq!(deprecated.announced_at(), Some(announced_at));
1605        assert_eq!(deprecated.sunset_at(), Some(sunset_at));
1606        assert_eq!(deprecated.retired_at(), None);
1607        assert_eq!(deprecated.notice().unwrap().as_str(), notice_secret);
1608        assert_eq!(deprecated.replacement(), Some(&replacement));
1609        assert!(!format!("{deprecated:?}").contains(notice_secret));
1610
1611        let encoded = to_value(&deprecated).unwrap();
1612        assert_eq!(encoded["status"], "deprecated");
1613        assert!(encoded.get("announced_at").is_some());
1614        assert!(encoded.get("sunset_at").is_some());
1615        assert_eq!(
1616            from_value::<CapabilityLifecycle>(encoded).unwrap(),
1617            deprecated
1618        );
1619
1620        for invalid_sunset in [announced_at, timestamp("2026-08-28T23:59:59.999999Z")] {
1621            assert_eq!(
1622                CapabilityLifecycle::deprecated(
1623                    announced_at,
1624                    Some(invalid_sunset),
1625                    description("Migrate before retirement."),
1626                    None,
1627                ),
1628                Err(CapabilityLifecycleError::InvalidSunsetOrder {
1629                    announced_at,
1630                    sunset_at: invalid_sunset,
1631                })
1632            );
1633        }
1634
1635        let retired_at = timestamp("2027-02-28T00:00:00.000001Z");
1636        let retired = CapabilityLifecycle::retired(
1637            retired_at,
1638            description("This capability is retained only for history."),
1639            Some(replacement),
1640        );
1641        assert_eq!(retired.state(), CapabilityLifecycleState::Retired);
1642        assert_eq!(retired.retired_at(), Some(retired_at));
1643        assert_eq!(
1644            from_value::<CapabilityLifecycle>(to_value(&retired).unwrap()).unwrap(),
1645            retired
1646        );
1647
1648        for invalid in [
1649            json!({ "status": "unknown" }),
1650            json!({ "status": "active", "notice": "unexpected" }),
1651            json!({ "status": "deprecated", "announced_at": announced_at }),
1652            json!({
1653                "status": "deprecated",
1654                "announced_at": sunset_at,
1655                "sunset_at": announced_at,
1656                "notice": "Invalid order."
1657            }),
1658            json!({ "status": "retired", "notice": "Missing timestamp." }),
1659            Value::Null,
1660        ] {
1661            assert!(
1662                from_value::<CapabilityLifecycle>(invalid.clone()).is_err(),
1663                "accepted lifecycle {invalid}"
1664            );
1665        }
1666        assert!(
1667            serde_json::from_str::<CapabilityLifecycle>(r#"{"status":"active","status":"active"}"#)
1668                .is_err()
1669        );
1670    }
1671
1672    #[test]
1673    fn capability_metadata_revalidates_cross_field_invariants_and_redacts_text() {
1674        let subject = identity("payments.capture", Version::new(2, 1, 0));
1675        let replacement = identity("payments.capture", Version::new(3, 0, 0));
1676        let title_secret = "Capture payment secret-title";
1677        let description_secret = "Capture one approved payment. secret-description";
1678        let extension_secret = "extension-secret";
1679        let lifecycle = CapabilityLifecycle::deprecated(
1680            timestamp("2026-08-29T00:00:00.000000Z"),
1681            Some(timestamp("2027-02-28T00:00:00.000000Z")),
1682            description("Migrate to the replacement before sunset."),
1683            Some(replacement),
1684        )
1685        .unwrap();
1686        let metadata = CapabilityMetadata::new(
1687            subject.clone(),
1688            CapabilityKind::Tool,
1689            Some(CapabilityTitle::new(title_secret).unwrap()),
1690            description(description_secret),
1691            lifecycle,
1692            scopes(&["payments:read", "payments:write"]),
1693            extensions(extension_secret),
1694        )
1695        .unwrap();
1696
1697        assert_eq!(metadata.identity(), &subject);
1698        assert_eq!(metadata.kind(), CapabilityKind::Tool);
1699        assert_eq!(metadata.title().unwrap().as_str(), title_secret);
1700        assert_eq!(metadata.description().as_str(), description_secret);
1701        assert_eq!(metadata.required_scopes().len(), 2);
1702        assert_eq!(metadata.extensions().len(), 1);
1703        assert_eq!(
1704            metadata.lifecycle().state(),
1705            CapabilityLifecycleState::Deprecated
1706        );
1707
1708        let debug = format!("{metadata:?}");
1709        assert!(!debug.contains(title_secret));
1710        assert!(!debug.contains(description_secret));
1711        assert!(!debug.contains(extension_secret));
1712
1713        let encoded = to_value(&metadata).unwrap();
1714        assert_eq!(
1715            from_value::<CapabilityMetadata>(encoded.clone()).unwrap(),
1716            metadata
1717        );
1718        let mut unknown = encoded.clone();
1719        unknown["authenticated"] = json!(true);
1720        assert!(from_value::<CapabilityMetadata>(unknown).is_err());
1721
1722        let self_replacing = CapabilityLifecycle::deprecated(
1723            timestamp("2026-08-29T00:00:00.000000Z"),
1724            None,
1725            description("Use a replacement."),
1726            Some(subject.clone()),
1727        )
1728        .unwrap();
1729        assert_eq!(
1730            CapabilityMetadata::new(
1731                subject.clone(),
1732                CapabilityKind::Tool,
1733                None,
1734                description("Capture one payment."),
1735                self_replacing,
1736                ScopeSet::empty(),
1737                Extensions::default(),
1738            ),
1739            Err(CapabilityMetadataError::ReplacementIsSelf)
1740        );
1741
1742        let mut invalid_wire = encoded;
1743        invalid_wire["lifecycle"]["replacement"] = to_value(&subject).unwrap();
1744        assert!(from_value::<CapabilityMetadata>(invalid_wire).is_err());
1745    }
1746
1747    #[test]
1748    fn capability_metadata_and_lifecycle_schemas_are_closed() {
1749        let schema = to_value(schemars::schema_for!(CapabilityMetadata)).unwrap();
1750        assert_eq!(schema["type"], "object");
1751        assert_eq!(schema["additionalProperties"], false);
1752        let required = schema["required"].as_array().unwrap();
1753        for field in [
1754            "identity",
1755            "kind",
1756            "description",
1757            "lifecycle",
1758            "required_scopes",
1759            "extensions",
1760        ] {
1761            assert!(required.contains(&Value::from(field)));
1762        }
1763        assert!(!required.contains(&Value::from("title")));
1764
1765        let lifecycle = to_value(schemars::schema_for!(CapabilityLifecycle)).unwrap();
1766        let variants = lifecycle["oneOf"].as_array().unwrap();
1767        assert_eq!(variants.len(), 3);
1768        assert!(
1769            variants
1770                .iter()
1771                .all(|variant| variant["additionalProperties"] == false)
1772        );
1773    }
1774
1775    proptest! {
1776        #[test]
1777        fn valid_description_text_round_trips_exactly(
1778            first in "[A-Za-z0-9]",
1779            middle in "[A-Za-z0-9 \\t\\n\\r]{0,512}",
1780            last in "[A-Za-z0-9]",
1781        ) {
1782            let value = format!("{first}{middle}{last}");
1783            let description = CapabilityDescription::new(&value).unwrap();
1784            prop_assert_eq!(description.as_str(), value.as_str());
1785            let encoded = serde_json::to_vec(&description).unwrap();
1786            let decoded = serde_json::from_slice::<CapabilityDescription>(&encoded).unwrap();
1787            prop_assert_eq!(decoded, description);
1788        }
1789
1790        #[test]
1791        fn sunset_order_is_strict_for_all_representable_instants(
1792            announced_micros in -1_000_000_000_000_i64..1_000_000_000_000_i64,
1793            delta in 1_i64..1_000_000_000_i64,
1794        ) {
1795            let announced_at = Timestamp::from_unix_micros(announced_micros).unwrap();
1796            let sunset_at = Timestamp::from_unix_micros(announced_micros + delta).unwrap();
1797            prop_assert!(CapabilityLifecycle::deprecated(
1798                announced_at,
1799                Some(sunset_at),
1800                description("Migrate before sunset."),
1801                None,
1802            ).is_ok());
1803            prop_assert!(CapabilityLifecycle::deprecated(
1804                sunset_at,
1805                Some(announced_at),
1806                description("Invalid reverse ordering."),
1807                None,
1808            ).is_err());
1809        }
1810    }
1811}