Skip to main content

qualia_app_contract/
effects.rs

1//! Command effect classification, undo policy, and interaction semantics.
2
3use crate::error::ContractError;
4use serde::{Deserialize, Serialize};
5use std::collections::BTreeSet;
6use std::fmt;
7
8/// Individual effect of an executed command.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
10#[serde(rename_all = "snake_case")]
11pub enum CommandEffect {
12    /// Read-only inspection of document, workspace, or session state.
13    Read,
14    /// Mutation confined to the active document state.
15    DocumentMutation,
16    /// Mutation to workspace, catalog, or project state outside the document.
17    WorkspaceMutation,
18    /// Persistent write to local storage, OPFS, or filesystem.
19    FilesystemWrite,
20    /// Disclosure of data or telemetry over network or remote transport.
21    NetworkDisclosure,
22    /// Capture from hardware device (camera, microphone, tablet, keyboard).
23    DeviceCapture,
24    /// Invocation causing external financial charge or credit deduction.
25    ExternalCharge,
26    /// Lifecycle transition of a package, worker, or application service.
27    PackageLifecycle,
28}
29
30impl CommandEffect {
31    /// `&str` form.
32    pub fn as_str(&self) -> &'static str {
33        match self {
34            Self::Read => "read",
35            Self::DocumentMutation => "document_mutation",
36            Self::WorkspaceMutation => "workspace_mutation",
37            Self::FilesystemWrite => "filesystem_write",
38            Self::NetworkDisclosure => "network_disclosure",
39            Self::DeviceCapture => "device_capture",
40            Self::ExternalCharge => "external_charge",
41            Self::PackageLifecycle => "package_lifecycle",
42        }
43    }
44
45    /// Constructs from str-strict.
46    pub fn from_str_strict(s: &str) -> Result<Self, ContractError> {
47        match s {
48            "read" => Ok(Self::Read),
49            "document_mutation" => Ok(Self::DocumentMutation),
50            "workspace_mutation" => Ok(Self::WorkspaceMutation),
51            "filesystem_write" => Ok(Self::FilesystemWrite),
52            "network_disclosure" => Ok(Self::NetworkDisclosure),
53            "device_capture" => Ok(Self::DeviceCapture),
54            "external_charge" => Ok(Self::ExternalCharge),
55            "package_lifecycle" => Ok(Self::PackageLifecycle),
56            other => Err(ContractError::UnknownEffect(other.to_string())),
57        }
58    }
59}
60
61impl fmt::Display for CommandEffect {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        write!(f, "{}", self.as_str())
64    }
65}
66
67/// Set of effects associated with a command descriptor or execution receipt.
68#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
69#[serde(transparent)]
70pub struct EffectSet(BTreeSet<CommandEffect>);
71
72impl EffectSet {
73    /// Empty instance.
74    pub fn empty() -> Self {
75        Self(BTreeSet::new())
76    }
77
78    /// Single-element set.
79    pub fn single(effect: CommandEffect) -> Self {
80        let mut set = BTreeSet::new();
81        set.insert(effect);
82        Self(set)
83    }
84
85    /// Inserts.
86    pub fn insert(&mut self, effect: CommandEffect) {
87        self.0.insert(effect);
88    }
89
90    /// `true` when it contains the item.
91    pub fn contains(&self, effect: CommandEffect) -> bool {
92        self.0.contains(&effect)
93    }
94
95    /// `true` when read-only.
96    pub fn is_read_only(&self) -> bool {
97        self.0.len() == 1 && self.0.contains(&CommandEffect::Read)
98    }
99
100    /// Iterator.
101    pub fn iter(&self) -> std::collections::btree_set::Iter<'_, CommandEffect> {
102        self.0.iter()
103    }
104}
105
106impl FromIterator<CommandEffect> for EffectSet {
107    fn from_iter<T: IntoIterator<Item = CommandEffect>>(iter: T) -> Self {
108        Self(iter.into_iter().collect())
109    }
110}
111
112/// The undoability contract for a command.
113#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
114#[serde(rename_all = "snake_case")]
115pub enum UndoPolicy {
116    /// Command cannot be undone (e.g. external disclosure or financial charge).
117    None,
118    /// Command can be reversed cleanly within the local document transaction stack.
119    ReversibleDocument,
120    /// Command has external side effects that require a compensating action.
121    CompensatingExternal,
122}
123
124/// The interaction kind defining how a command is triggered.
125#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
126#[serde(rename_all = "snake_case")]
127pub enum InteractionKind {
128    /// Point-in-time discrete action (e.g. button click or keyboard shortcut).
129    Discrete,
130    /// Interactive gesture with begin/update/commit/cancel phases (e.g. pen stroke or drag).
131    Gesture,
132    /// Read-only query or inspection.
133    Query,
134    /// View/presentation transition without document mutation.
135    View,
136    /// Long-running asynchronous background job.
137    Job,
138}