macfly-core 0.4.0

Core data model, config, DLP redaction, HTML fidelity analysis, and plan engine for MacFly
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Serialize};

use crate::config::{ProfileConfig, data_dir};
use crate::error::MacflyError;
use crate::model::compute_sha256_hex;

/// Eingabeformat, mit dem ein Mensch oder KI-Agent einen Änderungsplan vorschlägt.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlanProposal {
    #[serde(default = "default_schema_version")]
    pub schema_version: String,
    #[serde(default)]
    pub summary: Option<String>,
    pub operations: Vec<PlanOperation>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "action", rename_all = "snake_case")]
pub enum PlanOperation {
    NotesCreate {
        account: Option<String>,
        folder: String,
        title: String,
        body: String,
    },
    NotesAppend {
        note_id: String,
        #[serde(default)]
        expected_revision: Option<String>,
        text: String,
    },
    NotesMove {
        note_id: String,
        #[serde(default)]
        expected_revision: Option<String>,
        destination_folder: String,
        #[serde(default)]
        destination_account: Option<String>,
    },
    NotesMoveFolderContents {
        source_folder_id: String,
        source_folder_path: String,
        destination_folder_path: String,
        #[serde(default)]
        destination_account: Option<String>,
    },
    NotesCreateFolder {
        account: Option<String>,
        name: String,
        #[serde(default)]
        parent_folder: Option<String>,
    },
    NotesDeleteEmptyFolder {
        folder_id: String,
        folder_name: String,
    },
    MailCreateDraft {
        #[serde(default)]
        account: Option<String>,
        to: Vec<String>,
        #[serde(default)]
        cc: Vec<String>,
        subject: String,
        body: String,
        /// Optional: Name einer Signatur in Apple Mail (sonst aus config.json).
        #[serde(default)]
        signature_name: Option<String>,
        /// Optional: Bezugs-Mail-ID (für Antwort-Kontext im Entwurf).
        #[serde(default)]
        reply_to_local_id: Option<String>,
    },
    MailMarkRead {
        local_id: String,
        account: String,
        mailbox: String,
        read: bool,
    },
    MailMove {
        local_id: String,
        account: String,
        from_mailbox: String,
        to_mailbox: String,
    },
    ShortcutsRun {
        name: String,
        #[serde(default)]
        input: Option<String>,
    },
    RemindersCreate {
        #[serde(default)]
        list: Option<String>,
        title: String,
        #[serde(default)]
        notes: Option<String>,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RiskLevel {
    Low,
    Medium,
    High,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Reversibility {
    Reversible,
    BestEffort,
    Irreversible,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PlanStatus {
    PendingApproval,
    Approved,
    Applied,
    Failed,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StoredPlan {
    pub schema_version: String,
    pub plan_id: String,
    pub profile: String,
    pub summary: String,
    pub created_at_unix: u64,
    pub expires_at_unix: u64,
    pub status: PlanStatus,
    pub risk_level: RiskLevel,
    pub reversibility: Reversibility,
    pub plan_hash: String,
    pub approval_code: String,
    #[serde(default)]
    pub approved_at_unix: Option<u64>,
    #[serde(default)]
    pub applied_at_unix: Option<u64>,
    pub operations: Vec<PlanOperation>,
    pub preview_lines: Vec<String>,
}

impl PlanOperation {
    pub fn risk_level(&self) -> RiskLevel {
        match self {
            Self::NotesCreate { .. }
            | Self::NotesCreateFolder { .. }
            | Self::MailCreateDraft { .. }
            | Self::MailMarkRead { .. }
            | Self::RemindersCreate { .. } => RiskLevel::Low,
            Self::NotesAppend { .. }
            | Self::NotesMove { .. }
            | Self::NotesMoveFolderContents { .. }
            | Self::NotesDeleteEmptyFolder { .. }
            | Self::MailMove { .. }
            | Self::ShortcutsRun { .. } => RiskLevel::Medium,
        }
    }

    pub fn reversibility(&self) -> Reversibility {
        match self {
            Self::NotesAppend { .. } | Self::ShortcutsRun { .. } => Reversibility::BestEffort,
            _ => Reversibility::Reversible,
        }
    }

    pub fn preview(&self) -> String {
        match self {
            Self::NotesCreate {
                folder,
                title,
                body,
                ..
            } => format!(
                "[notes.create] Neue Notiz '{}' in Ordner '{}' ({} Zeichen)",
                title,
                folder,
                body.chars().count()
            ),
            Self::NotesAppend { note_id, text, .. } => format!(
                "[notes.append] An Notiz '{}' anhängen ({} Zeichen)",
                note_id,
                text.chars().count()
            ),
            Self::NotesMove {
                note_id,
                destination_folder,
                ..
            } => format!(
                "[notes.move] Notiz '{}' → Ordner '{}'",
                note_id, destination_folder
            ),
            Self::NotesMoveFolderContents {
                source_folder_path,
                destination_folder_path,
                ..
            } => format!(
                "[notes.move_folder_contents] Alle Notizen aus '{}' → '{}'",
                source_folder_path, destination_folder_path
            ),
            Self::NotesCreateFolder {
                name,
                parent_folder,
                ..
            } => match parent_folder {
                Some(p) => format!("[notes.create_folder] Neuer Unterordner '{p}/{name}'"),
                None => format!("[notes.create_folder] Neuer Ordner '{name}'"),
            },
            Self::NotesDeleteEmptyFolder {
                folder_id,
                folder_name,
            } => format!(
                "[notes.delete_empty_folder] Leeren Ordner '{}' ({}) entfernen",
                folder_name, folder_id
            ),
            Self::MailCreateDraft {
                to,
                subject,
                body,
                ..
            } => format!(
                "[mail.create_draft] Entwurf an {} | Betreff: '{}' ({} Zeichen, KEIN Versand)",
                to.join(", "),
                subject,
                body.chars().count()
            ),
            Self::MailMarkRead {
                local_id,
                mailbox,
                read,
                ..
            } => format!(
                "[mail.mark_read] Mail '{}' in '{}' als {} markieren",
                local_id,
                mailbox,
                if *read { "gelesen" } else { "ungelesen" }
            ),
            Self::MailMove {
                local_id,
                from_mailbox,
                to_mailbox,
                ..
            } => format!(
                "[mail.move] Mail '{}' von '{}' → '{}'",
                local_id, from_mailbox, to_mailbox
            ),
            Self::ShortcutsRun { name, input } => match input {
                Some(_) => format!("[shortcuts.run] Kurzbefehl '{name}' (mit Eingabe) ausführen"),
                None => format!("[shortcuts.run] Kurzbefehl '{name}' ausführen"),
            },
            Self::RemindersCreate { list, title, .. } => match list {
                Some(l) => format!("[reminders.create] Neue Erinnerung '{title}' in Liste '{l}'"),
                None => format!("[reminders.create] Neue Erinnerung '{title}'"),
            },
        }
    }

    pub fn validate_against_profile(
        &self,
        profile_name: &str,
        profile: &ProfileConfig,
    ) -> Result<(), MacflyError> {
        match self {
            Self::NotesCreate {
                account, folder, ..
            } => {
                if let Some(acc) = account
                    && !profile.notes.is_account_allowed(acc)
                {
                    return Err(MacflyError::ScopeDenied(format!(
                        "Notes-Account '{acc}' im Profil '{profile_name}' nicht erlaubt"
                    )));
                }
                if !profile.notes.is_folder_allowed(folder) {
                    return Err(MacflyError::ScopeDenied(format!(
                        "Zielordner '{folder}' im Profil '{profile_name}' gesperrt"
                    )));
                }
            }
            Self::NotesMove {
                destination_folder,
                destination_account,
                ..
            } => {
                if let Some(acc) = destination_account
                    && !profile.notes.is_account_allowed(acc)
                {
                    return Err(MacflyError::ScopeDenied(format!(
                        "Ziel-Account '{acc}' im Profil '{profile_name}' nicht erlaubt"
                    )));
                }
                if !profile.notes.is_folder_allowed(destination_folder) {
                    return Err(MacflyError::ScopeDenied(format!(
                        "Zielordner '{destination_folder}' im Profil '{profile_name}' gesperrt"
                    )));
                }
            }
            Self::NotesMoveFolderContents {
                source_folder_path,
                destination_folder_path,
                destination_account,
                ..
            } => {
                if let Some(acc) = destination_account
                    && !profile.notes.is_account_allowed(acc)
                {
                    return Err(MacflyError::ScopeDenied(format!(
                        "Ziel-Account '{acc}' im Profil '{profile_name}' nicht erlaubt"
                    )));
                }
                if !profile.notes.is_folder_allowed(source_folder_path)
                    || !profile.notes.is_folder_allowed(destination_folder_path)
                {
                    return Err(MacflyError::ScopeDenied(format!(
                        "Verschiebung '{source_folder_path}' → '{destination_folder_path}' im Profil '{profile_name}' gesperrt"
                    )));
                }
            }
            Self::NotesCreateFolder { account, name, .. } => {
                if let Some(acc) = account
                    && !profile.notes.is_account_allowed(acc)
                {
                    return Err(MacflyError::ScopeDenied(format!(
                        "Notes-Account '{acc}' im Profil '{profile_name}' nicht erlaubt"
                    )));
                }
                if !profile.notes.is_folder_allowed(name) {
                    return Err(MacflyError::ScopeDenied(format!(
                        "Ordnername '{name}' im Profil '{profile_name}' gesperrt"
                    )));
                }
            }
            Self::NotesDeleteEmptyFolder { folder_name, .. } => {
                if !profile.notes.is_folder_allowed(folder_name) {
                    return Err(MacflyError::ScopeDenied(format!(
                        "Ordner '{folder_name}' im Profil '{profile_name}' gesperrt"
                    )));
                }
            }
            Self::NotesAppend { .. } => {}
            Self::MailCreateDraft { account, to, .. } => {
                if to.is_empty() {
                    return Err(MacflyError::PlanError(
                        "mail.create_draft benötigt mindestens einen Empfänger in `to`".to_string(),
                    ));
                }
                if let Some(acc) = account
                    && !profile.mail.is_account_allowed(acc)
                {
                    return Err(MacflyError::ScopeDenied(format!(
                        "Mail-Account '{acc}' im Profil '{profile_name}' nicht erlaubt"
                    )));
                }
            }
            Self::MailMarkRead {
                account, mailbox, ..
            } => {
                if !profile.mail.is_account_allowed(account)
                    || !profile.mail.is_mailbox_allowed(mailbox)
                {
                    return Err(MacflyError::ScopeDenied(format!(
                        "Postfach '{account}/{mailbox}' im Profil '{profile_name}' gesperrt"
                    )));
                }
            }
            Self::MailMove {
                account,
                from_mailbox,
                to_mailbox,
                ..
            } => {
                if !profile.mail.is_account_allowed(account)
                    || !profile.mail.is_mailbox_allowed(from_mailbox)
                    || !profile.mail.is_mailbox_allowed(to_mailbox)
                {
                    return Err(MacflyError::ScopeDenied(format!(
                        "Mail-Verschiebung in '{account}' im Profil '{profile_name}' gesperrt"
                    )));
                }
            }
            Self::ShortcutsRun { name, .. } => {
                if !profile.shortcuts.is_allowed(name) {
                    return Err(MacflyError::ScopeDenied(format!(
                        "Kurzbefehl '{name}' ist im Profil '{profile_name}' nicht in `shortcuts.allow` freigegeben"
                    )));
                }
            }
            Self::RemindersCreate { title, .. } => {
                if title.trim().is_empty() {
                    return Err(MacflyError::PlanError(
                        "reminders.create benötigt einen nicht-leeren Titel".to_string(),
                    ));
                }
            }
        }
        Ok(())
    }
}

pub struct PlanStore {
    plans_dir: PathBuf,
}

impl PlanStore {
    pub fn default_store() -> Self {
        Self::new(data_dir().join("plans"))
    }

    pub fn new(plans_dir: PathBuf) -> Self {
        Self { plans_dir }
    }

    pub fn create(
        &self,
        profile_name: &str,
        profile: &ProfileConfig,
        proposal: PlanProposal,
        ttl_secs: u64,
    ) -> Result<StoredPlan, MacflyError> {
        if proposal.operations.is_empty() {
            return Err(MacflyError::PlanError(
                "Änderungsplan enthält keine Operationen".to_string(),
            ));
        }

        for op in &proposal.operations {
            op.validate_against_profile(profile_name, profile)?;
        }

        let now = now_unix();
        let canonical_ops = serde_json::to_string(&proposal.operations)?;
        let hash_input = format!("{profile_name}\n{canonical_ops}");
        let full_hash = compute_sha256_hex(&hash_input);
        let plan_hash = format!("sha256:{full_hash}");
        let approval_code = full_hash[..6].to_ascii_uppercase();
        let plan_id = format!("plan-{now}-{}", &full_hash[..8]);

        let mut risk_level = proposal
            .operations
            .iter()
            .map(PlanOperation::risk_level)
            .max()
            .unwrap_or(RiskLevel::Low);
        if proposal.operations.len() > 5 && risk_level < RiskLevel::High {
            risk_level = RiskLevel::High;
        }

        let reversibility = if proposal
            .operations
            .iter()
            .any(|o| o.reversibility() == Reversibility::Irreversible)
        {
            Reversibility::Irreversible
        } else if proposal
            .operations
            .iter()
            .any(|o| o.reversibility() == Reversibility::BestEffort)
        {
            Reversibility::BestEffort
        } else {
            Reversibility::Reversible
        };

        let preview_lines: Vec<String> =
            proposal.operations.iter().map(PlanOperation::preview).collect();
        let summary = proposal
            .summary
            .unwrap_or_else(|| format!("{} Operation(en)", proposal.operations.len()));

        let plan = StoredPlan {
            schema_version: "1.0".to_string(),
            plan_id,
            profile: profile_name.to_string(),
            summary,
            created_at_unix: now,
            expires_at_unix: now + ttl_secs,
            status: PlanStatus::PendingApproval,
            risk_level,
            reversibility,
            plan_hash,
            approval_code,
            approved_at_unix: None,
            applied_at_unix: None,
            operations: proposal.operations,
            preview_lines,
        };

        self.save(&plan)?;
        Ok(plan)
    }

    pub fn load(&self, plan_id: &str) -> Result<StoredPlan, MacflyError> {
        let path = self.plan_path(plan_id)?;
        if !path.exists() {
            return Err(MacflyError::NotFound(format!(
                "Plan '{plan_id}' nicht gefunden"
            )));
        }
        let raw = fs::read_to_string(&path)?;
        let plan: StoredPlan = serde_json::from_str(&raw)?;
        verify_plan_integrity(&plan)?;
        Ok(plan)
    }

    pub fn list(&self) -> Result<Vec<StoredPlan>, MacflyError> {
        if !self.plans_dir.exists() {
            return Ok(Vec::new());
        }
        let mut plans = Vec::new();
        for entry in fs::read_dir(&self.plans_dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.extension().and_then(|e| e.to_str()) != Some("json") {
                continue;
            }
            if let Ok(raw) = fs::read_to_string(&path)
                && let Ok(plan) = serde_json::from_str::<StoredPlan>(&raw)
            {
                plans.push(plan);
            }
        }
        plans.sort_by_key(|a| std::cmp::Reverse(a.created_at_unix));
        Ok(plans)
    }

    pub fn approve(&self, plan_id: &str, confirm_code: &str) -> Result<StoredPlan, MacflyError> {
        let mut plan = self.load(plan_id)?;
        let now = now_unix();
        if now > plan.expires_at_unix {
            return Err(MacflyError::ApprovalError(format!(
                "Plan '{plan_id}' ist abgelaufen (bitte neu erstellen)"
            )));
        }
        if plan.status != PlanStatus::PendingApproval {
            return Err(MacflyError::ApprovalError(format!(
                "Plan '{plan_id}' hat Status {:?} und kann nicht erneut freigegeben werden",
                plan.status
            )));
        }
        if !confirm_code.trim().eq_ignore_ascii_case(&plan.approval_code) {
            return Err(MacflyError::ApprovalError(format!(
                "Ungültiger Bestätigungscode (erwartet: {})",
                plan.approval_code
            )));
        }
        plan.status = PlanStatus::Approved;
        plan.approved_at_unix = Some(now);
        self.save(&plan)?;
        Ok(plan)
    }

    pub fn save(&self, plan: &StoredPlan) -> Result<(), MacflyError> {
        ensure_private_dir(&self.plans_dir)?;
        let path = self.plan_path(&plan.plan_id)?;
        let json = serde_json::to_string_pretty(plan)?;
        write_private_file(&path, &format!("{json}\n"))?;
        Ok(())
    }

    fn plan_path(&self, plan_id: &str) -> Result<PathBuf, MacflyError> {
        if plan_id.contains('/') || plan_id.contains('\\') || plan_id.contains("..") {
            return Err(MacflyError::PlanError(format!(
                "Ungültige Plan-ID '{plan_id}'"
            )));
        }
        Ok(self.plans_dir.join(format!("{plan_id}.json")))
    }
}

pub fn verify_plan_integrity(plan: &StoredPlan) -> Result<(), MacflyError> {
    let canonical_ops = serde_json::to_string(&plan.operations)?;
    let expected = format!(
        "sha256:{}",
        compute_sha256_hex(&format!("{}\n{}", plan.profile, canonical_ops))
    );
    if plan.plan_hash != expected {
        return Err(MacflyError::ApprovalError(format!(
            "Integritätsfehler: Plan '{}' wurde nach Erstellung verändert!",
            plan.plan_id
        )));
    }
    Ok(())
}

pub fn now_unix() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

pub fn ensure_private_dir(path: &Path) -> Result<(), MacflyError> {
    fs::create_dir_all(path)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let _ = fs::set_permissions(path, fs::Permissions::from_mode(0o700));
    }
    Ok(())
}

pub fn write_private_file(path: &Path, content: &str) -> Result<(), MacflyError> {
    fs::write(path, content)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let _ = fs::set_permissions(path, fs::Permissions::from_mode(0o600));
    }
    Ok(())
}

fn default_schema_version() -> String {
    "1.0".to_string()
}

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

    fn temp_store(tag: &str) -> PlanStore {
        let dir = std::env::temp_dir().join(format!("macfly-test-{tag}-{}", now_unix()));
        let _ = fs::remove_dir_all(&dir);
        PlanStore::new(dir)
    }

    #[test]
    fn plan_create_approve_and_tamper_detection() {
        let store = temp_store("tamper");
        let profile = ProfileConfig::default();
        let proposal = PlanProposal {
            schema_version: "1.0".to_string(),
            summary: Some("Ordner aufräumen".to_string()),
            operations: vec![PlanOperation::NotesMove {
                note_id: "x-coredata://123".to_string(),
                expected_revision: None,
                destination_folder: "Archiv".to_string(),
                destination_account: None,
            }],
        };

        let plan = store.create("default", &profile, proposal, 600).unwrap();
        assert_eq!(plan.status, PlanStatus::PendingApproval);
        assert_eq!(plan.risk_level, RiskLevel::Medium);

        // Falscher Code wird abgewiesen
        assert!(store.approve(&plan.plan_id, "000000").is_err());

        // Richtiger Code gibt frei
        let approved = store.approve(&plan.plan_id, &plan.approval_code).unwrap();
        assert_eq!(approved.status, PlanStatus::Approved);

        // Manipulation der gespeicherten Datei wird erkannt
        let path = store.plan_path(&plan.plan_id).unwrap();
        let raw = fs::read_to_string(&path).unwrap().replace("Archiv", "Manipuliert");
        fs::write(&path, raw).unwrap();
        assert!(store.load(&plan.plan_id).is_err());
    }

    #[test]
    fn blocks_denied_folder_in_plan() {
        let store = temp_store("scope");
        let profile = ProfileConfig::default();
        let proposal = PlanProposal {
            schema_version: "1.0".to_string(),
            summary: None,
            operations: vec![PlanOperation::NotesMove {
                note_id: "x-coredata://123".to_string(),
                expected_revision: None,
                destination_folder: "Passwörter".to_string(),
                destination_account: None,
            }],
        };
        let err = store.create("default", &profile, proposal, 600).unwrap_err();
        assert_eq!(err.code(), "SCOPE_DENIED");
    }

    #[test]
    fn shortcuts_run_requires_explicit_allowlist() {
        let store = temp_store("shortcuts");
        let mut profile = ProfileConfig::default();
        let proposal = PlanProposal {
            schema_version: "1.0".to_string(),
            summary: Some("Fokus-Szene".to_string()),
            operations: vec![PlanOperation::ShortcutsRun {
                name: "Office Focus".to_string(),
                input: None,
            }],
        };

        let err = store
            .create("default", &profile, proposal.clone(), 600)
            .unwrap_err();
        assert_eq!(err.code(), "SCOPE_DENIED");

        profile.shortcuts.allow.push("Office Focus".to_string());
        let ok = store.create("default", &profile, proposal, 600).unwrap();
        assert_eq!(ok.risk_level, RiskLevel::Medium);
    }
}