mur-common 2.22.1

Shared types and traits for the MUR ecosystem
Documentation
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
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::PathBuf;
use uuid::Uuid;

// ── Phase 1: Ingestion ──

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PendingItem {
    pub id: Uuid,
    pub source: ItemSource,
    pub files: Vec<PendingFile>,
    pub created_at: DateTime<Utc>,
    pub status: PendingStatus,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ItemSource {
    DragDrop { paths: Vec<PathBuf> },
    Clipboard { mime_type: String },
    ShareUrl { url: String, kind: ShareKind },
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ShareKind {
    WebPage,
    File,
    Unknown,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PendingFile {
    pub path: PathBuf,
    pub mime_type: String,
    pub size_bytes: u64,
    pub thumbnail_path: Option<PathBuf>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum PendingStatus {
    AwaitingSelection,
    Selected { action_id: String },
    Expired,
}

// ── Phase 2: Task Queue ──

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Task {
    pub id: Uuid,
    pub pending_item_id: Uuid,
    pub action: Action,
    pub state: TaskState,
    pub steps: Vec<TaskStep>,
    pub created_at: DateTime<Utc>,
    pub started_at: Option<DateTime<Utc>>,
    pub completed_at: Option<DateTime<Utc>>,
    pub timeout_seconds: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Action {
    pub id: String, // matches file_actions[].id
    pub label: String,
    pub user_prompt: Option<String>, // filled for ask_me
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum TaskState {
    Queued,
    Running,
    Paused,
    Completed { outcome: TaskOutcome },
    Cancelled,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum TaskOutcome {
    Success { outputs: Vec<ActionOutput> },
    PartialSuccess { succeeded: u32, failed: u32 },
    Failed { error: String },
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ActionOutput {
    pub kind: OutputKind,
    pub file_path: Option<PathBuf>,
    pub chat_content: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum OutputKind {
    File,
    ChatMessage,
    Both,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TaskStep {
    pub index: u32,
    pub label: String,
    pub state: StepState,
    pub started_at: Option<DateTime<Utc>>,
    pub completed_at: Option<DateTime<Utc>>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum StepState {
    Pending,
    Running,
    Done,
    Failed,
}

// ── Phase 3: Deletion Safety ──

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TrashEntry {
    pub id: Uuid,
    pub original_path: PathBuf,
    pub trash_path: Option<PathBuf>,
    pub file_size_bytes: u64,
    pub created_by_task_id: Uuid,
    pub created_at: DateTime<Utc>,
    pub execute_at: DateTime<Utc>,
    pub retention_until: Option<DateTime<Utc>>,
    pub status: TrashStatus,
    pub restore_metadata: RestoreMeta,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum TrashStatus {
    PendingDelete,
    Retained,
    Expired,
    Restored,
    PermDeleted,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RestoreMeta {
    pub owner_uid: u32,
    pub owner_gid: u32,
    pub permissions: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum PermDeleteReason {
    UserEmpty,
    UserNow,
    CapacityEviction,
}

// ── Shared Ledger Events ──

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "event", rename_all = "snake_case")]
pub enum ActionEvent {
    ItemIngested {
        item: PendingItem,
    },
    ItemSelected {
        item_id: Uuid,
        action: Action,
    },
    ItemExpired {
        item_id: Uuid,
    },
    TaskEnqueued {
        task: Task,
    },
    TaskStarted {
        task_id: Uuid,
    },
    TaskStepUpdated {
        task_id: Uuid,
        step: TaskStep,
    },
    TaskPaused {
        task_id: Uuid,
        reason: String,
    },
    TaskResumed {
        task_id: Uuid,
    },
    TaskCompleted {
        task_id: Uuid,
        outcome: TaskOutcome,
    },
    TaskCancelled {
        task_id: Uuid,
    },
    DeletionPending {
        entry: TrashEntry,
    },
    DeletionCancelled {
        entry_id: Uuid,
    },
    TrashCreated {
        entry: TrashEntry,
    },
    TrashRestored {
        entry_id: Uuid,
    },
    TrashExpired {
        entry_id: Uuid,
    },
    TrashPermDeleted {
        entry_id: Uuid,
        reason: PermDeleteReason,
    },
}

// ── Profile Schema Types ──

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct FileAction {
    pub id: String,
    #[serde(default)]
    pub label: BTreeMap<String, String>,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub mime_types: Vec<String>, // empty ⇒ matches any
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ActionPipelineConfig {
    #[serde(default)]
    pub deletion: DeletionConfig,
    #[serde(default)]
    pub queue: QueueConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DeletionConfig {
    #[serde(default = "default_true")]
    pub trash_enabled: bool,
    #[serde(default = "default_cancel_window")]
    pub cancel_window_minutes: u32,
    #[serde(default = "default_retention_days")]
    pub trash_retention_days: u32,
    #[serde(default = "default_trash_max_mb")]
    pub trash_max_mb: u64,
    #[serde(default = "default_max_batch")]
    pub max_batch: u32,
    #[serde(default)]
    pub auto_permanent_delete: bool, // MUST stay false
    #[serde(default)]
    pub trusted_paths: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct QueueConfig {
    #[serde(default = "default_max_concurrent")]
    pub max_concurrent: u32,
    #[serde(default = "default_timeout_minutes")]
    pub default_timeout_minutes: u32,
    #[serde(default = "default_pending_ttl_minutes")]
    pub pending_item_ttl_minutes: u32,
}

fn default_true() -> bool {
    true
}
fn default_cancel_window() -> u32 {
    10
}
fn default_retention_days() -> u32 {
    30
}
fn default_trash_max_mb() -> u64 {
    1024
}
fn default_max_batch() -> u32 {
    50
}
fn default_max_concurrent() -> u32 {
    3
}
fn default_timeout_minutes() -> u32 {
    30
}
fn default_pending_ttl_minutes() -> u32 {
    60
}

impl Default for ActionPipelineConfig {
    fn default() -> Self {
        Self {
            deletion: DeletionConfig {
                trash_enabled: true,
                cancel_window_minutes: 10,
                trash_retention_days: 30,
                trash_max_mb: 1024,
                max_batch: 50,
                auto_permanent_delete: false,
                trusted_paths: vec![],
            },
            queue: QueueConfig {
                max_concurrent: 3,
                default_timeout_minutes: 30,
                pending_item_ttl_minutes: 60,
            },
        }
    }
}

impl Default for DeletionConfig {
    fn default() -> Self {
        ActionPipelineConfig::default().deletion
    }
}

impl Default for QueueConfig {
    fn default() -> Self {
        ActionPipelineConfig::default().queue
    }
}

// ── BCP-47 label resolution ──

impl FileAction {
    /// Resolve label for a given BCP-47 locale string (e.g. "zh-TW").
    /// Falls back: exact match → language prefix → "en" → first entry → id.
    pub fn label_for(&self, locale: &str) -> &str {
        if let Some(v) = self.label.get(locale) {
            return v.as_str();
        }
        if let Some(prefix) = locale.split('-').next()
            && let Some(v) = self.label.get(prefix)
        {
            return v.as_str();
        }
        if let Some(v) = self.label.get("en") {
            return v.as_str();
        }
        self.label
            .values()
            .next()
            .map(|s| s.as_str())
            .unwrap_or(&self.id)
    }
}

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

    #[test]
    fn action_event_serde_roundtrip() {
        let item = PendingItem {
            id: Uuid::now_v7(),
            source: ItemSource::DragDrop {
                paths: vec![PathBuf::from("/tmp/test.pdf")],
            },
            files: vec![PendingFile {
                path: PathBuf::from("/tmp/test.pdf"),
                mime_type: "application/pdf".into(),
                size_bytes: 1024,
                thumbnail_path: None,
            }],
            created_at: Utc::now(),
            status: PendingStatus::AwaitingSelection,
        };
        let event = ActionEvent::ItemIngested { item };
        let json = serde_json::to_string(&event).unwrap();
        let back: ActionEvent = serde_json::from_str(&json).unwrap();
        match back {
            ActionEvent::ItemIngested { item } => {
                assert_eq!(item.files[0].mime_type, "application/pdf");
            }
            _ => panic!("wrong variant"),
        }
    }

    #[test]
    fn file_action_label_resolution() {
        let mut labels = BTreeMap::new();
        labels.insert("zh".into(), "摘要".into());
        labels.insert("en".into(), "Summarize".into());
        let fa = FileAction {
            id: "summarize".into(),
            label: labels,
            description: None,
            mime_types: vec!["text/*".into()],
        };
        assert_eq!(fa.label_for("zh-TW"), "摘要"); // exact match on "zh" prefix
        assert_eq!(fa.label_for("zh-CN"), "摘要"); // prefix fallback: zh-CN → zh
        assert_eq!(fa.label_for("en"), "Summarize");
        assert_eq!(fa.label_for("ja"), "Summarize"); // fallback to en
    }

    #[test]
    fn action_pipeline_config_defaults() {
        let cfg = ActionPipelineConfig::default();
        assert_eq!(cfg.deletion.cancel_window_minutes, 10);
        assert_eq!(cfg.deletion.trash_retention_days, 30);
        assert_eq!(cfg.queue.max_concurrent, 3);
    }

    #[test]
    fn trash_entry_serde_roundtrip() {
        let entry = TrashEntry {
            id: Uuid::now_v7(),
            original_path: PathBuf::from("/tmp/file.txt"),
            trash_path: None,
            file_size_bytes: 100,
            created_by_task_id: Uuid::now_v7(),
            created_at: Utc::now(),
            execute_at: Utc::now(),
            retention_until: None,
            status: TrashStatus::PendingDelete,
            restore_metadata: RestoreMeta {
                owner_uid: 501,
                owner_gid: 20,
                permissions: 0o644,
            },
        };
        let json = serde_json::to_string(&entry).unwrap();
        let back: TrashEntry = serde_json::from_str(&json).unwrap();
        assert_eq!(back.original_path, PathBuf::from("/tmp/file.txt"));
        assert_eq!(back.status, TrashStatus::PendingDelete);
    }

    #[test]
    fn deletion_config_yaml_roundtrip() {
        let yaml = r#"
trash_enabled: true
cancel_window_minutes: 5
trash_retention_days: 14
trash_max_mb: 512
max_batch: 25
auto_permanent_delete: false
trusted_paths: []
"#;
        let cfg: DeletionConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(cfg.cancel_window_minutes, 5);
        assert_eq!(cfg.trash_retention_days, 14);
        let out = serde_yaml_ng::to_string(&cfg).unwrap();
        let back: DeletionConfig = serde_yaml_ng::from_str(&out).unwrap();
        assert_eq!(back.cancel_window_minutes, 5);
    }

    #[test]
    fn queue_config_defaults_deserialize() {
        let yaml =
            "max_concurrent: 5\ndefault_timeout_minutes: 60\npending_item_ttl_minutes: 120\n";
        let cfg: QueueConfig = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(cfg.max_concurrent, 5);
        assert_eq!(cfg.default_timeout_minutes, 60);
        assert_eq!(cfg.pending_item_ttl_minutes, 120);
    }
}