Skip to main content

macfly_core/
plan.rs

1use std::fs::{self, OpenOptions};
2use std::io::Write;
3use std::path::{Path, PathBuf};
4use std::time::{SystemTime, UNIX_EPOCH};
5
6use serde::{Deserialize, Serialize};
7
8use crate::config::{ProfileConfig, data_dir};
9use crate::error::MacflyError;
10use crate::model::compute_sha256_hex;
11
12/// Eingabeformat, mit dem ein Mensch oder KI-Agent einen Änderungsplan vorschlägt.
13#[derive(Debug, Clone, Serialize, Deserialize)]
14pub struct PlanProposal {
15    #[serde(default = "default_schema_version")]
16    pub schema_version: String,
17    #[serde(default)]
18    pub summary: Option<String>,
19    pub operations: Vec<PlanOperation>,
20}
21
22#[derive(Debug, Clone, Serialize, Deserialize)]
23#[serde(tag = "action", rename_all = "snake_case")]
24pub enum PlanOperation {
25    NotesCreate {
26        account: Option<String>,
27        folder: String,
28        title: String,
29        body: String,
30    },
31    NotesAppend {
32        note_id: String,
33        #[serde(default)]
34        expected_revision: Option<String>,
35        text: String,
36    },
37    NotesMove {
38        note_id: String,
39        #[serde(default)]
40        expected_revision: Option<String>,
41        destination_folder: String,
42        #[serde(default)]
43        destination_account: Option<String>,
44    },
45    NotesMoveFolderContents {
46        source_folder_id: String,
47        source_folder_path: String,
48        destination_folder_path: String,
49        #[serde(default)]
50        destination_account: Option<String>,
51    },
52    NotesCreateFolder {
53        account: Option<String>,
54        name: String,
55        #[serde(default)]
56        parent_folder: Option<String>,
57    },
58    NotesDeleteEmptyFolder {
59        folder_id: String,
60        folder_name: String,
61    },
62    MailCreateDraft {
63        #[serde(default)]
64        account: Option<String>,
65        to: Vec<String>,
66        #[serde(default)]
67        cc: Vec<String>,
68        subject: String,
69        body: String,
70        /// Optional: Name einer Signatur in Apple Mail (sonst aus config.json).
71        #[serde(default)]
72        signature_name: Option<String>,
73        /// Optional: Bezugs-Mail-ID (für Antwort-Kontext im Entwurf).
74        #[serde(default)]
75        reply_to_local_id: Option<String>,
76    },
77    MailMarkRead {
78        local_id: String,
79        account: String,
80        mailbox: String,
81        read: bool,
82    },
83    MailMove {
84        local_id: String,
85        account: String,
86        from_mailbox: String,
87        to_mailbox: String,
88    },
89    ShortcutsRun {
90        name: String,
91        #[serde(default)]
92        input: Option<String>,
93    },
94    RemindersCreate {
95        #[serde(default)]
96        list: Option<String>,
97        title: String,
98        #[serde(default)]
99        notes: Option<String>,
100    },
101}
102
103#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
104#[serde(rename_all = "snake_case")]
105pub enum RiskLevel {
106    Low,
107    Medium,
108    High,
109}
110
111#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
112#[serde(rename_all = "snake_case")]
113pub enum Reversibility {
114    Reversible,
115    BestEffort,
116    Irreversible,
117}
118
119#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
120#[serde(rename_all = "snake_case")]
121pub enum PlanStatus {
122    PendingApproval,
123    Approved,
124    PartiallyApplied,
125    Applied,
126    Failed,
127}
128
129#[derive(Debug, Clone, Serialize, Deserialize)]
130pub struct OperationRecord {
131    pub index: usize,
132    pub succeeded: bool,
133    pub message: String,
134    pub executed_at_unix: u64,
135}
136
137#[derive(Debug, Clone, Serialize, Deserialize)]
138pub struct StoredPlan {
139    pub schema_version: String,
140    pub plan_id: String,
141    pub profile: String,
142    pub summary: String,
143    pub created_at_unix: u64,
144    pub expires_at_unix: u64,
145    pub status: PlanStatus,
146    pub risk_level: RiskLevel,
147    pub reversibility: Reversibility,
148    pub plan_hash: String,
149    pub approval_code: String,
150    #[serde(default)]
151    pub approved_at_unix: Option<u64>,
152    #[serde(default)]
153    pub applied_at_unix: Option<u64>,
154    pub operations: Vec<PlanOperation>,
155    pub preview_lines: Vec<String>,
156    #[serde(default)]
157    pub completed_ops: Vec<OperationRecord>,
158}
159
160/// Exklusiver Dateilock gegen parallele oder doppelte Ausführung desselben Plans.
161pub struct PlanLock {
162    lock_path: PathBuf,
163}
164
165impl Drop for PlanLock {
166    fn drop(&mut self) {
167        let _ = fs::remove_file(&self.lock_path);
168    }
169}
170
171impl PlanOperation {
172    pub fn risk_level(&self) -> RiskLevel {
173        match self {
174            Self::NotesCreate { .. }
175            | Self::NotesCreateFolder { .. }
176            | Self::MailCreateDraft { .. }
177            | Self::MailMarkRead { .. }
178            | Self::RemindersCreate { .. } => RiskLevel::Low,
179            Self::NotesAppend { .. }
180            | Self::NotesMove { .. }
181            | Self::NotesMoveFolderContents { .. }
182            | Self::NotesDeleteEmptyFolder { .. }
183            | Self::MailMove { .. } => RiskLevel::Medium,
184            // Kurzbefehle können beliebige Nebenwirkungen in macOS/externen Diensten auslösen.
185            Self::ShortcutsRun { .. } => RiskLevel::High,
186        }
187    }
188
189    pub fn reversibility(&self) -> Reversibility {
190        match self {
191            Self::ShortcutsRun { .. } => Reversibility::Irreversible,
192            Self::NotesAppend { .. } => Reversibility::BestEffort,
193            _ => Reversibility::Reversible,
194        }
195    }
196
197    /// Vollständige Inhalts- und Diff-Vorschau für die menschliche Prüfung vor Freigabe.
198    pub fn detailed_preview(&self) -> Vec<String> {
199        let mut lines = vec![format!(
200            "{}  [risk: {:?} | reversibility: {:?}]",
201            self.preview(),
202            self.risk_level(),
203            self.reversibility()
204        )];
205        match self {
206            Self::MailCreateDraft {
207                account,
208                to,
209                cc,
210                subject,
211                body,
212                signature_name,
213                reply_to_local_id,
214            } => {
215                if let Some(acc) = account {
216                    lines.push(format!("    Account:   {acc}"));
217                }
218                lines.push(format!("    To:        {}", to.join(", ")));
219                if !cc.is_empty() {
220                    lines.push(format!("    Cc:        {}", cc.join(", ")));
221                }
222                lines.push(format!("    Subject:   {subject}"));
223                if let Some(sig) = signature_name {
224                    lines.push(format!("    Signature: {sig}"));
225                }
226                if let Some(reply_id) = reply_to_local_id {
227                    lines.push(format!("    Reply-To:  {reply_id}"));
228                }
229                lines.push("    --- Draft body (will NOT be sent automatically) ---".to_string());
230                for body_line in body.lines() {
231                    lines.push(format!("    | {body_line}"));
232                }
233                if body.is_empty() {
234                    lines.push("    | (leer)".to_string());
235                }
236            }
237            Self::NotesCreate {
238                account,
239                folder,
240                title,
241                body,
242            } => {
243                if let Some(acc) = account {
244                    lines.push(format!("    Account: {acc}"));
245                }
246                lines.push(format!("    Folder:  {folder}"));
247                lines.push(format!("    Title:   {title}"));
248                lines.push("    --- New note content ---".to_string());
249                for body_line in body.lines() {
250                    lines.push(format!("    + {body_line}"));
251                }
252            }
253            Self::NotesAppend {
254                note_id,
255                expected_revision,
256                text,
257            } => {
258                lines.push(format!("    Note ID:  {note_id}"));
259                if let Some(rev) = expected_revision {
260                    lines.push(format!("    Revision: {rev}"));
261                }
262                lines.push("    --- Appended text ---".to_string());
263                for tline in text.lines() {
264                    lines.push(format!("    + {tline}"));
265                }
266            }
267            Self::ShortcutsRun { name, input } => {
268                lines.push(format!("    Shortcut: {name}"));
269                if let Some(inp) = input {
270                    lines.push(format!("    Input:    {inp}"));
271                }
272                lines.push(
273                    "    ! HIGH RISK: Shortcuts can trigger arbitrary macOS or external actions and cannot be rolled back."
274                        .to_string(),
275                );
276            }
277            Self::RemindersCreate { list, title, notes } => {
278                if let Some(l) = list {
279                    lines.push(format!("    List:  {l}"));
280                }
281                lines.push(format!("    Title: {title}"));
282                if let Some(n) = notes {
283                    for nline in n.lines() {
284                        lines.push(format!("    + {nline}"));
285                    }
286                }
287            }
288            _ => {}
289        }
290        lines
291    }
292
293    pub fn preview(&self) -> String {
294        match self {
295            Self::NotesCreate {
296                folder,
297                title,
298                body,
299                ..
300            } => format!(
301                "[notes.create] Neue Notiz '{}' in Ordner '{}' ({} Zeichen)",
302                title,
303                folder,
304                body.chars().count()
305            ),
306            Self::NotesAppend { note_id, text, .. } => format!(
307                "[notes.append] An Notiz '{}' anhängen ({} Zeichen)",
308                note_id,
309                text.chars().count()
310            ),
311            Self::NotesMove {
312                note_id,
313                destination_folder,
314                ..
315            } => format!(
316                "[notes.move] Notiz '{}' → Ordner '{}'",
317                note_id, destination_folder
318            ),
319            Self::NotesMoveFolderContents {
320                source_folder_path,
321                destination_folder_path,
322                ..
323            } => format!(
324                "[notes.move_folder_contents] Alle Notizen aus '{}' → '{}'",
325                source_folder_path, destination_folder_path
326            ),
327            Self::NotesCreateFolder {
328                name,
329                parent_folder,
330                ..
331            } => match parent_folder {
332                Some(p) => format!("[notes.create_folder] Neuer Unterordner '{p}/{name}'"),
333                None => format!("[notes.create_folder] Neuer Ordner '{name}'"),
334            },
335            Self::NotesDeleteEmptyFolder {
336                folder_id,
337                folder_name,
338            } => format!(
339                "[notes.delete_empty_folder] Leeren Ordner '{}' ({}) entfernen",
340                folder_name, folder_id
341            ),
342            Self::MailCreateDraft {
343                to,
344                subject,
345                body,
346                ..
347            } => format!(
348                "[mail.create_draft] Entwurf an {} | Betreff: '{}' ({} Zeichen, KEIN Versand)",
349                to.join(", "),
350                subject,
351                body.chars().count()
352            ),
353            Self::MailMarkRead {
354                local_id,
355                mailbox,
356                read,
357                ..
358            } => format!(
359                "[mail.mark_read] Mail '{}' in '{}' als {} markieren",
360                local_id,
361                mailbox,
362                if *read { "gelesen" } else { "ungelesen" }
363            ),
364            Self::MailMove {
365                local_id,
366                from_mailbox,
367                to_mailbox,
368                ..
369            } => format!(
370                "[mail.move] Mail '{}' von '{}' → '{}'",
371                local_id, from_mailbox, to_mailbox
372            ),
373            Self::ShortcutsRun { name, input } => match input {
374                Some(_) => format!("[shortcuts.run] Kurzbefehl '{name}' (mit Eingabe) ausführen"),
375                None => format!("[shortcuts.run] Kurzbefehl '{name}' ausführen"),
376            },
377            Self::RemindersCreate { list, title, .. } => match list {
378                Some(l) => format!("[reminders.create] Neue Erinnerung '{title}' in Liste '{l}'"),
379                None => format!("[reminders.create] Neue Erinnerung '{title}'"),
380            },
381        }
382    }
383
384    pub fn validate_against_profile(
385        &self,
386        profile_name: &str,
387        profile: &ProfileConfig,
388    ) -> Result<(), MacflyError> {
389        match self {
390            Self::NotesCreate {
391                account, folder, ..
392            } => {
393                if let Some(acc) = account
394                    && !profile.notes.is_account_allowed(acc)
395                {
396                    return Err(MacflyError::ScopeDenied(format!(
397                        "Notes-Account '{acc}' im Profil '{profile_name}' nicht erlaubt"
398                    )));
399                }
400                if !profile.notes.is_folder_allowed(folder) {
401                    return Err(MacflyError::ScopeDenied(format!(
402                        "Zielordner '{folder}' im Profil '{profile_name}' gesperrt"
403                    )));
404                }
405            }
406            Self::NotesMove {
407                destination_folder,
408                destination_account,
409                ..
410            } => {
411                if let Some(acc) = destination_account
412                    && !profile.notes.is_account_allowed(acc)
413                {
414                    return Err(MacflyError::ScopeDenied(format!(
415                        "Ziel-Account '{acc}' im Profil '{profile_name}' nicht erlaubt"
416                    )));
417                }
418                if !profile.notes.is_folder_allowed(destination_folder) {
419                    return Err(MacflyError::ScopeDenied(format!(
420                        "Zielordner '{destination_folder}' im Profil '{profile_name}' gesperrt"
421                    )));
422                }
423            }
424            Self::NotesMoveFolderContents {
425                source_folder_path,
426                destination_folder_path,
427                destination_account,
428                ..
429            } => {
430                if let Some(acc) = destination_account
431                    && !profile.notes.is_account_allowed(acc)
432                {
433                    return Err(MacflyError::ScopeDenied(format!(
434                        "Ziel-Account '{acc}' im Profil '{profile_name}' nicht erlaubt"
435                    )));
436                }
437                if !profile.notes.is_folder_allowed(source_folder_path)
438                    || !profile.notes.is_folder_allowed(destination_folder_path)
439                {
440                    return Err(MacflyError::ScopeDenied(format!(
441                        "Verschiebung '{source_folder_path}' → '{destination_folder_path}' im Profil '{profile_name}' gesperrt"
442                    )));
443                }
444            }
445            Self::NotesCreateFolder { account, name, .. } => {
446                if let Some(acc) = account
447                    && !profile.notes.is_account_allowed(acc)
448                {
449                    return Err(MacflyError::ScopeDenied(format!(
450                        "Notes-Account '{acc}' im Profil '{profile_name}' nicht erlaubt"
451                    )));
452                }
453                if !profile.notes.is_folder_allowed(name) {
454                    return Err(MacflyError::ScopeDenied(format!(
455                        "Ordnername '{name}' im Profil '{profile_name}' gesperrt"
456                    )));
457                }
458            }
459            Self::NotesDeleteEmptyFolder { folder_name, .. } => {
460                if !profile.notes.is_folder_allowed(folder_name) {
461                    return Err(MacflyError::ScopeDenied(format!(
462                        "Ordner '{folder_name}' im Profil '{profile_name}' gesperrt"
463                    )));
464                }
465            }
466            Self::NotesAppend { .. } => {}
467            Self::MailCreateDraft { account, to, .. } => {
468                if to.is_empty() {
469                    return Err(MacflyError::PlanError(
470                        "mail.create_draft benötigt mindestens einen Empfänger in `to`".to_string(),
471                    ));
472                }
473                if let Some(acc) = account
474                    && !profile.mail.is_account_allowed(acc)
475                {
476                    return Err(MacflyError::ScopeDenied(format!(
477                        "Mail-Account '{acc}' im Profil '{profile_name}' nicht erlaubt"
478                    )));
479                }
480            }
481            Self::MailMarkRead {
482                account, mailbox, ..
483            } => {
484                if !profile.mail.is_account_allowed(account)
485                    || !profile.mail.is_mailbox_allowed(mailbox)
486                {
487                    return Err(MacflyError::ScopeDenied(format!(
488                        "Postfach '{account}/{mailbox}' im Profil '{profile_name}' gesperrt"
489                    )));
490                }
491            }
492            Self::MailMove {
493                account,
494                from_mailbox,
495                to_mailbox,
496                ..
497            } => {
498                if !profile.mail.is_account_allowed(account)
499                    || !profile.mail.is_mailbox_allowed(from_mailbox)
500                    || !profile.mail.is_mailbox_allowed(to_mailbox)
501                {
502                    return Err(MacflyError::ScopeDenied(format!(
503                        "Mail-Verschiebung in '{account}' im Profil '{profile_name}' gesperrt"
504                    )));
505                }
506            }
507            Self::ShortcutsRun { name, .. } => {
508                if !profile.shortcuts.is_allowed(name) {
509                    return Err(MacflyError::ScopeDenied(format!(
510                        "Kurzbefehl '{name}' ist im Profil '{profile_name}' nicht in `shortcuts.allow` freigegeben"
511                    )));
512                }
513            }
514            Self::RemindersCreate { title, .. } => {
515                if title.trim().is_empty() {
516                    return Err(MacflyError::PlanError(
517                        "reminders.create benötigt einen nicht-leeren Titel".to_string(),
518                    ));
519                }
520            }
521        }
522        Ok(())
523    }
524}
525
526pub struct PlanStore {
527    plans_dir: PathBuf,
528}
529
530impl PlanStore {
531    pub fn default_store() -> Self {
532        Self::new(data_dir().join("plans"))
533    }
534
535    pub fn new(plans_dir: PathBuf) -> Self {
536        Self { plans_dir }
537    }
538
539    pub fn create(
540        &self,
541        profile_name: &str,
542        profile: &ProfileConfig,
543        proposal: PlanProposal,
544        ttl_secs: u64,
545    ) -> Result<StoredPlan, MacflyError> {
546        if proposal.operations.is_empty() {
547            return Err(MacflyError::PlanError(
548                "Änderungsplan enthält keine Operationen".to_string(),
549            ));
550        }
551
552        for op in &proposal.operations {
553            op.validate_against_profile(profile_name, profile)?;
554        }
555
556        let now = now_unix();
557        let canonical_ops = serde_json::to_string(&proposal.operations)?;
558        let hash_input = format!("{profile_name}\n{canonical_ops}");
559        let full_hash = compute_sha256_hex(&hash_input);
560        let plan_hash = format!("sha256:{full_hash}");
561        let approval_code = full_hash[..6].to_ascii_uppercase();
562        let plan_id = format!("plan-{now}-{}", &full_hash[..8]);
563
564        let mut risk_level = proposal
565            .operations
566            .iter()
567            .map(PlanOperation::risk_level)
568            .max()
569            .unwrap_or(RiskLevel::Low);
570        if proposal.operations.len() > 5 && risk_level < RiskLevel::High {
571            risk_level = RiskLevel::High;
572        }
573
574        let reversibility = if proposal
575            .operations
576            .iter()
577            .any(|o| o.reversibility() == Reversibility::Irreversible)
578        {
579            Reversibility::Irreversible
580        } else if proposal
581            .operations
582            .iter()
583            .any(|o| o.reversibility() == Reversibility::BestEffort)
584        {
585            Reversibility::BestEffort
586        } else {
587            Reversibility::Reversible
588        };
589
590        let preview_lines: Vec<String> =
591            proposal.operations.iter().map(PlanOperation::preview).collect();
592        let summary = proposal
593            .summary
594            .unwrap_or_else(|| format!("{} Operation(en)", proposal.operations.len()));
595
596        let plan = StoredPlan {
597            schema_version: "1.0".to_string(),
598            plan_id,
599            profile: profile_name.to_string(),
600            summary,
601            created_at_unix: now,
602            expires_at_unix: now + ttl_secs,
603            status: PlanStatus::PendingApproval,
604            risk_level,
605            reversibility,
606            plan_hash,
607            approval_code,
608            approved_at_unix: None,
609            applied_at_unix: None,
610            operations: proposal.operations,
611            preview_lines,
612            completed_ops: Vec::new(),
613        };
614
615        self.save(&plan)?;
616        Ok(plan)
617    }
618
619    pub fn load(&self, plan_id: &str) -> Result<StoredPlan, MacflyError> {
620        let path = self.plan_path(plan_id)?;
621        if !path.exists() {
622            return Err(MacflyError::NotFound(format!(
623                "Plan '{plan_id}' nicht gefunden"
624            )));
625        }
626        let raw = fs::read_to_string(&path)?;
627        let plan: StoredPlan = serde_json::from_str(&raw)?;
628        verify_plan_integrity(&plan)?;
629        Ok(plan)
630    }
631
632    pub fn list(&self) -> Result<Vec<StoredPlan>, MacflyError> {
633        if !self.plans_dir.exists() {
634            return Ok(Vec::new());
635        }
636        let mut plans = Vec::new();
637        for entry in fs::read_dir(&self.plans_dir)? {
638            let entry = entry?;
639            let path = entry.path();
640            if path.extension().and_then(|e| e.to_str()) != Some("json") {
641                continue;
642            }
643            if let Ok(raw) = fs::read_to_string(&path)
644                && let Ok(plan) = serde_json::from_str::<StoredPlan>(&raw)
645            {
646                plans.push(plan);
647            }
648        }
649        plans.sort_by_key(|a| std::cmp::Reverse(a.created_at_unix));
650        Ok(plans)
651    }
652
653    pub fn approve(&self, plan_id: &str, confirm_code: &str) -> Result<StoredPlan, MacflyError> {
654        let mut plan = self.load(plan_id)?;
655        let now = now_unix();
656        if now > plan.expires_at_unix {
657            return Err(MacflyError::ApprovalError(format!(
658                "Plan '{plan_id}' ist abgelaufen (bitte neu erstellen)"
659            )));
660        }
661        if plan.status != PlanStatus::PendingApproval {
662            return Err(MacflyError::ApprovalError(format!(
663                "Plan '{plan_id}' hat Status {:?} und kann nicht erneut freigegeben werden",
664                plan.status
665            )));
666        }
667        if !confirm_code.trim().eq_ignore_ascii_case(&plan.approval_code) {
668            return Err(MacflyError::ApprovalError(format!(
669                "Ungültiger Bestätigungscode (erwartet: {})",
670                plan.approval_code
671            )));
672        }
673        plan.status = PlanStatus::Approved;
674        plan.approved_at_unix = Some(now);
675        self.save(&plan)?;
676        Ok(plan)
677    }
678
679    pub fn save(&self, plan: &StoredPlan) -> Result<(), MacflyError> {
680        ensure_private_dir(&self.plans_dir)?;
681        let path = self.plan_path(&plan.plan_id)?;
682        let json = serde_json::to_string_pretty(plan)?;
683        write_private_file(&path, &format!("{json}\n"))?;
684        Ok(())
685    }
686
687    pub fn acquire_lock(&self, plan_id: &str) -> Result<PlanLock, MacflyError> {
688        ensure_private_dir(&self.plans_dir)?;
689        let plan_path = self.plan_path(plan_id)?;
690        let lock_path = plan_path.with_extension("lock");
691        let mut file = OpenOptions::new()
692            .write(true)
693            .create_new(true)
694            .open(&lock_path)
695            .map_err(|e| {
696                if e.kind() == std::io::ErrorKind::AlreadyExists {
697                    MacflyError::ApprovalError(format!(
698                        "Plan '{plan_id}' wird bereits von einem anderen Prozess ausgeführt (Lock aktiv: {})",
699                        lock_path.display()
700                    ))
701                } else {
702                    MacflyError::Io(e)
703                }
704            })?;
705        let _ = writeln!(file, "pid={} started_at={}", std::process::id(), now_unix());
706        Ok(PlanLock { lock_path })
707    }
708
709    fn plan_path(&self, plan_id: &str) -> Result<PathBuf, MacflyError> {
710        if plan_id.contains('/') || plan_id.contains('\\') || plan_id.contains("..") {
711            return Err(MacflyError::PlanError(format!(
712                "Ungültige Plan-ID '{plan_id}'"
713            )));
714        }
715        Ok(self.plans_dir.join(format!("{plan_id}.json")))
716    }
717}
718
719pub fn verify_plan_integrity(plan: &StoredPlan) -> Result<(), MacflyError> {
720    let canonical_ops = serde_json::to_string(&plan.operations)?;
721    let expected = format!(
722        "sha256:{}",
723        compute_sha256_hex(&format!("{}\n{}", plan.profile, canonical_ops))
724    );
725    if plan.plan_hash != expected {
726        return Err(MacflyError::ApprovalError(format!(
727            "Integritätsfehler: Plan '{}' wurde nach Erstellung verändert!",
728            plan.plan_id
729        )));
730    }
731    Ok(())
732}
733
734pub fn now_unix() -> u64 {
735    SystemTime::now()
736        .duration_since(UNIX_EPOCH)
737        .map(|d| d.as_secs())
738        .unwrap_or(0)
739}
740
741pub fn ensure_private_dir(path: &Path) -> Result<(), MacflyError> {
742    fs::create_dir_all(path)?;
743    #[cfg(unix)]
744    {
745        use std::os::unix::fs::PermissionsExt;
746        let _ = fs::set_permissions(path, fs::Permissions::from_mode(0o700));
747    }
748    Ok(())
749}
750
751pub fn write_private_file(path: &Path, content: &str) -> Result<(), MacflyError> {
752    fs::write(path, content)?;
753    #[cfg(unix)]
754    {
755        use std::os::unix::fs::PermissionsExt;
756        let _ = fs::set_permissions(path, fs::Permissions::from_mode(0o600));
757    }
758    Ok(())
759}
760
761fn default_schema_version() -> String {
762    "1.0".to_string()
763}
764
765#[cfg(test)]
766mod tests {
767    use super::*;
768
769    fn temp_store(tag: &str) -> PlanStore {
770        let dir = std::env::temp_dir().join(format!("macfly-test-{tag}-{}", now_unix()));
771        let _ = fs::remove_dir_all(&dir);
772        PlanStore::new(dir)
773    }
774
775    #[test]
776    fn plan_create_approve_and_tamper_detection() {
777        let store = temp_store("tamper");
778        let profile = ProfileConfig::default();
779        let proposal = PlanProposal {
780            schema_version: "1.0".to_string(),
781            summary: Some("Ordner aufräumen".to_string()),
782            operations: vec![PlanOperation::NotesMove {
783                note_id: "x-coredata://123".to_string(),
784                expected_revision: None,
785                destination_folder: "Archiv".to_string(),
786                destination_account: None,
787            }],
788        };
789
790        let plan = store.create("default", &profile, proposal, 600).unwrap();
791        assert_eq!(plan.status, PlanStatus::PendingApproval);
792        assert_eq!(plan.risk_level, RiskLevel::Medium);
793
794        // Falscher Code wird abgewiesen
795        assert!(store.approve(&plan.plan_id, "000000").is_err());
796
797        // Richtiger Code gibt frei
798        let approved = store.approve(&plan.plan_id, &plan.approval_code).unwrap();
799        assert_eq!(approved.status, PlanStatus::Approved);
800
801        // Manipulation der gespeicherten Datei wird erkannt
802        let path = store.plan_path(&plan.plan_id).unwrap();
803        let raw = fs::read_to_string(&path).unwrap().replace("Archiv", "Manipuliert");
804        fs::write(&path, raw).unwrap();
805        assert!(store.load(&plan.plan_id).is_err());
806    }
807
808    #[test]
809    fn blocks_denied_folder_in_plan() {
810        let store = temp_store("scope");
811        let profile = ProfileConfig::default();
812        let proposal = PlanProposal {
813            schema_version: "1.0".to_string(),
814            summary: None,
815            operations: vec![PlanOperation::NotesMove {
816                note_id: "x-coredata://123".to_string(),
817                expected_revision: None,
818                destination_folder: "Passwörter".to_string(),
819                destination_account: None,
820            }],
821        };
822        let err = store.create("default", &profile, proposal, 600).unwrap_err();
823        assert_eq!(err.code(), "SCOPE_DENIED");
824    }
825
826    #[test]
827    fn shortcuts_run_requires_explicit_allowlist() {
828        let store = temp_store("shortcuts");
829        let mut profile = ProfileConfig::default();
830        let proposal = PlanProposal {
831            schema_version: "1.0".to_string(),
832            summary: Some("Fokus-Szene".to_string()),
833            operations: vec![PlanOperation::ShortcutsRun {
834                name: "Office Focus".to_string(),
835                input: None,
836            }],
837        };
838
839        let err = store
840            .create("default", &profile, proposal.clone(), 600)
841            .unwrap_err();
842        assert_eq!(err.code(), "SCOPE_DENIED");
843
844        profile.shortcuts.allow.push("Office Focus".to_string());
845        let ok = store.create("default", &profile, proposal, 600).unwrap();
846        assert_eq!(ok.risk_level, RiskLevel::High);
847        assert_eq!(ok.reversibility, Reversibility::Irreversible);
848    }
849
850    #[test]
851    fn plan_lock_prevents_concurrent_execution() {
852        let store = temp_store("lock");
853        let lock1 = store.acquire_lock("plan-123").unwrap();
854        let err = store.acquire_lock("plan-123").err().unwrap();
855        assert_eq!(err.code(), "APPROVAL_ERROR");
856        drop(lock1);
857        assert!(store.acquire_lock("plan-123").is_ok());
858    }
859
860    #[test]
861    fn detailed_preview_shows_full_mail_draft_body_and_notes_diff() {
862        let draft = PlanOperation::MailCreateDraft {
863            account: Some("Exchange".to_string()),
864            to: vec!["billing@acme.example".to_string()],
865            cc: vec![],
866            subject: "Re: Invoice #42".to_string(),
867            body: "Line one\nLine two".to_string(),
868            signature_name: Some("Corporate".to_string()),
869            reply_to_local_id: None,
870        };
871        let lines = draft.detailed_preview().join("\n");
872        assert!(lines.contains("| Line one"));
873        assert!(lines.contains("| Line two"));
874        assert!(lines.contains("Signature: Corporate"));
875
876        let note = PlanOperation::NotesAppend {
877            note_id: "x-coredata://note/1".to_string(),
878            expected_revision: Some("sha256:abc".to_string()),
879            text: "New bullet".to_string(),
880        };
881        let note_lines = note.detailed_preview().join("\n");
882        assert!(note_lines.contains("+ New bullet"));
883    }
884}