Skip to main content

dekopon_core/
lib.rs

1#![forbid(unsafe_code)]
2#![cfg_attr(test, allow(clippy::unwrap_used))]
3#![cfg_attr(
4    test,
5    allow(
6        clippy::disallowed_methods,
7        clippy::disallowed_types,
8        reason = "tests spawn, join and drain freely; production sites carry their own expectation"
9    )
10)]
11pub mod asset;
12pub mod github;
13
14#[cfg(feature = "native")]
15pub mod base64;
16
17mod accept;
18mod attribute;
19#[cfg(feature = "cli")]
20mod cli_error;
21mod diagnostics;
22#[cfg(unix)]
23pub mod env_file;
24mod failure;
25#[cfg(unix)]
26pub mod fragments;
27#[cfg(unix)]
28pub mod private_file;
29mod redaction;
30mod skill;
31mod space;
32mod subject;
33mod trace;
34#[cfg(unix)]
35mod trusted_file;
36mod vm;
37
38use std::{fmt, str::FromStr};
39
40use serde::{Deserialize, Deserializer, Serialize, de::Error as _};
41use thiserror::Error;
42
43pub use accept::{ACCEPT_BACKOFF_MS, MAX_ACCEPT_BACKOFF_MS, retryable_accept_error};
44pub use attribute::{BoundedDisplay, MAX_ATTRIBUTE_BYTES, bounded_attribute, bounded_display};
45#[cfg(feature = "cli")]
46pub use cli_error::render_cli_error;
47pub use diagnostics::{MAX_PROBLEM_BYTES, MAX_RENDERED_PROBLEMS, bounded_problems, error_chain};
48pub use failure::{MAX_FAILURE_CODE_BYTES, MAX_FAILURE_MESSAGE_BYTES, ProviderFailureDetail};
49pub use redaction::{REDACTION_MARKER, Redacted, redaction_marker, serialize_exposed};
50pub use skill::{
51    MAX_SKILL_FILE_BYTES, MAX_SKILL_NAME_LENGTH, MAX_SKILL_RESOURCE_BYTES,
52    MAX_SKILL_RESOURCE_DEPTH, MAX_SKILL_RESOURCES, MAX_SKILL_TOTAL_BYTES, SKILL_FILE_NAME, SkillId,
53    SkillIdError,
54};
55pub use space::{SpaceBinding, SpaceChannel, SpaceKey, SpaceTransport, SpaceWorkspace};
56pub use subject::{
57    AttestedSubject, Namespace, PrincipalKind, Subject, SubjectError, SubjectField, SubjectKind,
58    SubjectScope,
59};
60pub use trace::{TraceId, TraceIdError};
61#[cfg(unix)]
62pub use trusted_file::{
63    AncestorOwners, AncestorPolicy, FileHygieneError, FileTier, check_trusted_ancestors,
64    check_trusted_metadata, read_trusted_file,
65};
66pub use vm::{VM_SESSION_HEADER, VmSession};
67
68pub(crate) const MAX_IDENTIFIER_LENGTH: usize = 253;
69pub const MAX_SECRET_DRN_LENGTH: usize = 512;
70pub const MAX_SECRET_USERNAME_LENGTH: usize = 256;
71
72pub const PROVIDER_COMPONENT_EXTENSION: &str = "wasm";
73
74pub const RESERVED_COMMAND_WORDS: &[&str] = &[
75    ".", ":", "[", "[[", "]]", "awk", "base64", "bg", "break", "cap", "case", "cat", "continue",
76    "cut", "declare", "do", "done", "echo", "elif", "else", "esac", "eval", "exec", "exit",
77    "export", "false", "fg", "fi", "for", "function", "grep", "head", "if", "in", "jobs", "jq",
78    "kill", "local", "printf", "progress", "read", "return", "sed", "select", "set", "shift",
79    "sleep", "sort", "source", "tail", "test", "then", "trap", "true", "uniq", "unset", "until",
80    "wait", "wc", "while", "xargs",
81];
82
83#[derive(Clone, Debug, Eq, Error, PartialEq)]
84pub enum IdentifierError {
85    #[error("{kind} identifier must not be empty")]
86    Empty { kind: &'static str },
87    #[error("{kind} identifier is {length} bytes; the maximum is {maximum}")]
88    TooLong {
89        kind: &'static str,
90        length: usize,
91        maximum: usize,
92    },
93    #[error(
94        "{kind} identifier must start with a lowercase ASCII letter or digit, found {character:?}"
95    )]
96    InvalidStart { kind: &'static str, character: char },
97    #[error(
98        "{kind} identifier must end with a lowercase ASCII letter or digit, found {character:?}"
99    )]
100    InvalidEnd { kind: &'static str, character: char },
101    #[error(
102        "{kind} identifier contains invalid character {character:?} at byte {index}; use lowercase ASCII letters, digits, '.', '-', or '_'"
103    )]
104    InvalidCharacter {
105        kind: &'static str,
106        index: usize,
107        character: char,
108    },
109    #[error("{kind} identifier contains adjacent separators at byte {index}")]
110    AdjacentSeparators { kind: &'static str, index: usize },
111}
112
113fn is_edge_character(character: char) -> bool {
114    character.is_ascii_lowercase() || character.is_ascii_digit()
115}
116
117fn is_separator(character: char) -> bool {
118    matches!(character, '.' | '-' | '_')
119}
120
121fn validate_identifier(value: &str, kind: &'static str) -> Result<(), IdentifierError> {
122    if value.is_empty() {
123        return Err(IdentifierError::Empty { kind });
124    }
125    if value.len() > MAX_IDENTIFIER_LENGTH {
126        return Err(IdentifierError::TooLong {
127            kind,
128            length: value.len(),
129            maximum: MAX_IDENTIFIER_LENGTH,
130        });
131    }
132
133    let mut characters = value.char_indices();
134    let (_, first) = characters.next().ok_or(IdentifierError::Empty { kind })?;
135    if !is_edge_character(first) {
136        return Err(IdentifierError::InvalidStart {
137            kind,
138            character: first,
139        });
140    }
141
142    let mut previous_was_separator = false;
143    for (index, character) in value.char_indices() {
144        if !is_edge_character(character) && !is_separator(character) {
145            return Err(IdentifierError::InvalidCharacter {
146                kind,
147                index,
148                character,
149            });
150        }
151        if is_separator(character) && previous_was_separator {
152            return Err(IdentifierError::AdjacentSeparators { kind, index });
153        }
154        previous_was_separator = is_separator(character);
155    }
156
157    let last = value
158        .chars()
159        .next_back()
160        .ok_or(IdentifierError::Empty { kind })?;
161    if !is_edge_character(last) {
162        return Err(IdentifierError::InvalidEnd {
163            kind,
164            character: last,
165        });
166    }
167
168    Ok(())
169}
170
171macro_rules! identifier {
172    ($name:ident, $label:literal, $docs:literal) => {
173        #[doc = $docs]
174        #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
175        #[serde(transparent)]
176        pub struct $name(String);
177
178        impl $name {
179            #[must_use]
180            pub fn as_str(&self) -> &str {
181                &self.0
182            }
183        }
184
185        impl fmt::Display for $name {
186            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
187                formatter.write_str(&self.0)
188            }
189        }
190
191        impl FromStr for $name {
192            type Err = IdentifierError;
193
194            fn from_str(value: &str) -> Result<Self, Self::Err> {
195                validate_identifier(value, $label)?;
196                Ok(Self(value.to_owned()))
197            }
198        }
199
200        impl TryFrom<String> for $name {
201            type Error = IdentifierError;
202
203            fn try_from(value: String) -> Result<Self, Self::Error> {
204                validate_identifier(&value, $label)?;
205                Ok(Self(value))
206            }
207        }
208
209        impl TryFrom<&str> for $name {
210            type Error = IdentifierError;
211
212            fn try_from(value: &str) -> Result<Self, Self::Error> {
213                value.parse()
214            }
215        }
216
217        impl From<$name> for String {
218            fn from(value: $name) -> Self {
219                value.0
220            }
221        }
222
223        impl<'de> Deserialize<'de> for $name {
224            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
225            where
226                D: Deserializer<'de>,
227            {
228                Self::try_from(String::deserialize(deserializer)?).map_err(D::Error::custom)
229            }
230        }
231    };
232}
233
234identifier!(AgentId, "agent", "A validated agent resource identifier.");
235identifier!(
236    CapabilityId,
237    "capability",
238    "A validated capability resource identifier."
239);
240identifier!(
241    ProviderId,
242    "provider",
243    "A validated capability-provider identifier."
244);
245identifier!(TaskId, "task", "A validated task identifier.");
246identifier!(
247    InvocationId,
248    "invocation",
249    "A validated capability invocation identifier."
250);
251identifier!(
252    TransportId,
253    "transport",
254    "A validated owner-configured chat transport identifier."
255);
256identifier!(
257    PrincipalId,
258    "principal",
259    "A validated authenticated principal identifier."
260);
261identifier!(GroupId, "group", "A validated principal group identifier.");
262
263#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
264#[serde(transparent)]
265pub struct SecretDrn(String);
266
267impl SecretDrn {
268    #[must_use]
269    pub fn as_str(&self) -> &str {
270        &self.0
271    }
272}
273
274impl fmt::Display for SecretDrn {
275    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
276        formatter.write_str(&self.0)
277    }
278}
279
280impl FromStr for SecretDrn {
281    type Err = SecretDrnError;
282
283    fn from_str(value: &str) -> Result<Self, Self::Err> {
284        Self::try_from(value.to_owned())
285    }
286}
287
288impl TryFrom<String> for SecretDrn {
289    type Error = SecretDrnError;
290
291    fn try_from(mut value: String) -> Result<Self, Self::Error> {
292        value.make_ascii_lowercase();
293        validate_secret_drn(&value)?;
294        Ok(Self(value))
295    }
296}
297
298impl<'de> Deserialize<'de> for SecretDrn {
299    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
300    where
301        D: Deserializer<'de>,
302    {
303        Self::try_from(String::deserialize(deserializer)?).map_err(D::Error::custom)
304    }
305}
306
307fn validate_secret_drn(value: &str) -> Result<(), SecretDrnError> {
308    if value.len() > MAX_SECRET_DRN_LENGTH {
309        return Err(SecretDrnError::TooLong {
310            length: value.len(),
311            maximum: MAX_SECRET_DRN_LENGTH,
312        });
313    }
314    let path = value
315        .strip_prefix("drn:secret:")
316        .ok_or(SecretDrnError::Malformed)?;
317    if path
318        .split('/')
319        .any(|segment| !valid_drn_component(segment) || matches!(segment, "." | ".."))
320    {
321        return Err(SecretDrnError::Malformed);
322    }
323    Ok(())
324}
325
326fn valid_drn_component(value: &str) -> bool {
327    !value.is_empty()
328        && value.len() <= MAX_IDENTIFIER_LENGTH
329        && value
330            .bytes()
331            .next()
332            .is_some_and(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
333        && value
334            .bytes()
335            .next_back()
336            .is_some_and(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
337        && value.bytes().all(|byte| {
338            byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'-' | b'_')
339        })
340}
341
342#[derive(Clone, Debug, Eq, Error, PartialEq)]
343pub enum SecretDrnError {
344    #[error("secret DRN must be `drn:secret:<path>`")]
345    Malformed,
346    #[error("secret DRN is {length} bytes; maximum is {maximum}")]
347    TooLong { length: usize, maximum: usize },
348}
349
350#[derive(Clone, Eq, PartialEq)]
351pub struct SecretBytes(Vec<u8>);
352
353impl SecretBytes {
354    #[must_use]
355    pub fn new(bytes: Vec<u8>) -> Self {
356        Self(bytes)
357    }
358
359    #[must_use]
360    pub fn expose(&self) -> &[u8] {
361        &self.0
362    }
363}
364
365impl fmt::Debug for SecretBytes {
366    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
367        formatter.write_str("[REDACTED]")
368    }
369}
370
371#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
372#[serde(rename_all = "camelCase")]
373pub enum SecretSinkKind {
374    HttpBearer,
375    HttpBasic,
376    HttpBot,
377}
378
379impl fmt::Display for SecretSinkKind {
380    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
381        formatter.write_str(match self {
382            Self::HttpBearer => "httpBearer",
383            Self::HttpBasic => "httpBasic",
384            Self::HttpBot => "httpBot",
385        })
386    }
387}
388
389#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
390#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
391pub enum SecretUseProposal {
392    HttpBearer {
393        secret: SecretDrn,
394    },
395    HttpBasic {
396        secret: SecretDrn,
397        #[serde(deserialize_with = "deserialize_secret_username")]
398        username: String,
399    },
400    HttpBot {
401        secret: SecretDrn,
402    },
403}
404
405impl SecretUseProposal {
406    #[must_use]
407    pub const fn secret(&self) -> &SecretDrn {
408        match self {
409            Self::HttpBearer { secret }
410            | Self::HttpBasic { secret, .. }
411            | Self::HttpBot { secret } => secret,
412        }
413    }
414
415    #[must_use]
416    pub const fn sink(&self) -> SecretSinkKind {
417        match self {
418            Self::HttpBearer { .. } => SecretSinkKind::HttpBearer,
419            Self::HttpBasic { .. } => SecretSinkKind::HttpBasic,
420            Self::HttpBot { .. } => SecretSinkKind::HttpBot,
421        }
422    }
423
424    #[must_use]
425    pub fn username(&self) -> Option<&str> {
426        match self {
427            Self::HttpBasic { username, .. } => Some(username),
428            Self::HttpBearer { .. } | Self::HttpBot { .. } => None,
429        }
430    }
431}
432
433fn deserialize_secret_username<'de, D>(deserializer: D) -> Result<String, D::Error>
434where
435    D: Deserializer<'de>,
436{
437    let username = String::deserialize(deserializer)?;
438    if username.is_empty()
439        || username.len() > MAX_SECRET_USERNAME_LENGTH
440        || username.contains(':')
441        || username
442            .bytes()
443            .any(|byte| byte.is_ascii_control() || byte == 0x7f)
444    {
445        return Err(D::Error::custom(
446            "HTTP Basic username must be nonempty, bounded, colon-free, and contain no controls",
447        ));
448    }
449    Ok(username)
450}
451
452#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
453#[serde(tag = "type", rename_all = "camelCase", deny_unknown_fields)]
454pub enum Actor {
455    Human { principal: PrincipalId },
456    Agent { agent: AgentId },
457    Service { principal: PrincipalId },
458}
459
460#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
461#[serde(rename_all = "PascalCase")]
462pub enum RiskLevel {
463    Low,
464    Medium,
465    High,
466    Critical,
467}
468
469impl fmt::Display for RiskLevel {
470    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
471        write!(formatter, "{self:?}")
472    }
473}
474
475#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
476#[serde(rename_all = "PascalCase")]
477pub enum AgentStatus {
478    Disabled,
479    Pending,
480    Ready,
481    Error,
482}
483
484impl fmt::Display for AgentStatus {
485    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
486        write!(formatter, "{self:?}")
487    }
488}
489
490#[cfg(test)]
491mod tests {
492    use super::{
493        AgentId, IdentifierError, RiskLevel, SecretDrn, SecretSinkKind, SecretUseProposal,
494    };
495
496    #[test]
497    fn accepts_portable_identifiers() {
498        for value in ["reviewer", "github.pull-request.read", "agent_2"] {
499            let parsed = value.parse::<AgentId>();
500            assert!(parsed.is_ok(), "{value} should be valid: {parsed:?}");
501        }
502    }
503
504    #[test]
505    fn rejects_invalid_identifiers_with_context() {
506        assert!(matches!(
507            "Reviewer".parse::<AgentId>(),
508            Err(IdentifierError::InvalidStart { .. })
509        ));
510        assert!(matches!(
511            "github..read".parse::<AgentId>(),
512            Err(IdentifierError::AdjacentSeparators { .. })
513        ));
514        assert!(matches!(
515            "reviewer/one".parse::<AgentId>(),
516            Err(IdentifierError::InvalidCharacter { index: 8, .. })
517        ));
518        assert!(matches!(
519            "reviewer-".parse::<AgentId>(),
520            Err(IdentifierError::InvalidEnd { .. })
521        ));
522    }
523
524    #[test]
525    fn deserialization_cannot_bypass_validation() {
526        let error = serde_json::from_str::<AgentId>(r#""not valid""#)
527            .expect_err("whitespace must be rejected");
528        assert!(error.to_string().contains("invalid character"));
529    }
530
531    #[test]
532    fn display_is_stable() {
533        assert_eq!(RiskLevel::High.to_string(), "High");
534    }
535
536    #[test]
537    fn secret_drns_fold_to_one_lowercase_spelling() {
538        let parsed = "DRN:Secret:Payments/Blah-API-basic"
539            .parse::<SecretDrn>()
540            .expect("mixed case folds");
541        assert_eq!(parsed.as_str(), "drn:secret:payments/blah-api-basic");
542        let round_trip = serde_json::from_str::<SecretDrn>(
543            &serde_json::to_string(&parsed).expect("serialize DRN"),
544        )
545        .expect("deserialize DRN");
546        assert_eq!(round_trip, parsed);
547    }
548
549    #[test]
550    fn secret_drns_reject_physical_ambiguous_or_legacy_spellings() {
551        for value in [
552            "drn:secret:",
553            "drn:secret:a//b",
554            "drn:secret:a/../b",
555            "drn:secret:a/./b",
556            "drn:secret:a%2fb",
557            "drn:secret:a?version=2",
558            "drn:secret:a:b",
559            "drn:secret:-a",
560            "drn:com.xrl:secret:prod:name",
561            "drn:slack:user:t1:u1",
562        ] {
563            assert!(value.parse::<SecretDrn>().is_err(), "accepted {value}");
564        }
565    }
566
567    #[test]
568    fn typed_secret_use_rejects_basic_username_confusion() {
569        let valid = serde_json::from_str::<SecretUseProposal>(
570            r#"{"kind":"httpBasic","secret":"drn:secret:api/basic","username":"user-a"}"#,
571        )
572        .expect("valid Basic proposal");
573        assert_eq!(valid.sink(), SecretSinkKind::HttpBasic);
574        assert_eq!(valid.username(), Some("user-a"));
575
576        for username in ["", "user:password", "line\nbreak"] {
577            let document = format!(
578                r#"{{"kind":"httpBasic","secret":"drn:secret:api/basic","username":{}}}"#,
579                serde_json::to_string(username).expect("username JSON")
580            );
581            assert!(
582                serde_json::from_str::<SecretUseProposal>(&document).is_err(),
583                "accepted {username:?}"
584            );
585        }
586    }
587}
588
589#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
590pub enum CommandWordConflictKind {
591    Reserved,
592    Duplicate,
593    Repeated,
594}
595
596impl CommandWordConflictKind {
597    #[must_use]
598    pub const fn explanation(self) -> &'static str {
599        match self {
600            Self::Reserved => "is reserved by the sandboxed shell and could never dispatch",
601            Self::Duplicate => "is claimed by more than one provider",
602            Self::Repeated => "is declared more than once by the same provider",
603        }
604    }
605
606    #[must_use]
607    pub const fn remedy(self) -> &'static str {
608        match self {
609            Self::Duplicate => "rename one command word, or drop a provider from the search path",
610            Self::Reserved => "rename the command word; this name is reserved",
611            Self::Repeated => "remove the repeated entry from that provider's command words",
612        }
613    }
614}
615
616#[derive(Clone, Debug, Eq, PartialEq)]
617pub struct CommandWordConflict {
618    pub word: String,
619    pub claimants: Vec<String>,
620    pub kind: CommandWordConflictKind,
621}
622
623#[must_use]
624pub fn command_word_conflicts(declared: &[(String, Vec<String>)]) -> Vec<CommandWordConflict> {
625    use std::collections::BTreeMap;
626
627    let mut claimants: BTreeMap<&str, Vec<String>> = BTreeMap::new();
628    for (provider, words) in declared {
629        for word in words {
630            claimants
631                .entry(word.as_str())
632                .or_default()
633                .push(provider.clone());
634        }
635    }
636
637    let mut conflicts = Vec::new();
638    for (word, providers) in claimants {
639        let mut distinct = Vec::with_capacity(providers.len());
640        for provider in &providers {
641            if !distinct.contains(provider) {
642                distinct.push(provider.clone());
643            }
644        }
645        let kind = if RESERVED_COMMAND_WORDS.contains(&word) {
646            CommandWordConflictKind::Reserved
647        } else if distinct.len() > 1 {
648            CommandWordConflictKind::Duplicate
649        } else if distinct.len() < providers.len() {
650            CommandWordConflictKind::Repeated
651        } else {
652            continue;
653        };
654        conflicts.push(CommandWordConflict {
655            word: word.to_owned(),
656            claimants: distinct,
657            kind,
658        });
659    }
660    conflicts
661}
662
663#[cfg(test)]
664mod command_word_tests {
665    use super::{CommandWordConflictKind, RESERVED_COMMAND_WORDS, command_word_conflicts};
666
667    fn declared(entries: &[(&str, &[&str])]) -> Vec<(String, Vec<String>)> {
668        entries
669            .iter()
670            .map(|(provider, words)| {
671                (
672                    (*provider).to_owned(),
673                    words.iter().map(|word| (*word).to_owned()).collect(),
674                )
675            })
676            .collect()
677    }
678
679    #[test]
680    fn a_word_no_one_else_claims_is_no_conflict() {
681        assert!(
682            command_word_conflicts(&declared(&[("fly", &["fly"]), ("k8s", &["kubectl"])]))
683                .is_empty()
684        );
685    }
686
687    #[test]
688    fn a_provider_may_claim_gh_now_that_no_builtin_owns_it() {
689        assert!(command_word_conflicts(&declared(&[("gh", &["gh"])])).is_empty());
690    }
691
692    #[test]
693    fn each_class_of_conflict_is_recognized() {
694        for (word, kind) in [
695            ("jq", CommandWordConflictKind::Reserved),
696            ("eval", CommandWordConflictKind::Reserved),
697            ("break", CommandWordConflictKind::Reserved),
698        ] {
699            let conflicts = command_word_conflicts(&declared(&[("some-provider", &[word])]));
700            assert_eq!(conflicts.len(), 1, "{word}: {conflicts:?}");
701            assert_eq!(conflicts[0].kind, kind, "{word}");
702            assert_eq!(conflicts[0].word, word);
703        }
704    }
705
706    #[test]
707    fn one_provider_repeating_a_word_is_not_reported_as_two_providers() {
708        let conflicts = command_word_conflicts(&declared(&[("fly", &["deploy", "deploy"])]));
709
710        assert_eq!(conflicts.len(), 1, "{conflicts:?}");
711        assert_eq!(conflicts[0].kind, CommandWordConflictKind::Repeated);
712        assert_eq!(conflicts[0].claimants, ["fly"]);
713        assert!(
714            conflicts[0]
715                .kind
716                .explanation()
717                .contains("more than once by the same provider"),
718            "{}",
719            conflicts[0].kind.explanation()
720        );
721
722        let conflicts = command_word_conflicts(&declared(&[
723            ("fly", &["deploy", "deploy"]),
724            ("k8s", &["deploy"]),
725        ]));
726        assert_eq!(conflicts.len(), 1, "{conflicts:?}");
727        assert_eq!(conflicts[0].kind, CommandWordConflictKind::Duplicate);
728        assert_eq!(conflicts[0].claimants, ["fly", "k8s"]);
729    }
730
731    #[test]
732    fn a_word_containing_a_separator_follows_the_ordinary_rules() {
733        assert!(
734            command_word_conflicts(&declared(&[(
735                "some-provider",
736                &["gh.pr", "wiki-page", "wikipedia_page"]
737            )]))
738            .is_empty()
739        );
740
741        let conflicts =
742            command_word_conflicts(&declared(&[("fly", &["gh.pr"]), ("k8s", &["gh.pr"])]));
743        assert_eq!(conflicts.len(), 1, "{conflicts:?}");
744        assert_eq!(conflicts[0].kind, CommandWordConflictKind::Duplicate);
745        assert_eq!(conflicts[0].claimants, ["fly", "k8s"]);
746    }
747
748    #[test]
749    fn two_providers_claiming_one_word_names_both() {
750        let conflicts =
751            command_word_conflicts(&declared(&[("fly", &["deploy"]), ("k8s", &["deploy"])]));
752        assert_eq!(conflicts.len(), 1, "{conflicts:?}");
753        assert_eq!(conflicts[0].kind, CommandWordConflictKind::Duplicate);
754        assert_eq!(conflicts[0].claimants, ["fly", "k8s"]);
755    }
756
757    #[test]
758    fn conflicts_of_several_classes_are_all_reported_at_once() {
759        let conflicts = command_word_conflicts(&declared(&[
760            ("fly", &["deploy", "jq"]),
761            ("k8s", &["deploy", "gh.pr"]),
762            ("danger", &["eval"]),
763        ]));
764
765        let mut found = conflicts
766            .iter()
767            .map(|conflict| (conflict.word.as_str(), conflict.kind))
768            .collect::<Vec<_>>();
769        found.sort();
770        assert_eq!(
771            found,
772            [
773                ("deploy", CommandWordConflictKind::Duplicate),
774                ("eval", CommandWordConflictKind::Reserved),
775                ("jq", CommandWordConflictKind::Reserved),
776            ]
777        );
778    }
779
780    #[test]
781    fn a_reserved_word_is_reported_as_reserved_even_when_contested() {
782        let conflicts = command_word_conflicts(&declared(&[("one", &["jq"]), ("two", &["jq"])]));
783        assert_eq!(conflicts.len(), 1);
784        assert_eq!(conflicts[0].kind, CommandWordConflictKind::Reserved);
785        assert_eq!(conflicts[0].claimants, ["one", "two"]);
786    }
787
788    #[test]
789    fn the_reserved_list_is_sorted_and_free_of_duplicates() {
790        let mut sorted = RESERVED_COMMAND_WORDS.to_vec();
791        sorted.sort_unstable();
792        sorted.dedup();
793        assert_eq!(
794            sorted, RESERVED_COMMAND_WORDS,
795            "keep this list sorted and unique"
796        );
797    }
798}
799
800#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
801#[serde(try_from = "u64", into = "u64")]
802pub struct AssetNumber(std::num::NonZeroU64);
803
804impl AssetNumber {
805    #[must_use]
806    pub const fn get(self) -> u64 {
807        self.0.get()
808    }
809
810    pub fn parse(text: &str) -> Option<Self> {
811        let digits = text.strip_prefix("chat-asset:")?;
812        if digits.starts_with('0') || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
813            return None;
814        }
815        digits.parse().ok().map(Self)
816    }
817}
818
819impl TryFrom<u64> for AssetNumber {
820    type Error = std::num::TryFromIntError;
821
822    fn try_from(value: u64) -> Result<Self, Self::Error> {
823        std::num::NonZeroU64::try_from(value).map(Self)
824    }
825}
826
827impl From<AssetNumber> for u64 {
828    fn from(value: AssetNumber) -> Self {
829        value.get()
830    }
831}
832
833impl fmt::Display for AssetNumber {
834    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
835        write!(formatter, "chat-asset:{}", self.0)
836    }
837}
838
839#[cfg(test)]
840mod space_key_tests {
841    use super::*;
842
843    #[test]
844    fn space_keys_separate_delimiters_optional_workspaces_and_agents() {
845        let key = |agent: &str, workspace: Option<&str>, channel: &str| SpaceKey {
846            agent: agent.parse().expect("agent"),
847            transport: "team-slack".to_owned().into(),
848            workspace: workspace.map(|value| value.to_owned().into()),
849            channel: channel.to_owned().into(),
850        };
851        assert_ne!(
852            key("reviewer", Some("a:b"), "c").encode(),
853            key("reviewer", Some("a"), "b:c").encode()
854        );
855        assert_ne!(
856            key("reviewer", None, "c").encode(),
857            key("reviewer", Some(""), "c").encode()
858        );
859        assert_ne!(
860            key("reviewer", None, "c").encode(),
861            key("helper", None, "c").encode()
862        );
863    }
864}