Skip to main content

mur_common/
action.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use std::collections::BTreeMap;
4use std::path::PathBuf;
5use uuid::Uuid;
6
7// ── Phase 1: Ingestion ──
8
9#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
10pub struct PendingItem {
11    pub id: Uuid,
12    pub source: ItemSource,
13    pub files: Vec<PendingFile>,
14    pub created_at: DateTime<Utc>,
15    pub status: PendingStatus,
16}
17
18#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
19pub enum ItemSource {
20    DragDrop { paths: Vec<PathBuf> },
21    Clipboard { mime_type: String },
22    ShareUrl { url: String, kind: ShareKind },
23}
24
25#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
26pub enum ShareKind {
27    WebPage,
28    File,
29    Unknown,
30}
31
32#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
33pub struct PendingFile {
34    pub path: PathBuf,
35    pub mime_type: String,
36    pub size_bytes: u64,
37    pub thumbnail_path: Option<PathBuf>,
38}
39
40#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
41pub enum PendingStatus {
42    AwaitingSelection,
43    Selected { action_id: String },
44    Expired,
45}
46
47// ── Phase 2: Task Queue ──
48
49#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
50pub struct Task {
51    pub id: Uuid,
52    pub pending_item_id: Uuid,
53    pub action: Action,
54    pub state: TaskState,
55    pub steps: Vec<TaskStep>,
56    pub created_at: DateTime<Utc>,
57    pub started_at: Option<DateTime<Utc>>,
58    pub completed_at: Option<DateTime<Utc>>,
59    pub timeout_seconds: u32,
60}
61
62#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
63pub struct Action {
64    pub id: String, // matches file_actions[].id
65    pub label: String,
66    pub user_prompt: Option<String>, // filled for ask_me
67}
68
69#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
70pub enum TaskState {
71    Queued,
72    Running,
73    Paused,
74    Completed { outcome: TaskOutcome },
75    Cancelled,
76}
77
78#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
79pub enum TaskOutcome {
80    Success { outputs: Vec<ActionOutput> },
81    PartialSuccess { succeeded: u32, failed: u32 },
82    Failed { error: String },
83}
84
85#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
86pub struct ActionOutput {
87    pub kind: OutputKind,
88    pub file_path: Option<PathBuf>,
89    pub chat_content: Option<String>,
90}
91
92#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
93pub enum OutputKind {
94    File,
95    ChatMessage,
96    Both,
97}
98
99#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
100pub struct TaskStep {
101    pub index: u32,
102    pub label: String,
103    pub state: StepState,
104    pub started_at: Option<DateTime<Utc>>,
105    pub completed_at: Option<DateTime<Utc>>,
106}
107
108#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
109pub enum StepState {
110    Pending,
111    Running,
112    Done,
113    Failed,
114}
115
116// ── Phase 3: Deletion Safety ──
117
118#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
119pub struct TrashEntry {
120    pub id: Uuid,
121    pub original_path: PathBuf,
122    pub trash_path: Option<PathBuf>,
123    pub file_size_bytes: u64,
124    pub created_by_task_id: Uuid,
125    pub created_at: DateTime<Utc>,
126    pub execute_at: DateTime<Utc>,
127    pub retention_until: Option<DateTime<Utc>>,
128    pub status: TrashStatus,
129    pub restore_metadata: RestoreMeta,
130}
131
132#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
133pub enum TrashStatus {
134    PendingDelete,
135    Retained,
136    Expired,
137    Restored,
138    PermDeleted,
139}
140
141#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
142pub struct RestoreMeta {
143    pub owner_uid: u32,
144    pub owner_gid: u32,
145    pub permissions: u32,
146}
147
148#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
149pub enum PermDeleteReason {
150    UserEmpty,
151    UserNow,
152    CapacityEviction,
153}
154
155// ── Shared Ledger Events ──
156
157#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
158#[serde(tag = "event", rename_all = "snake_case")]
159pub enum ActionEvent {
160    ItemIngested {
161        item: PendingItem,
162    },
163    ItemSelected {
164        item_id: Uuid,
165        action: Action,
166    },
167    ItemExpired {
168        item_id: Uuid,
169    },
170    TaskEnqueued {
171        task: Task,
172    },
173    TaskStarted {
174        task_id: Uuid,
175    },
176    TaskStepUpdated {
177        task_id: Uuid,
178        step: TaskStep,
179    },
180    TaskPaused {
181        task_id: Uuid,
182        reason: String,
183    },
184    TaskResumed {
185        task_id: Uuid,
186    },
187    TaskCompleted {
188        task_id: Uuid,
189        outcome: TaskOutcome,
190    },
191    TaskCancelled {
192        task_id: Uuid,
193    },
194    DeletionPending {
195        entry: TrashEntry,
196    },
197    DeletionCancelled {
198        entry_id: Uuid,
199    },
200    TrashCreated {
201        entry: TrashEntry,
202    },
203    TrashRestored {
204        entry_id: Uuid,
205    },
206    TrashExpired {
207        entry_id: Uuid,
208    },
209    TrashPermDeleted {
210        entry_id: Uuid,
211        reason: PermDeleteReason,
212    },
213    /// An agent ran a delete MUR could not route through the trash (#2154).
214    /// Audit only: nothing is recoverable from it.
215    UnprotectedDelete {
216        command: String,
217        reason: String,
218        at: DateTime<Utc>,
219    },
220}
221
222// ── Profile Schema Types ──
223
224#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
225pub struct FileAction {
226    pub id: String,
227    #[serde(default)]
228    pub label: BTreeMap<String, String>,
229    #[serde(default)]
230    pub description: Option<String>,
231    #[serde(default)]
232    pub mime_types: Vec<String>, // empty ⇒ matches any
233}
234
235#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
236pub struct ActionPipelineConfig {
237    #[serde(default)]
238    pub deletion: DeletionConfig,
239    #[serde(default)]
240    pub queue: QueueConfig,
241}
242
243#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
244pub struct DeletionConfig {
245    #[serde(default = "default_true")]
246    pub trash_enabled: bool,
247    #[serde(default = "default_cancel_window")]
248    pub cancel_window_minutes: u32,
249    #[serde(default = "default_retention_days")]
250    pub trash_retention_days: u32,
251    #[serde(default = "default_trash_max_mb")]
252    pub trash_max_mb: u64,
253    #[serde(default = "default_max_batch")]
254    pub max_batch: u32,
255    #[serde(default)]
256    pub auto_permanent_delete: bool, // MUST stay false
257    #[serde(default)]
258    pub trusted_paths: Vec<String>,
259}
260
261#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
262pub struct QueueConfig {
263    #[serde(default = "default_max_concurrent")]
264    pub max_concurrent: u32,
265    #[serde(default = "default_timeout_minutes")]
266    pub default_timeout_minutes: u32,
267    #[serde(default = "default_pending_ttl_minutes")]
268    pub pending_item_ttl_minutes: u32,
269}
270
271fn default_true() -> bool {
272    true
273}
274fn default_cancel_window() -> u32 {
275    10
276}
277fn default_retention_days() -> u32 {
278    30
279}
280fn default_trash_max_mb() -> u64 {
281    1024
282}
283fn default_max_batch() -> u32 {
284    50
285}
286fn default_max_concurrent() -> u32 {
287    3
288}
289fn default_timeout_minutes() -> u32 {
290    30
291}
292fn default_pending_ttl_minutes() -> u32 {
293    60
294}
295
296impl Default for ActionPipelineConfig {
297    fn default() -> Self {
298        Self {
299            deletion: DeletionConfig {
300                trash_enabled: true,
301                cancel_window_minutes: 10,
302                trash_retention_days: 30,
303                trash_max_mb: 1024,
304                max_batch: 50,
305                auto_permanent_delete: false,
306                trusted_paths: vec![],
307            },
308            queue: QueueConfig {
309                max_concurrent: 3,
310                default_timeout_minutes: 30,
311                pending_item_ttl_minutes: 60,
312            },
313        }
314    }
315}
316
317impl Default for DeletionConfig {
318    fn default() -> Self {
319        ActionPipelineConfig::default().deletion
320    }
321}
322
323impl Default for QueueConfig {
324    fn default() -> Self {
325        ActionPipelineConfig::default().queue
326    }
327}
328
329// ── BCP-47 label resolution ──
330
331impl FileAction {
332    /// Resolve label for a given BCP-47 locale string (e.g. "zh-TW").
333    /// Falls back: exact match → language prefix → "en" → first entry → id.
334    pub fn label_for(&self, locale: &str) -> &str {
335        if let Some(v) = self.label.get(locale) {
336            return v.as_str();
337        }
338        if let Some(prefix) = locale.split('-').next()
339            && let Some(v) = self.label.get(prefix)
340        {
341            return v.as_str();
342        }
343        if let Some(v) = self.label.get("en") {
344            return v.as_str();
345        }
346        self.label
347            .values()
348            .next()
349            .map(|s| s.as_str())
350            .unwrap_or(&self.id)
351    }
352}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357
358    #[test]
359    fn action_event_serde_roundtrip() {
360        let item = PendingItem {
361            id: Uuid::now_v7(),
362            source: ItemSource::DragDrop {
363                paths: vec![PathBuf::from("/tmp/test.pdf")],
364            },
365            files: vec![PendingFile {
366                path: PathBuf::from("/tmp/test.pdf"),
367                mime_type: "application/pdf".into(),
368                size_bytes: 1024,
369                thumbnail_path: None,
370            }],
371            created_at: Utc::now(),
372            status: PendingStatus::AwaitingSelection,
373        };
374        let event = ActionEvent::ItemIngested { item };
375        let json = serde_json::to_string(&event).unwrap();
376        let back: ActionEvent = serde_json::from_str(&json).unwrap();
377        match back {
378            ActionEvent::ItemIngested { item } => {
379                assert_eq!(item.files[0].mime_type, "application/pdf");
380            }
381            _ => panic!("wrong variant"),
382        }
383    }
384
385    #[test]
386    fn file_action_label_resolution() {
387        let mut labels = BTreeMap::new();
388        labels.insert("zh".into(), "摘要".into());
389        labels.insert("en".into(), "Summarize".into());
390        let fa = FileAction {
391            id: "summarize".into(),
392            label: labels,
393            description: None,
394            mime_types: vec!["text/*".into()],
395        };
396        assert_eq!(fa.label_for("zh-TW"), "摘要"); // exact match on "zh" prefix
397        assert_eq!(fa.label_for("zh-CN"), "摘要"); // prefix fallback: zh-CN → zh
398        assert_eq!(fa.label_for("en"), "Summarize");
399        assert_eq!(fa.label_for("ja"), "Summarize"); // fallback to en
400    }
401
402    #[test]
403    fn action_pipeline_config_defaults() {
404        let cfg = ActionPipelineConfig::default();
405        assert_eq!(cfg.deletion.cancel_window_minutes, 10);
406        assert_eq!(cfg.deletion.trash_retention_days, 30);
407        assert_eq!(cfg.queue.max_concurrent, 3);
408    }
409
410    #[test]
411    fn trash_entry_serde_roundtrip() {
412        let entry = TrashEntry {
413            id: Uuid::now_v7(),
414            original_path: PathBuf::from("/tmp/file.txt"),
415            trash_path: None,
416            file_size_bytes: 100,
417            created_by_task_id: Uuid::now_v7(),
418            created_at: Utc::now(),
419            execute_at: Utc::now(),
420            retention_until: None,
421            status: TrashStatus::PendingDelete,
422            restore_metadata: RestoreMeta {
423                owner_uid: 501,
424                owner_gid: 20,
425                permissions: 0o644,
426            },
427        };
428        let json = serde_json::to_string(&entry).unwrap();
429        let back: TrashEntry = serde_json::from_str(&json).unwrap();
430        assert_eq!(back.original_path, PathBuf::from("/tmp/file.txt"));
431        assert_eq!(back.status, TrashStatus::PendingDelete);
432    }
433
434    #[test]
435    fn deletion_config_yaml_roundtrip() {
436        let yaml = r#"
437trash_enabled: true
438cancel_window_minutes: 5
439trash_retention_days: 14
440trash_max_mb: 512
441max_batch: 25
442auto_permanent_delete: false
443trusted_paths: []
444"#;
445        let cfg: DeletionConfig = serde_yaml_ng::from_str(yaml).unwrap();
446        assert_eq!(cfg.cancel_window_minutes, 5);
447        assert_eq!(cfg.trash_retention_days, 14);
448        let out = serde_yaml_ng::to_string(&cfg).unwrap();
449        let back: DeletionConfig = serde_yaml_ng::from_str(&out).unwrap();
450        assert_eq!(back.cancel_window_minutes, 5);
451    }
452
453    #[test]
454    fn queue_config_defaults_deserialize() {
455        let yaml =
456            "max_concurrent: 5\ndefault_timeout_minutes: 60\npending_item_ttl_minutes: 120\n";
457        let cfg: QueueConfig = serde_yaml_ng::from_str(yaml).unwrap();
458        assert_eq!(cfg.max_concurrent, 5);
459        assert_eq!(cfg.default_timeout_minutes, 60);
460        assert_eq!(cfg.pending_item_ttl_minutes, 120);
461    }
462}