aves-corv 0.5.0

Specialized discussion domain for the Aves async application runtime
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
use std::fmt;
use std::path::Path;

use semver::Version;
use serde::{Deserialize, Serialize};
use thiserror::Error;

/// Application-supplied, immutable definitions used by Discuss.
#[derive(Clone, Copy, Debug)]
pub struct AssetLibrary {
    agents: &'static [AgentDefinition],
    skills: &'static [SkillDefinition],
    commands: &'static [CommandDefinition],
    teams: &'static [TeamDefinition],
}

impl AssetLibrary {
    /// Supply the host application's embedded catalog; Corv has no built-in content.
    pub fn new(
        agents: &'static [AgentDefinition],
        skills: &'static [SkillDefinition],
        commands: &'static [CommandDefinition],
        teams: &'static [TeamDefinition],
    ) -> Self {
        Self {
            agents,
            skills,
            commands,
            teams,
        }
    }

    /// Iterate over supplied agents in canonical order.
    pub fn agents_for(self) -> impl Iterator<Item = &'static AgentDefinition> {
        self.agents.iter()
    }

    /// Iterate over supplied skills in canonical order.
    pub fn skills_for(self) -> impl Iterator<Item = &'static SkillDefinition> {
        self.skills.iter()
    }

    /// Iterate over supplied commands in canonical order.
    pub fn commands_for(self) -> impl Iterator<Item = &'static CommandDefinition> {
        self.commands.iter()
    }

    /// Iterate over supplied teams in canonical order.
    pub fn teams_for(self) -> impl Iterator<Item = &'static TeamDefinition> {
        self.teams.iter()
    }
}

/// A compile-time embedded canonical agent definition.
#[derive(Debug, Clone)]
pub struct AgentAssetDefinition<Id> {
    /// Stable asset identity.
    pub id: Id,

    /// Registry version for this agent.
    pub version: Version,

    /// The role this agent occupies in canonical teams.
    pub role: AgentRole,

    /// Human-readable agent name
    pub name: &'static str,

    /// Human-readable job title
    pub job_title: &'static str,

    /// Human-readable asset description.
    pub description: &'static str,

    /// Compile-time embedded asset body.
    pub body: &'static str,
}

pub type AgentDefinition = AgentAssetDefinition<AgentId>;

/// The role an agent occupies in a canonical team.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AgentRole {
    /// The agent that leads the team.
    Leader,
    /// An agent that follows the team leader.
    Follower,
}

/// A canonical team definition identified by its leader.
#[derive(Debug, Clone)]
pub struct TeamDefinition {
    /// The stable identity of the team leader.
    pub leader: AgentId,

    /// Team followers in canonical order.
    pub followers: Vec<AgentId>,

    /// Skills assigned to the team in canonical order.
    pub skills: Vec<SkillId>,

    /// Registry version for this team.
    pub version: Version,
}

/// Static metadata for a compiled canonical team.
#[derive(Debug, Clone)]
pub struct TeamSummary {
    /// The stable identity of the team leader.
    pub leader: AgentId,

    /// Team followers in canonical order.
    pub followers: Vec<AgentId>,

    /// Skills assigned to the team in canonical order.
    pub skills: Vec<SkillId>,

    /// Registry version for this team.
    pub version: Version,
}

/// One file in a canonical skill bundle.
#[derive(Debug, Clone)]
pub struct SkillBundleFile {
    /// Destination-safe path relative to the skill directory.
    pub relative_path: &'static str,

    /// Compile-time embedded file contents.
    pub contents: &'static str,
}

impl SkillBundleFile {
    /// Creates a bundle file after validating its relative destination path.
    pub fn new(relative_path: &'static str, contents: &'static str) -> Result<Self, Error> {
        validate_relative_path(relative_path)?;
        Ok(Self {
            relative_path,
            contents,
        })
    }
}

/// A compile-time embedded canonical skill definition.
#[derive(Debug, Clone)]
pub struct SkillDefinition {
    /// Stable skill identity.
    pub id: SkillId,

    /// Registry version for this skill.
    pub version: Version,

    /// Human-readable skill name.
    pub name: &'static str,

    /// Canonical trigger-oriented skill description.
    pub description: &'static str,

    /// Skill bundle files, with `SKILL.md` required as the first item.
    pub bundle: Vec<SkillBundleFile>,
}

impl SkillDefinition {
    /// Creates a skill definition with the canonical `SKILL.md` entry first.
    pub fn new(
        id: SkillId,
        version: Version,
        name: &'static str,
        description: &'static str,
        bundle: Vec<SkillBundleFile>,
    ) -> Result<Self, Error> {
        let definition = Self {
            id,
            version,
            name,
            description,
            bundle,
        };
        definition.validate()?;
        Ok(definition)
    }

    /// Validates bundle paths and the required first `SKILL.md` file.
    pub fn validate(&self) -> Result<(), Error> {
        for file in &self.bundle {
            validate_relative_path(file.relative_path)?;
        }

        if self.bundle.first().map(|file| file.relative_path) != Some("SKILL.md") {
            return Err(Error::InvalidAssetId {
                asset_id: self
                    .bundle
                    .first()
                    .map_or_else(String::new, |file| file.relative_path.to_owned()),
                violation: AssetIdViolation::Empty,
            });
        }

        Ok(())
    }
}

/// A compile-time embedded canonical command definition.
#[derive(Debug, Clone)]
pub struct CommandDefinition {
    /// Stable command identity.
    pub id: CommandId,

    /// Registry version for this command.
    pub version: Version,

    /// Human-readable command name.
    pub name: &'static str,

    /// Human-readable asset description.
    pub description: &'static str,

    /// Compile-time embedded command body.
    pub body: &'static str,
}

/// Static metadata for a compiled agent registry entry.
#[derive(Debug, Clone)]
pub struct AgentSummary {
    /// Stable agent identity.
    pub id: AgentId,

    /// Registry version for this agent.
    pub version: Version,

    /// The role this agent occupies in canonical teams.
    pub role: AgentRole,

    /// Human-readable agent name.
    pub name: &'static str,

    /// Human-readable agent job title.
    pub job_title: &'static str,

    /// Human-readable agent description.
    pub description: &'static str,
}

/// Static metadata for a compiled skill registry entry.
#[derive(Debug, Clone)]
pub struct SkillSummary {
    /// Stable skill identity.
    pub id: SkillId,

    /// Registry version for this skill.
    pub version: Version,

    /// Human-readable skill name.
    pub name: &'static str,

    /// Canonical trigger-oriented skill description.
    pub description: &'static str,
}

/// Static metadata for a compiled command registry entry.
#[derive(Debug, Clone)]
pub struct CommandSummary {
    /// Stable command identity.
    pub id: CommandId,

    /// Registry version for this command.
    pub version: Version,

    /// Human-readable command name.
    pub name: &'static str,

    /// Human-readable command description.
    pub description: &'static str,
}

macro_rules! asset_id {
    ($name:ident, $description:literal) => {
        #[doc = $description]
        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
        #[serde(try_from = "String")]
        pub struct $name(String);

        impl $name {
            /// Creates an ID after validating its destination safety.
            pub fn new(value: impl Into<String>) -> Result<Self, Error> {
                Self::try_from(value.into())
            }

            /// Returns this ID's normalized relative destination segment.
            #[must_use]
            pub fn normalized_destination(&self) -> &str {
                &self.0
            }
        }

        impl AsRef<str> for $name {
            fn as_ref(&self) -> &str {
                &self.0
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str(&self.0)
            }
        }

        impl TryFrom<String> for $name {
            type Error = Error;

            fn try_from(value: String) -> Result<Self, Self::Error> {
                let violation = if value.is_empty() {
                    Some(AssetIdViolation::Empty)
                } else if value.chars().any(char::is_control) {
                    Some(AssetIdViolation::ControlCharacter)
                } else if value == "." || value == ".." {
                    Some(AssetIdViolation::DotSegment)
                } else if Path::new(&value).is_absolute() {
                    Some(AssetIdViolation::AbsoluteOrRooted)
                } else if {
                    let bytes = value.as_bytes();
                    bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':'
                } {
                    Some(AssetIdViolation::PathPrefix)
                } else if value.contains('/') || value.contains('\\') {
                    Some(AssetIdViolation::Separator)
                } else {
                    None
                };

                if let Some(violation) = violation {
                    return Err(Error::InvalidAssetId {
                        asset_id: value,
                        violation,
                    });
                }
                Ok(Self(value))
            }
        }

        impl TryFrom<&str> for $name {
            type Error = Error;

            fn try_from(value: &str) -> Result<Self, Self::Error> {
                Self::try_from(value.to_owned())
            }
        }
    };
}

asset_id!(AgentId, "A safe canonical agent destination identity.");
asset_id!(SkillId, "A safe canonical skill destination identity.");
asset_id!(CommandId, "A safe canonical command destination identity.");

fn validate_relative_path(relative_path: &str) -> Result<(), Error> {
    let bytes = relative_path.as_bytes();
    let has_path_prefix = bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':';
    let invalid = if relative_path.is_empty() {
        Some(AssetIdViolation::Empty)
    } else if relative_path.chars().any(char::is_control) {
        Some(AssetIdViolation::ControlCharacter)
    } else if Path::new(relative_path).is_absolute() {
        Some(AssetIdViolation::AbsoluteOrRooted)
    } else if has_path_prefix {
        Some(AssetIdViolation::PathPrefix)
    } else if relative_path.contains('\\') || relative_path.split('/').any(str::is_empty) {
        Some(AssetIdViolation::Separator)
    } else if relative_path
        .split('/')
        .any(|segment| segment == "." || segment == "..")
    {
        Some(AssetIdViolation::DotSegment)
    } else {
        None
    };

    invalid.map_or(Ok(()), |violation| {
        Err(Error::InvalidAssetId {
            asset_id: relative_path.to_owned(),
            violation,
        })
    })
}

/// Why an asset ID cannot safely form a relative destination segment.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AssetIdViolation {
    /// The ID is empty.
    Empty,
    /// The ID contains a destination separator.
    Separator,
    /// The ID is `.` or `..`.
    DotSegment,
    /// The ID is absolute or rooted.
    AbsoluteOrRooted,
    /// The ID has a platform path prefix.
    PathPrefix,
    /// The ID contains a NUL or other control character.
    ControlCharacter,
}

impl fmt::Display for AssetIdViolation {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let reason = match self {
            Self::Empty => "asset ID must not be empty",
            Self::Separator => "asset ID must be a single destination segment",
            Self::DotSegment => "asset ID must not be `.` or `..`",
            Self::AbsoluteOrRooted => "asset ID must not be absolute or rooted",
            Self::PathPrefix => "asset ID must not contain a platform path prefix",
            Self::ControlCharacter => "asset ID must not contain control characters",
        };

        formatter.write_str(reason)
    }
}

/// Failures produced while validating application-supplied asset definitions.
#[derive(Debug, Error)]
pub enum Error {
    /// An asset identity cannot safely name a destination segment.
    #[error("invalid asset id {asset_id:?}: {violation}")]
    InvalidAssetId {
        asset_id: String,
        violation: AssetIdViolation,
    },
}

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

    fn assert_invalid_asset_id<T>(result: Result<T, Error>, asset_id: &str, violation: AssetIdViolation) {
        let error = match result {
            Ok(_) => panic!("asset ID should be rejected"),
            Err(error) => error,
        };

        assert!(matches!(
            error,
            Error::InvalidAssetId {
                asset_id: invalid_id,
                violation: actual_violation,
            } if invalid_id == asset_id && actual_violation == violation
        ));
    }

    #[test]
    fn asset_ids_accept_safe_single_segments_without_cosmetic_restrictions() {
        let safe_id = "Agent name_42.@example";

        assert_eq!(AgentId::new(safe_id).unwrap().normalized_destination(), safe_id);
        assert_eq!(SkillId::try_from(safe_id).unwrap().as_ref(), safe_id);
        assert_eq!(CommandId::try_from(safe_id.to_owned()).unwrap().to_string(), safe_id);
    }

    #[test]
    fn asset_ids_reject_unsafe_destination_segments_with_typed_context() {
        let cases = [
            ("", AssetIdViolation::Empty),
            ("/", AssetIdViolation::AbsoluteOrRooted),
            ("agent\\id", AssetIdViolation::Separator),
            (".", AssetIdViolation::DotSegment),
            ("..", AssetIdViolation::DotSegment),
            ("/absolute", AssetIdViolation::AbsoluteOrRooted),
            ("C:prefix", AssetIdViolation::PathPrefix),
            ("agent\0id", AssetIdViolation::ControlCharacter),
            ("agent\nid", AssetIdViolation::ControlCharacter),
        ];

        for (asset_id, violation) in cases {
            assert_invalid_asset_id(AgentId::try_from(asset_id), asset_id, violation);
            assert_invalid_asset_id(SkillId::try_from(asset_id), asset_id, violation);
            assert_invalid_asset_id(CommandId::try_from(asset_id), asset_id, violation);
        }
    }
}