Skip to main content

qualia_app_contract/
catalog.rs

1//! Deterministic command catalog with alias mapping and collision rejection.
2
3use crate::descriptor::CommandDescriptor;
4use crate::error::ContractError;
5use crate::id::CommandId;
6use serde::{Deserialize, Serialize};
7use std::collections::BTreeMap;
8
9/// Canonical registry/catalog of available command descriptors.
10#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
11pub struct CommandCatalog {
12    /// Ordered list of unique registered descriptors.
13    descriptors: Vec<CommandDescriptor>,
14    /// Index mapping command ID to descriptor position.
15    #[serde(skip)]
16    id_to_index: BTreeMap<CommandId, usize>,
17    /// Alias mapping (e.g. "bold" -> "wordcraft::format.bold").
18    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
19    aliases: BTreeMap<String, CommandId>,
20}
21
22impl CommandCatalog {
23    /// Create an empty catalog.
24    pub fn new() -> Self {
25        Self::default()
26    }
27
28    /// Register a command descriptor. Rejects duplicate IDs and invalid schemas.
29    pub fn register(&mut self, descriptor: CommandDescriptor) -> Result<(), ContractError> {
30        descriptor.validate()?;
31
32        if self.id_to_index.contains_key(&descriptor.command_id) {
33            return Err(ContractError::DuplicateCommandId(descriptor.command_id.as_str().to_string()));
34        }
35
36        let idx = self.descriptors.len();
37        self.id_to_index.insert(descriptor.command_id.clone(), idx);
38        self.descriptors.push(descriptor);
39        Ok(())
40    }
41
42    /// Register an alias pointing to a registered command ID. Rejects duplicate aliases.
43    pub fn register_alias(&mut self, alias: impl Into<String>, target: &CommandId) -> Result<(), ContractError> {
44        let alias = alias.into();
45        if !self.id_to_index.contains_key(target) {
46            return Err(ContractError::MalformedParams(format!(
47                "alias target '{}' is not registered in catalog",
48                target.as_str()
49            )));
50        }
51
52        if self.aliases.contains_key(&alias) {
53            return Err(ContractError::DuplicateAlias(alias));
54        }
55
56        self.aliases.insert(alias, target.clone());
57        Ok(())
58    }
59
60    /// Lookup a descriptor by its exact command ID.
61    pub fn get(&self, id: &CommandId) -> Option<&CommandDescriptor> {
62        self.id_to_index.get(id).map(|&idx| &self.descriptors[idx])
63    }
64
65    /// Resolve an alias or direct command ID to its descriptor.
66    pub fn resolve(&self, alias_or_id: &str) -> Option<&CommandDescriptor> {
67        if let Some(target_id) = self.aliases.get(alias_or_id) {
68            return self.get(target_id);
69        }
70        if let Ok(cmd_id) = CommandId::parse(alias_or_id) {
71            return self.get(&cmd_id);
72        }
73        None
74    }
75
76    /// Returns a slice of all registered descriptors in insertion order.
77    pub fn descriptors(&self) -> &[CommandDescriptor] {
78        &self.descriptors
79    }
80
81    /// Count of registered descriptors.
82    pub fn len(&self) -> usize {
83        self.descriptors.len()
84    }
85
86    /// Check if the catalog is empty.
87    pub fn is_empty(&self) -> bool {
88        self.descriptors.is_empty()
89    }
90}