Skip to main content

ragfs_fuse/
ops.rs

1//! Operations manager for agent file management.
2//!
3//! This module provides a structured interface for file operations with JSON feedback,
4//! designed for AI agents to manage files through the virtual `.ops/` directory.
5
6use chrono::{DateTime, Utc};
7use ragfs_core::VectorStore;
8use serde::{Deserialize, Serialize};
9use std::fs;
10use std::path::{Path, PathBuf};
11use std::sync::Arc;
12use tokio::sync::{RwLock, mpsc};
13use tracing::{debug, info, warn};
14use uuid::Uuid;
15
16use crate::safety::{HistoryOperation, SafetyManager, UndoData};
17
18/// A single file operation.
19#[derive(Debug, Clone, Serialize, Deserialize)]
20#[serde(tag = "op", rename_all = "snake_case")]
21pub enum Operation {
22    /// Create a new file with content
23    Create { path: PathBuf, content: String },
24    /// Delete a file (soft delete if safety layer is enabled)
25    Delete { path: PathBuf },
26    /// Move/rename a file
27    Move { src: PathBuf, dst: PathBuf },
28    /// Copy a file
29    Copy { src: PathBuf, dst: PathBuf },
30    /// Write content to a file (overwrite or append)
31    Write {
32        path: PathBuf,
33        content: String,
34        #[serde(default)]
35        append: bool,
36    },
37    /// Create a directory
38    Mkdir { path: PathBuf },
39    /// Create a symbolic link
40    Symlink { target: PathBuf, link: PathBuf },
41}
42
43/// Batch operation request.
44#[derive(Debug, Clone, Serialize, Deserialize)]
45pub struct BatchRequest {
46    /// List of operations to perform
47    pub operations: Vec<Operation>,
48    /// If true, rollback all operations if any fails
49    #[serde(default)]
50    pub atomic: bool,
51    /// If true, only validate without executing
52    #[serde(default)]
53    pub dry_run: bool,
54}
55
56/// Result of a single operation.
57#[derive(Debug, Clone, Serialize, Deserialize)]
58pub struct OperationResult {
59    /// Unique identifier for this operation
60    pub id: Uuid,
61    /// Whether the operation succeeded
62    pub success: bool,
63    /// Type of operation performed
64    pub operation: String,
65    /// Primary path involved
66    pub path: PathBuf,
67    /// Error message if failed
68    #[serde(skip_serializing_if = "Option::is_none")]
69    pub error: Option<String>,
70    /// Timestamp of the operation
71    pub timestamp: DateTime<Utc>,
72    /// Whether the file was indexed/reindexed
73    pub indexed: bool,
74    /// `SafetyManager` history id — write this to `.safety/.undo`
75    #[serde(skip_serializing_if = "Option::is_none")]
76    pub undo_id: Option<Uuid>,
77    /// Soft-delete trash entry used by atomic batch rollback (not in `.result` JSON)
78    #[serde(skip)]
79    trash_id: Option<Uuid>,
80}
81
82impl OperationResult {
83    /// Create a successful operation result.
84    pub fn success(operation: &str, path: PathBuf, indexed: bool) -> Self {
85        Self {
86            id: Uuid::new_v4(),
87            success: true,
88            operation: operation.to_string(),
89            path,
90            error: None,
91            timestamp: Utc::now(),
92            indexed,
93            undo_id: None,
94            trash_id: None,
95        }
96    }
97
98    /// Create a failed operation result.
99    pub fn failure(operation: &str, path: PathBuf, error: String) -> Self {
100        Self {
101            id: Uuid::new_v4(),
102            success: false,
103            operation: operation.to_string(),
104            path,
105            error: Some(error),
106            timestamp: Utc::now(),
107            indexed: false,
108            undo_id: None,
109            trash_id: None,
110        }
111    }
112}
113
114/// Result of batch operations.
115#[derive(Debug, Clone, Serialize, Deserialize)]
116pub struct BatchResult {
117    /// Unique identifier for this batch
118    pub id: Uuid,
119    /// Whether all operations succeeded
120    pub success: bool,
121    /// Total number of operations
122    pub total: usize,
123    /// Number of successful operations
124    pub succeeded: usize,
125    /// Number of failed operations
126    pub failed: usize,
127    /// Individual operation results
128    pub results: Vec<OperationResult>,
129    /// Timestamp of the batch
130    pub timestamp: DateTime<Utc>,
131    /// Whether a rollback was performed (for atomic batches)
132    #[serde(skip_serializing_if = "Option::is_none")]
133    pub rollback_performed: Option<bool>,
134    /// Details about rollback if it was attempted
135    #[serde(skip_serializing_if = "Option::is_none")]
136    pub rollback_details: Option<RollbackDetails>,
137}
138
139/// Details about rollback execution for atomic batches.
140#[derive(Debug, Clone, Serialize, Deserialize)]
141pub struct RollbackDetails {
142    /// Number of operations rolled back successfully
143    pub rolled_back: usize,
144    /// Number of operations that failed to rollback
145    pub rollback_failures: usize,
146    /// Errors encountered during rollback
147    pub errors: Vec<RollbackError>,
148}
149
150/// Error encountered during a rollback operation.
151#[derive(Debug, Clone, Serialize, Deserialize)]
152pub struct RollbackError {
153    /// Index of the operation in the original batch
154    pub operation_index: usize,
155    /// Error message
156    pub error: String,
157}
158
159/// Data needed to rollback an operation.
160/// This is internal to batch operations and more detailed than `UndoData`.
161#[derive(Debug, Clone)]
162enum RollbackData {
163    /// Rollback a create by deleting the created file
164    Create { created_path: PathBuf },
165    /// Rollback a delete by restoring from trash or backup content
166    Delete {
167        original_path: PathBuf,
168        trash_id: Option<Uuid>,
169        content_backup: Option<Vec<u8>>,
170    },
171    /// Rollback a move by moving back
172    Move { src: PathBuf, dst: PathBuf },
173    /// Rollback a copy by deleting the copy
174    Copy { copied_path: PathBuf },
175    /// Rollback a write by restoring previous content
176    Write {
177        path: PathBuf,
178        previous_content: Option<Vec<u8>>,
179        file_existed: bool,
180    },
181    /// Rollback a mkdir by removing the directory
182    Mkdir { created_path: PathBuf },
183    /// Rollback a symlink by removing the link
184    Symlink { link_path: PathBuf },
185}
186
187/// Journal entry tracking an executed operation for potential rollback.
188#[derive(Debug, Clone)]
189struct JournalEntry {
190    /// Index of the operation in the batch
191    operation_index: usize,
192    /// Data needed to rollback this operation
193    rollback_data: RollbackData,
194}
195
196/// Operations manager for file operations with feedback.
197pub struct OpsManager {
198    /// Source directory root
199    source: PathBuf,
200    /// Vector store for indexing operations
201    store: Option<Arc<dyn VectorStore>>,
202    /// Channel to send reindex requests
203    reindex_sender: Option<mpsc::Sender<PathBuf>>,
204    /// Safety manager for trash/history/undo (optional)
205    safety_manager: Option<Arc<SafetyManager>>,
206    /// Last operation result (for .result file)
207    last_result: Arc<RwLock<Option<OperationResult>>>,
208    /// Last batch result
209    last_batch_result: Arc<RwLock<Option<BatchResult>>>,
210}
211
212impl OpsManager {
213    /// Create a new operations manager.
214    pub fn new(
215        source: PathBuf,
216        store: Option<Arc<dyn VectorStore>>,
217        reindex_sender: Option<mpsc::Sender<PathBuf>>,
218    ) -> Self {
219        Self {
220            source,
221            store,
222            reindex_sender,
223            safety_manager: None,
224            last_result: Arc::new(RwLock::new(None)),
225            last_batch_result: Arc::new(RwLock::new(None)),
226        }
227    }
228
229    /// Create operations manager with safety manager.
230    pub fn with_safety(
231        source: PathBuf,
232        store: Option<Arc<dyn VectorStore>>,
233        reindex_sender: Option<mpsc::Sender<PathBuf>>,
234        safety_manager: Arc<SafetyManager>,
235    ) -> Self {
236        Self {
237            source,
238            store,
239            reindex_sender,
240            safety_manager: Some(safety_manager),
241            last_result: Arc::new(RwLock::new(None)),
242            last_batch_result: Arc::new(RwLock::new(None)),
243        }
244    }
245
246    /// Set the safety manager.
247    pub fn set_safety_manager(&mut self, safety_manager: Arc<SafetyManager>) {
248        self.safety_manager = Some(safety_manager);
249    }
250
251    /// Log operation to history if safety manager is available.
252    /// Returns the history entry id used as `OperationResult.undo_id`.
253    fn log_to_history(
254        &self,
255        operation: HistoryOperation,
256        undo_data: Option<UndoData>,
257    ) -> Option<Uuid> {
258        self.safety_manager
259            .as_ref()
260            .map(|safety| safety.log_success(operation, undo_data))
261    }
262
263    /// Log failure to history if safety manager is available.
264    fn log_failure_to_history(&self, operation: HistoryOperation, error: &str) {
265        if let Some(ref safety) = self.safety_manager {
266            safety.log_failure(operation, error.to_string());
267        }
268    }
269
270    /// Resolve a path relative to the source directory.
271    /// Rejects paths that escape the source root (absolute, `..`, symlink).
272    fn resolve_path(&self, path: &PathBuf) -> Result<PathBuf, String> {
273        ragfs_core::resolve_under_root(&self.source, path)
274    }
275
276    /// Jail-check a symlink target the way Unix will resolve it: relative
277    /// targets are interpreted from the link's parent, not the source root.
278    fn jail_symlink_target(
279        &self,
280        target: &PathBuf,
281        resolved_link: &Path,
282    ) -> Result<PathBuf, String> {
283        let validation_target = if target.is_absolute() {
284            target.clone()
285        } else if let Some(parent) = resolved_link.parent() {
286            parent.join(target)
287        } else {
288            target.clone()
289        };
290        self.resolve_path(&validation_target)
291    }
292
293    async fn fail_and_store(
294        &self,
295        operation: &str,
296        path: PathBuf,
297        error: String,
298    ) -> OperationResult {
299        let result = OperationResult::failure(operation, path, error);
300        *self.last_result.write().await = Some(result.clone());
301        result
302    }
303
304    /// Trigger reindexing for a path.
305    async fn trigger_reindex(&self, path: &PathBuf) -> bool {
306        if let Some(ref sender) = self.reindex_sender {
307            match sender.send(path.clone()).await {
308                Ok(()) => {
309                    debug!("Reindex triggered for {:?}", path);
310                    true
311                }
312                Err(e) => {
313                    warn!("Failed to trigger reindex for {:?}: {}", path, e);
314                    false
315                }
316            }
317        } else {
318            false
319        }
320    }
321
322    /// Delete from vector store.
323    async fn delete_from_store(&self, path: &PathBuf) {
324        if let Some(ref store) = self.store
325            && let Err(e) = store.delete_by_file_path(path).await
326        {
327            warn!("Failed to delete {:?} from store: {e}", path);
328        }
329    }
330
331    /// Update path in vector store.
332    async fn update_store_path(&self, from: &PathBuf, to: &PathBuf) {
333        if let Some(ref store) = self.store
334            && let Err(e) = store.update_file_path(from, to).await
335        {
336            warn!("Failed to update path in store {:?} -> {:?}: {e}", from, to);
337        }
338    }
339
340    /// Execute an operation and capture rollback data for atomic batches.
341    /// Returns (result, `rollback_data`) tuple.
342    async fn execute_with_rollback(
343        &self,
344        op: &Operation,
345    ) -> (OperationResult, Option<RollbackData>) {
346        match op {
347            Operation::Create { path, content } => {
348                let result = self.create(path, content).await;
349                let rollback = if result.success {
350                    self.resolve_path(path)
351                        .ok()
352                        .map(|created_path| RollbackData::Create { created_path })
353                } else {
354                    None
355                };
356                (result, rollback)
357            }
358            Operation::Delete { path } => {
359                let resolved = match self.resolve_path(path) {
360                    Ok(p) => p,
361                    Err(_) => return (self.delete(path).await, None),
362                };
363                // Capture content before delete for rollback (in case of hard delete)
364                let content_backup = if resolved.exists() && resolved.is_file() {
365                    fs::read(&resolved).ok()
366                } else {
367                    None
368                };
369
370                let result = self.delete(path).await;
371                let rollback = if result.success {
372                    Some(RollbackData::Delete {
373                        original_path: resolved,
374                        trash_id: result.trash_id,
375                        content_backup: if result.trash_id.is_none() {
376                            content_backup
377                        } else {
378                            None
379                        },
380                    })
381                } else {
382                    None
383                };
384                (result, rollback)
385            }
386            Operation::Move { src, dst } => {
387                let result = self.move_file(src, dst).await;
388                let rollback = if result.success {
389                    match (self.resolve_path(src), self.resolve_path(dst)) {
390                        (Ok(resolved_src), Ok(resolved_dst)) => Some(RollbackData::Move {
391                            src: resolved_dst,
392                            dst: resolved_src,
393                        }),
394                        _ => None,
395                    }
396                } else {
397                    None
398                };
399                (result, rollback)
400            }
401            Operation::Copy { src, dst } => {
402                let result = self.copy(src, dst).await;
403                let rollback = if result.success {
404                    self.resolve_path(dst)
405                        .ok()
406                        .map(|copied_path| RollbackData::Copy { copied_path })
407                } else {
408                    None
409                };
410                (result, rollback)
411            }
412            Operation::Write {
413                path,
414                content,
415                append,
416            } => {
417                let (file_existed, previous_content, resolved) = match self.resolve_path(path) {
418                    Ok(resolved) => {
419                        let file_existed = resolved.exists();
420                        let previous_content = if file_existed {
421                            fs::read(&resolved).ok()
422                        } else {
423                            None
424                        };
425                        (file_existed, previous_content, Some(resolved))
426                    }
427                    Err(_) => (false, None, None),
428                };
429
430                let result = self.write(path, content, *append).await;
431                let rollback = if result.success {
432                    resolved.map(|path| RollbackData::Write {
433                        path,
434                        previous_content,
435                        file_existed,
436                    })
437                } else {
438                    None
439                };
440                (result, rollback)
441            }
442            Operation::Mkdir { path } => {
443                let result = self.mkdir(path).await;
444                let rollback = if result.success {
445                    self.resolve_path(path)
446                        .ok()
447                        .map(|created_path| RollbackData::Mkdir { created_path })
448                } else {
449                    None
450                };
451                (result, rollback)
452            }
453            Operation::Symlink { target, link } => {
454                let result = self.symlink(target, link).await;
455                let rollback = if result.success {
456                    self.resolve_path(link)
457                        .ok()
458                        .map(|link_path| RollbackData::Symlink { link_path })
459                } else {
460                    None
461                };
462                (result, rollback)
463            }
464        }
465    }
466
467    /// Rollback a single operation.
468    async fn rollback_operation(&self, rollback_data: &RollbackData) -> Result<(), String> {
469        match rollback_data {
470            RollbackData::Create { created_path } => {
471                // Undo create by deleting the file
472                if created_path.exists() {
473                    fs::remove_file(created_path)
474                        .map_err(|e| format!("Failed to rollback create: {e}"))?;
475                    // Remove from vector store
476                    self.delete_from_store(created_path).await;
477                }
478                Ok(())
479            }
480            RollbackData::Delete {
481                original_path,
482                trash_id,
483                content_backup,
484            } => {
485                // Try to restore from trash first
486                if let Some(id) = trash_id
487                    && let Some(ref safety) = self.safety_manager
488                {
489                    return safety
490                        .restore(*id)
491                        .await
492                        .map(|_| ())
493                        .map_err(|e| format!("Failed to restore from trash: {e}"));
494                }
495                // Fall back to content backup
496                if let Some(content) = content_backup {
497                    if let Some(parent) = original_path.parent() {
498                        fs::create_dir_all(parent)
499                            .map_err(|e| format!("Failed to create parent dir: {e}"))?;
500                    }
501                    fs::write(original_path, content)
502                        .map_err(|e| format!("Failed to restore content: {e}"))?;
503                    self.trigger_reindex(original_path).await;
504                    Ok(())
505                } else {
506                    Err("Cannot rollback delete: no trash entry or content backup".into())
507                }
508            }
509            RollbackData::Move { src, dst } => {
510                // Move back (src is current location, dst is original location)
511                if src.exists() {
512                    if let Some(parent) = dst.parent() {
513                        fs::create_dir_all(parent)
514                            .map_err(|e| format!("Failed to create parent dir: {e}"))?;
515                    }
516                    fs::rename(src, dst).map_err(|e| format!("Failed to rollback move: {e}"))?;
517                    self.update_store_path(src, dst).await;
518                }
519                Ok(())
520            }
521            RollbackData::Copy { copied_path } => {
522                // Delete the copy
523                if copied_path.exists() {
524                    fs::remove_file(copied_path)
525                        .map_err(|e| format!("Failed to rollback copy: {e}"))?;
526                    self.delete_from_store(copied_path).await;
527                }
528                Ok(())
529            }
530            RollbackData::Write {
531                path,
532                previous_content,
533                file_existed,
534            } => {
535                if *file_existed {
536                    if let Some(content) = previous_content {
537                        fs::write(path, content)
538                            .map_err(|e| format!("Failed to rollback write: {e}"))?;
539                    } else {
540                        return Err("Cannot rollback write: no previous content saved".into());
541                    }
542                } else {
543                    // File didn't exist before, delete it
544                    if path.exists() {
545                        fs::remove_file(path)
546                            .map_err(|e| format!("Failed to rollback write (delete): {e}"))?;
547                        self.delete_from_store(path).await;
548                    }
549                }
550                self.trigger_reindex(path).await;
551                Ok(())
552            }
553            RollbackData::Mkdir { created_path } => {
554                // Undo mkdir by removing the directory (only if empty)
555                if created_path.exists() && created_path.is_dir() {
556                    fs::remove_dir(created_path)
557                        .map_err(|e| format!("Failed to rollback mkdir: {e}"))?;
558                }
559                Ok(())
560            }
561            RollbackData::Symlink { link_path } => {
562                // Undo symlink by removing the link
563                if link_path.exists() || link_path.symlink_metadata().is_ok() {
564                    fs::remove_file(link_path)
565                        .map_err(|e| format!("Failed to rollback symlink: {e}"))?;
566                }
567                Ok(())
568            }
569        }
570    }
571
572    /// Perform rollback of journal entries in reverse order.
573    async fn perform_rollback(&self, journal: &[JournalEntry]) -> RollbackDetails {
574        let mut rolled_back = 0;
575        let mut rollback_failures = 0;
576        let mut errors = Vec::new();
577
578        // Rollback in reverse order
579        for entry in journal.iter().rev() {
580            match self.rollback_operation(&entry.rollback_data).await {
581                Ok(()) => {
582                    rolled_back += 1;
583                    info!("Rolled back operation index {}", entry.operation_index);
584                }
585                Err(e) => {
586                    rollback_failures += 1;
587                    warn!(
588                        "Failed to rollback operation index {}: {}",
589                        entry.operation_index, e
590                    );
591                    errors.push(RollbackError {
592                        operation_index: entry.operation_index,
593                        error: e,
594                    });
595                }
596            }
597        }
598
599        RollbackDetails {
600            rolled_back,
601            rollback_failures,
602            errors,
603        }
604    }
605
606    /// Create a new file with content.
607    pub async fn create(&self, path: &PathBuf, content: &str) -> OperationResult {
608        let resolved = match self.resolve_path(path) {
609            Ok(p) => p,
610            Err(e) => return self.fail_and_store("create", path.clone(), e).await,
611        };
612        debug!("ops::create {:?}", resolved);
613
614        // Check if file already exists
615        if resolved.exists() {
616            return OperationResult::failure("create", path.clone(), "File already exists".into());
617        }
618
619        // Ensure parent directory exists
620        if let Some(parent) = resolved.parent()
621            && !parent.exists()
622            && let Err(e) = fs::create_dir_all(parent)
623        {
624            return OperationResult::failure(
625                "create",
626                path.clone(),
627                format!("Failed to create parent directory: {e}"),
628            );
629        }
630
631        // Create the file
632        match fs::write(&resolved, content) {
633            Ok(()) => {
634                info!("Created file: {:?}", resolved);
635                let indexed = self.trigger_reindex(&resolved).await;
636                let undo_id = self.log_to_history(
637                    HistoryOperation::Create {
638                        path: resolved.clone(),
639                    },
640                    Some(UndoData::Create { path: resolved }),
641                );
642                let mut result = OperationResult::success("create", path.clone(), indexed);
643                result.undo_id = undo_id;
644
645                *self.last_result.write().await = Some(result.clone());
646                result
647            }
648            Err(e) => {
649                let error_msg = format!("Failed to create file: {e}");
650                self.log_failure_to_history(
651                    HistoryOperation::Create { path: resolved },
652                    &error_msg,
653                );
654
655                let result = OperationResult::failure("create", path.clone(), error_msg);
656                *self.last_result.write().await = Some(result.clone());
657                result
658            }
659        }
660    }
661
662    /// Delete a file.
663    /// Uses soft delete (move to trash) if safety manager is available.
664    pub async fn delete(&self, path: &PathBuf) -> OperationResult {
665        let resolved = match self.resolve_path(path) {
666            Ok(p) => p,
667            Err(e) => return self.fail_and_store("delete", path.clone(), e).await,
668        };
669        debug!("ops::delete {:?}", resolved);
670
671        if !resolved.exists() {
672            return OperationResult::failure("delete", path.clone(), "File not found".into());
673        }
674
675        if resolved.is_dir() {
676            return OperationResult::failure(
677                "delete",
678                path.clone(),
679                "Cannot delete directory with .delete, use rmdir".into(),
680            );
681        }
682
683        // Delete from store first
684        self.delete_from_store(&resolved).await;
685
686        // Try soft delete if safety manager is available
687        if let Some(ref safety) = self.safety_manager {
688            match safety.soft_delete(&resolved).await {
689                Ok(entry) => {
690                    info!("Soft deleted file: {:?} -> trash/{}", resolved, entry.id);
691
692                    let undo_id = self.log_to_history(
693                        HistoryOperation::Delete {
694                            path: resolved,
695                            trash_id: Some(entry.id),
696                        },
697                        Some(UndoData::Delete { trash_id: entry.id }),
698                    );
699
700                    let mut result = OperationResult::success("delete", path.clone(), false);
701                    result.undo_id = undo_id;
702                    result.trash_id = Some(entry.id);
703                    *self.last_result.write().await = Some(result.clone());
704                    return result;
705                }
706                Err(e) => {
707                    let error_msg = format!("Soft delete failed: {e}");
708                    warn!("{error_msg}");
709                    self.log_failure_to_history(
710                        HistoryOperation::Delete {
711                            path: resolved,
712                            trash_id: None,
713                        },
714                        &error_msg,
715                    );
716                    return self.fail_and_store("delete", path.clone(), error_msg).await;
717                }
718            }
719        }
720
721        // Hard delete only when no safety manager is configured.
722        match fs::remove_file(&resolved) {
723            Ok(()) => {
724                info!("Hard deleted file: {:?}", resolved);
725
726                let undo_id = self.log_to_history(
727                    HistoryOperation::Delete {
728                        path: resolved,
729                        trash_id: None,
730                    },
731                    None, // Hard delete is not reversible
732                );
733
734                let mut result = OperationResult::success("delete", path.clone(), false);
735                result.undo_id = undo_id;
736                *self.last_result.write().await = Some(result.clone());
737                result
738            }
739            Err(e) => {
740                let error_msg = format!("Failed to delete file: {e}");
741                self.log_failure_to_history(
742                    HistoryOperation::Delete {
743                        path: resolved,
744                        trash_id: None,
745                    },
746                    &error_msg,
747                );
748
749                let result = OperationResult::failure("delete", path.clone(), error_msg);
750                *self.last_result.write().await = Some(result.clone());
751                result
752            }
753        }
754    }
755
756    /// Move/rename a file.
757    pub async fn move_file(&self, src: &PathBuf, dst: &PathBuf) -> OperationResult {
758        let resolved_src = match self.resolve_path(src) {
759            Ok(p) => p,
760            Err(e) => return self.fail_and_store("move", src.clone(), e).await,
761        };
762        let resolved_dst = match self.resolve_path(dst) {
763            Ok(p) => p,
764            Err(e) => return self.fail_and_store("move", src.clone(), e).await,
765        };
766        debug!("ops::move {:?} -> {:?}", resolved_src, resolved_dst);
767
768        if !resolved_src.exists() {
769            return OperationResult::failure("move", src.clone(), "Source file not found".into());
770        }
771
772        if resolved_dst.exists() {
773            return OperationResult::failure(
774                "move",
775                src.clone(),
776                "Destination already exists".into(),
777            );
778        }
779
780        // Ensure parent directory exists
781        if let Some(parent) = resolved_dst.parent()
782            && !parent.exists()
783            && let Err(e) = fs::create_dir_all(parent)
784        {
785            return OperationResult::failure(
786                "move",
787                src.clone(),
788                format!("Failed to create parent directory: {e}"),
789            );
790        }
791
792        // Move the file
793        match fs::rename(&resolved_src, &resolved_dst) {
794            Ok(()) => {
795                info!("Moved: {:?} -> {:?}", resolved_src, resolved_dst);
796                self.update_store_path(&resolved_src, &resolved_dst).await;
797
798                let undo_id = self.log_to_history(
799                    HistoryOperation::Move {
800                        src: resolved_src.clone(),
801                        dst: resolved_dst.clone(),
802                    },
803                    Some(UndoData::Move {
804                        src: resolved_src,
805                        dst: resolved_dst,
806                    }),
807                );
808
809                let mut result = OperationResult::success("move", dst.clone(), true);
810                result.undo_id = undo_id;
811                *self.last_result.write().await = Some(result.clone());
812                result
813            }
814            Err(e) => {
815                let error_msg = format!("Failed to move file: {e}");
816                self.log_failure_to_history(
817                    HistoryOperation::Move {
818                        src: resolved_src,
819                        dst: resolved_dst,
820                    },
821                    &error_msg,
822                );
823
824                let result = OperationResult::failure("move", src.clone(), error_msg);
825                *self.last_result.write().await = Some(result.clone());
826                result
827            }
828        }
829    }
830
831    /// Copy a file.
832    pub async fn copy(&self, src: &PathBuf, dst: &PathBuf) -> OperationResult {
833        let resolved_src = match self.resolve_path(src) {
834            Ok(p) => p,
835            Err(e) => return self.fail_and_store("copy", src.clone(), e).await,
836        };
837        let resolved_dst = match self.resolve_path(dst) {
838            Ok(p) => p,
839            Err(e) => return self.fail_and_store("copy", src.clone(), e).await,
840        };
841        debug!("ops::copy {:?} -> {:?}", resolved_src, resolved_dst);
842
843        if !resolved_src.exists() {
844            return OperationResult::failure("copy", src.clone(), "Source file not found".into());
845        }
846
847        if resolved_dst.exists() {
848            return OperationResult::failure(
849                "copy",
850                src.clone(),
851                "Destination already exists".into(),
852            );
853        }
854
855        // Ensure parent directory exists
856        if let Some(parent) = resolved_dst.parent()
857            && !parent.exists()
858            && let Err(e) = fs::create_dir_all(parent)
859        {
860            return OperationResult::failure(
861                "copy",
862                src.clone(),
863                format!("Failed to create parent directory: {e}"),
864            );
865        }
866
867        // Copy the file
868        match fs::copy(&resolved_src, &resolved_dst) {
869            Ok(_) => {
870                info!("Copied: {:?} -> {:?}", resolved_src, resolved_dst);
871                let indexed = self.trigger_reindex(&resolved_dst).await;
872
873                let undo_id = self.log_to_history(
874                    HistoryOperation::Copy {
875                        src: resolved_src,
876                        dst: resolved_dst.clone(),
877                    },
878                    Some(UndoData::Copy { path: resolved_dst }),
879                );
880
881                let mut result = OperationResult::success("copy", dst.clone(), indexed);
882                result.undo_id = undo_id;
883                *self.last_result.write().await = Some(result.clone());
884                result
885            }
886            Err(e) => {
887                let error_msg = format!("Failed to copy file: {e}");
888                self.log_failure_to_history(
889                    HistoryOperation::Copy {
890                        src: resolved_src,
891                        dst: resolved_dst,
892                    },
893                    &error_msg,
894                );
895
896                let result = OperationResult::failure("copy", src.clone(), error_msg);
897                *self.last_result.write().await = Some(result.clone());
898                result
899            }
900        }
901    }
902
903    /// Write content to a file.
904    pub async fn write(&self, path: &PathBuf, content: &str, append: bool) -> OperationResult {
905        let resolved = match self.resolve_path(path) {
906            Ok(p) => p,
907            Err(e) => return self.fail_and_store("write", path.clone(), e).await,
908        };
909        debug!("ops::write {:?} (append={})", resolved, append);
910
911        let write_result = if append {
912            use std::io::Write;
913            fs::OpenOptions::new()
914                .create(true)
915                .append(true)
916                .open(&resolved)
917                .and_then(|mut f| f.write_all(content.as_bytes()))
918        } else {
919            fs::write(&resolved, content)
920        };
921
922        match write_result {
923            Ok(()) => {
924                info!("Wrote to file: {:?}", resolved);
925                let indexed = self.trigger_reindex(&resolved).await;
926
927                let undo_id = self.log_to_history(
928                    HistoryOperation::Write {
929                        path: resolved,
930                        append,
931                    },
932                    None, // No undo data - would need to store previous content
933                );
934
935                let mut result = OperationResult::success("write", path.clone(), indexed);
936                result.undo_id = undo_id;
937                *self.last_result.write().await = Some(result.clone());
938                result
939            }
940            Err(e) => {
941                let error_msg = format!("Failed to write file: {e}");
942                self.log_failure_to_history(
943                    HistoryOperation::Write {
944                        path: resolved,
945                        append,
946                    },
947                    &error_msg,
948                );
949
950                let result = OperationResult::failure("write", path.clone(), error_msg);
951                *self.last_result.write().await = Some(result.clone());
952                result
953            }
954        }
955    }
956
957    /// Create a directory.
958    pub async fn mkdir(&self, path: &PathBuf) -> OperationResult {
959        let resolved = match self.resolve_path(path) {
960            Ok(p) => p,
961            Err(e) => return self.fail_and_store("mkdir", path.clone(), e).await,
962        };
963        debug!("ops::mkdir {:?}", resolved);
964
965        if resolved.exists() {
966            return OperationResult::failure("mkdir", path.clone(), "Path already exists".into());
967        }
968
969        match fs::create_dir_all(&resolved) {
970            Ok(()) => {
971                info!("Created directory: {:?}", resolved);
972
973                // Note: Directories are not indexed; no HistoryOperation for mkdir.
974                let result = OperationResult::success("mkdir", path.clone(), false);
975
976                *self.last_result.write().await = Some(result.clone());
977                result
978            }
979            Err(e) => {
980                let error_msg = format!("Failed to create directory: {e}");
981                let result = OperationResult::failure("mkdir", path.clone(), error_msg);
982                *self.last_result.write().await = Some(result.clone());
983                result
984            }
985        }
986    }
987
988    /// Create a symbolic link.
989    #[cfg(unix)]
990    pub async fn symlink(&self, target: &PathBuf, link: &PathBuf) -> OperationResult {
991        let resolved_link = match self.resolve_path(link) {
992            Ok(p) => p,
993            Err(e) => return self.fail_and_store("symlink", link.clone(), e).await,
994        };
995        if let Err(e) = self.jail_symlink_target(target, &resolved_link) {
996            return self.fail_and_store("symlink", link.clone(), e).await;
997        }
998        debug!("ops::symlink {:?} -> {:?}", resolved_link, target);
999
1000        if resolved_link.exists() {
1001            return OperationResult::failure(
1002                "symlink",
1003                link.clone(),
1004                "Link path already exists".into(),
1005            );
1006        }
1007
1008        // Ensure parent directory exists
1009        if let Some(parent) = resolved_link.parent()
1010            && !parent.exists()
1011            && let Err(e) = fs::create_dir_all(parent)
1012        {
1013            return OperationResult::failure(
1014                "symlink",
1015                link.clone(),
1016                format!("Failed to create parent directory: {e}"),
1017            );
1018        }
1019
1020        // Pass the original target so a relative link stays relative.
1021        match std::os::unix::fs::symlink(target, &resolved_link) {
1022            Ok(()) => {
1023                info!("Created symlink: {:?} -> {:?}", resolved_link, target);
1024
1025                let result = OperationResult::success("symlink", link.clone(), false);
1026
1027                *self.last_result.write().await = Some(result.clone());
1028                result
1029            }
1030            Err(e) => {
1031                let error_msg = format!("Failed to create symlink: {e}");
1032                let result = OperationResult::failure("symlink", link.clone(), error_msg);
1033                *self.last_result.write().await = Some(result.clone());
1034                result
1035            }
1036        }
1037    }
1038
1039    /// Create a symbolic link (non-Unix fallback - not supported).
1040    #[cfg(not(unix))]
1041    pub async fn symlink(&self, _target: &PathBuf, link: &PathBuf) -> OperationResult {
1042        OperationResult::failure(
1043            "symlink",
1044            link.clone(),
1045            "Symlinks are not supported on this platform".into(),
1046        )
1047    }
1048
1049    /// Execute a single operation.
1050    pub async fn execute_operation(&self, op: &Operation) -> OperationResult {
1051        match op {
1052            Operation::Create { path, content } => self.create(path, content).await,
1053            Operation::Delete { path } => self.delete(path).await,
1054            Operation::Move { src, dst } => self.move_file(src, dst).await,
1055            Operation::Copy { src, dst } => self.copy(src, dst).await,
1056            Operation::Write {
1057                path,
1058                content,
1059                append,
1060            } => self.write(path, content, *append).await,
1061            Operation::Mkdir { path } => self.mkdir(path).await,
1062            Operation::Symlink { target, link } => self.symlink(target, link).await,
1063        }
1064    }
1065
1066    /// Execute a batch of operations.
1067    pub async fn batch(&self, request: BatchRequest) -> BatchResult {
1068        let batch_id = Uuid::new_v4();
1069        let total = request.operations.len();
1070        let mut results = Vec::with_capacity(total);
1071        let mut succeeded = 0;
1072        let mut failed = 0;
1073        let mut journal: Vec<JournalEntry> = Vec::new();
1074
1075        debug!(
1076            "ops::batch {} operations (atomic={}, dry_run={})",
1077            total, request.atomic, request.dry_run
1078        );
1079
1080        if request.dry_run {
1081            // Just validate operations without executing
1082            for op in &request.operations {
1083                let result = self.validate_operation(op);
1084                if result.success {
1085                    succeeded += 1;
1086                } else {
1087                    failed += 1;
1088                }
1089                results.push(result);
1090            }
1091
1092            let batch_result = BatchResult {
1093                id: batch_id,
1094                success: failed == 0,
1095                total,
1096                succeeded,
1097                failed,
1098                results,
1099                timestamp: Utc::now(),
1100                rollback_performed: None,
1101                rollback_details: None,
1102            };
1103
1104            *self.last_batch_result.write().await = Some(batch_result.clone());
1105            return batch_result;
1106        }
1107
1108        // Execute operations with journal for atomic rollback
1109        for (index, op) in request.operations.iter().enumerate() {
1110            let (result, rollback_data) = self.execute_with_rollback(op).await;
1111
1112            if result.success {
1113                succeeded += 1;
1114                // Record in journal for potential rollback
1115                if request.atomic
1116                    && let Some(rd) = rollback_data
1117                {
1118                    journal.push(JournalEntry {
1119                        operation_index: index,
1120                        rollback_data: rd,
1121                    });
1122                }
1123                results.push(result);
1124            } else {
1125                failed += 1;
1126                results.push(result);
1127
1128                if request.atomic && !journal.is_empty() {
1129                    // Perform rollback of all previously successful operations
1130                    info!(
1131                        "Batch failed at operation {}, rolling back {} operations",
1132                        index,
1133                        journal.len()
1134                    );
1135                    let rollback_details = self.perform_rollback(&journal).await;
1136                    let rollback_success = rollback_details.rollback_failures == 0;
1137
1138                    let batch_result = BatchResult {
1139                        id: batch_id,
1140                        success: false,
1141                        total,
1142                        succeeded,
1143                        failed,
1144                        results,
1145                        timestamp: Utc::now(),
1146                        rollback_performed: Some(rollback_success),
1147                        rollback_details: Some(rollback_details),
1148                    };
1149
1150                    *self.last_batch_result.write().await = Some(batch_result.clone());
1151                    return batch_result;
1152                } else if request.atomic {
1153                    // First operation failed, no rollback needed
1154                    let batch_result = BatchResult {
1155                        id: batch_id,
1156                        success: false,
1157                        total,
1158                        succeeded,
1159                        failed,
1160                        results,
1161                        timestamp: Utc::now(),
1162                        rollback_performed: None,
1163                        rollback_details: None,
1164                    };
1165
1166                    *self.last_batch_result.write().await = Some(batch_result.clone());
1167                    return batch_result;
1168                }
1169                // Non-atomic: continue with next operation
1170            }
1171        }
1172
1173        let batch_result = BatchResult {
1174            id: batch_id,
1175            success: failed == 0,
1176            total,
1177            succeeded,
1178            failed,
1179            results,
1180            timestamp: Utc::now(),
1181            rollback_performed: None,
1182            rollback_details: None,
1183        };
1184
1185        *self.last_batch_result.write().await = Some(batch_result.clone());
1186        batch_result
1187    }
1188
1189    /// Validate an operation without executing it.
1190    fn validate_operation(&self, op: &Operation) -> OperationResult {
1191        match op {
1192            Operation::Create { path, .. } => {
1193                let resolved = match self.resolve_path(path) {
1194                    Ok(p) => p,
1195                    Err(e) => return OperationResult::failure("create", path.clone(), e),
1196                };
1197                if resolved.exists() {
1198                    OperationResult::failure("create", path.clone(), "File already exists".into())
1199                } else {
1200                    OperationResult::success("create", path.clone(), false)
1201                }
1202            }
1203            Operation::Delete { path } => {
1204                let resolved = match self.resolve_path(path) {
1205                    Ok(p) => p,
1206                    Err(e) => return OperationResult::failure("delete", path.clone(), e),
1207                };
1208                if !resolved.exists() {
1209                    OperationResult::failure("delete", path.clone(), "File not found".into())
1210                } else if resolved.is_dir() {
1211                    OperationResult::failure(
1212                        "delete",
1213                        path.clone(),
1214                        "Cannot delete directory".into(),
1215                    )
1216                } else {
1217                    OperationResult::success("delete", path.clone(), false)
1218                }
1219            }
1220            Operation::Move { src, dst } => {
1221                let resolved_src = match self.resolve_path(src) {
1222                    Ok(p) => p,
1223                    Err(e) => return OperationResult::failure("move", src.clone(), e),
1224                };
1225                let resolved_dst = match self.resolve_path(dst) {
1226                    Ok(p) => p,
1227                    Err(e) => return OperationResult::failure("move", src.clone(), e),
1228                };
1229                if !resolved_src.exists() {
1230                    OperationResult::failure("move", src.clone(), "Source not found".into())
1231                } else if resolved_dst.exists() {
1232                    OperationResult::failure(
1233                        "move",
1234                        src.clone(),
1235                        "Destination already exists".into(),
1236                    )
1237                } else {
1238                    OperationResult::success("move", dst.clone(), false)
1239                }
1240            }
1241            Operation::Copy { src, dst } => {
1242                let resolved_src = match self.resolve_path(src) {
1243                    Ok(p) => p,
1244                    Err(e) => return OperationResult::failure("copy", src.clone(), e),
1245                };
1246                let resolved_dst = match self.resolve_path(dst) {
1247                    Ok(p) => p,
1248                    Err(e) => return OperationResult::failure("copy", src.clone(), e),
1249                };
1250                if !resolved_src.exists() {
1251                    OperationResult::failure("copy", src.clone(), "Source not found".into())
1252                } else if resolved_dst.exists() {
1253                    OperationResult::failure(
1254                        "copy",
1255                        src.clone(),
1256                        "Destination already exists".into(),
1257                    )
1258                } else {
1259                    OperationResult::success("copy", dst.clone(), false)
1260                }
1261            }
1262            Operation::Write { path, .. } => match self.resolve_path(path) {
1263                Ok(_) => OperationResult::success("write", path.clone(), false),
1264                Err(e) => OperationResult::failure("write", path.clone(), e),
1265            },
1266            Operation::Mkdir { path } => {
1267                let resolved = match self.resolve_path(path) {
1268                    Ok(p) => p,
1269                    Err(e) => return OperationResult::failure("mkdir", path.clone(), e),
1270                };
1271                if resolved.exists() {
1272                    OperationResult::failure("mkdir", path.clone(), "Path already exists".into())
1273                } else {
1274                    OperationResult::success("mkdir", path.clone(), false)
1275                }
1276            }
1277            Operation::Symlink { target, link } => {
1278                let resolved_link = match self.resolve_path(link) {
1279                    Ok(p) => p,
1280                    Err(e) => return OperationResult::failure("symlink", link.clone(), e),
1281                };
1282                if let Err(e) = self.jail_symlink_target(target, &resolved_link) {
1283                    return OperationResult::failure("symlink", link.clone(), e);
1284                }
1285                if resolved_link.exists() {
1286                    OperationResult::failure(
1287                        "symlink",
1288                        link.clone(),
1289                        "Link path already exists".into(),
1290                    )
1291                } else {
1292                    OperationResult::success("symlink", link.clone(), false)
1293                }
1294            }
1295        }
1296    }
1297
1298    /// Get the last operation result as JSON.
1299    pub async fn get_last_result(&self) -> Vec<u8> {
1300        let result = self.last_result.read().await;
1301        if let Some(r) = &*result {
1302            serde_json::to_string_pretty(r)
1303                .unwrap_or_else(|_| "{}".to_string())
1304                .into_bytes()
1305        } else {
1306            let empty = serde_json::json!({
1307                "message": "No operations performed yet"
1308            });
1309            serde_json::to_string_pretty(&empty)
1310                .unwrap_or_default()
1311                .into_bytes()
1312        }
1313    }
1314
1315    /// Get the last batch result as JSON.
1316    #[allow(dead_code)]
1317    pub async fn get_last_batch_result(&self) -> Vec<u8> {
1318        let result = self.last_batch_result.read().await;
1319        if let Some(r) = &*result {
1320            serde_json::to_string_pretty(r)
1321                .unwrap_or_else(|_| "{}".to_string())
1322                .into_bytes()
1323        } else {
1324            let empty = serde_json::json!({
1325                "message": "No batch operations performed yet"
1326            });
1327            serde_json::to_string_pretty(&empty)
1328                .unwrap_or_default()
1329                .into_bytes()
1330        }
1331    }
1332
1333    /// Parse and execute a create operation from string input.
1334    /// Format: "path\ncontent"
1335    pub async fn parse_and_create(&self, input: &str) -> OperationResult {
1336        let parts: Vec<&str> = input.splitn(2, '\n').collect();
1337        if parts.len() < 2 {
1338            return OperationResult::failure(
1339                "create",
1340                PathBuf::new(),
1341                "Invalid format. Expected: path\\ncontent".into(),
1342            );
1343        }
1344        let path = PathBuf::from(parts[0].trim());
1345        let content = parts[1];
1346        self.create(&path, content).await
1347    }
1348
1349    /// Parse and execute a delete operation from string input.
1350    /// Format: "path"
1351    pub async fn parse_and_delete(&self, input: &str) -> OperationResult {
1352        let path = PathBuf::from(input.trim());
1353        if path.as_os_str().is_empty() {
1354            return OperationResult::failure(
1355                "delete",
1356                PathBuf::new(),
1357                "Invalid format. Expected: path".into(),
1358            );
1359        }
1360        self.delete(&path).await
1361    }
1362
1363    /// Parse and execute a move operation from string input.
1364    /// Format: "src\ndst"
1365    pub async fn parse_and_move(&self, input: &str) -> OperationResult {
1366        let parts: Vec<&str> = input.splitn(2, '\n').collect();
1367        if parts.len() < 2 {
1368            return OperationResult::failure(
1369                "move",
1370                PathBuf::new(),
1371                "Invalid format. Expected: src\\ndst".into(),
1372            );
1373        }
1374        let src = PathBuf::from(parts[0].trim());
1375        let dst = PathBuf::from(parts[1].trim());
1376        self.move_file(&src, &dst).await
1377    }
1378
1379    /// Parse and execute a batch operation from JSON input.
1380    pub async fn parse_and_batch(&self, input: &str) -> BatchResult {
1381        match serde_json::from_str::<BatchRequest>(input) {
1382            Ok(request) => self.batch(request).await,
1383            Err(e) => BatchResult {
1384                id: Uuid::new_v4(),
1385                success: false,
1386                total: 0,
1387                succeeded: 0,
1388                failed: 1,
1389                results: vec![OperationResult::failure(
1390                    "batch",
1391                    PathBuf::new(),
1392                    format!("Invalid JSON: {e}"),
1393                )],
1394                timestamp: Utc::now(),
1395                rollback_performed: None,
1396                rollback_details: None,
1397            },
1398        }
1399    }
1400}
1401
1402#[cfg(test)]
1403mod tests {
1404    use super::*;
1405    use tempfile::TempDir;
1406
1407    fn create_test_manager() -> (OpsManager, TempDir) {
1408        let temp_dir = TempDir::new().unwrap();
1409        let manager = OpsManager::new(temp_dir.path().to_path_buf(), None, None);
1410        (manager, temp_dir)
1411    }
1412
1413    #[tokio::test]
1414    async fn test_create_file() {
1415        let (manager, _temp) = create_test_manager();
1416        let path = PathBuf::from("test.txt");
1417
1418        let result = manager.create(&path, "Hello, World!").await;
1419
1420        assert!(result.success);
1421        assert_eq!(result.operation, "create");
1422        assert!(manager.resolve_path(&path).unwrap().exists());
1423    }
1424
1425    #[tokio::test]
1426    async fn test_create_file_already_exists() {
1427        let (manager, temp) = create_test_manager();
1428        let path = PathBuf::from("existing.txt");
1429        fs::write(temp.path().join("existing.txt"), "content").unwrap();
1430
1431        let result = manager.create(&path, "new content").await;
1432
1433        assert!(!result.success);
1434        assert!(result.error.unwrap().contains("already exists"));
1435    }
1436
1437    #[tokio::test]
1438    async fn test_delete_file() {
1439        let (manager, temp) = create_test_manager();
1440        let path = PathBuf::from("to_delete.txt");
1441        fs::write(temp.path().join("to_delete.txt"), "content").unwrap();
1442
1443        let result = manager.delete(&path).await;
1444
1445        assert!(result.success);
1446        assert!(!manager.resolve_path(&path).unwrap().exists());
1447    }
1448
1449    #[tokio::test]
1450    async fn test_delete_nonexistent() {
1451        let (manager, _temp) = create_test_manager();
1452        let path = PathBuf::from("nonexistent.txt");
1453
1454        let result = manager.delete(&path).await;
1455
1456        assert!(!result.success);
1457        assert!(result.error.unwrap().contains("not found"));
1458    }
1459
1460    #[tokio::test]
1461    async fn test_move_file() {
1462        let (manager, temp) = create_test_manager();
1463        let src = PathBuf::from("source.txt");
1464        let dst = PathBuf::from("dest.txt");
1465        fs::write(temp.path().join("source.txt"), "content").unwrap();
1466
1467        let result = manager.move_file(&src, &dst).await;
1468
1469        assert!(result.success);
1470        assert!(!manager.resolve_path(&src).unwrap().exists());
1471        assert!(manager.resolve_path(&dst).unwrap().exists());
1472    }
1473
1474    #[tokio::test]
1475    async fn test_copy_file() {
1476        let (manager, temp) = create_test_manager();
1477        let src = PathBuf::from("original.txt");
1478        let dst = PathBuf::from("copy.txt");
1479        fs::write(temp.path().join("original.txt"), "content").unwrap();
1480
1481        let result = manager.copy(&src, &dst).await;
1482
1483        assert!(result.success);
1484        assert!(manager.resolve_path(&src).unwrap().exists());
1485        assert!(manager.resolve_path(&dst).unwrap().exists());
1486    }
1487
1488    #[tokio::test]
1489    async fn test_write_file() {
1490        let (manager, _temp) = create_test_manager();
1491        let path = PathBuf::from("write_test.txt");
1492
1493        let result = manager.write(&path, "content", false).await;
1494
1495        assert!(result.success);
1496        let content = fs::read_to_string(manager.resolve_path(&path).unwrap()).unwrap();
1497        assert_eq!(content, "content");
1498    }
1499
1500    #[tokio::test]
1501    async fn test_write_append() {
1502        let (manager, temp) = create_test_manager();
1503        let path = PathBuf::from("append_test.txt");
1504        fs::write(temp.path().join("append_test.txt"), "first").unwrap();
1505
1506        let result = manager.write(&path, " second", true).await;
1507
1508        assert!(result.success);
1509        let content = fs::read_to_string(manager.resolve_path(&path).unwrap()).unwrap();
1510        assert_eq!(content, "first second");
1511    }
1512
1513    #[tokio::test]
1514    async fn test_batch_operations() {
1515        let (manager, _temp) = create_test_manager();
1516
1517        let request = BatchRequest {
1518            operations: vec![
1519                Operation::Create {
1520                    path: PathBuf::from("file1.txt"),
1521                    content: "content1".to_string(),
1522                },
1523                Operation::Create {
1524                    path: PathBuf::from("file2.txt"),
1525                    content: "content2".to_string(),
1526                },
1527            ],
1528            atomic: false,
1529            dry_run: false,
1530        };
1531
1532        let result = manager.batch(request).await;
1533
1534        assert!(result.success);
1535        assert_eq!(result.total, 2);
1536        assert_eq!(result.succeeded, 2);
1537        assert_eq!(result.failed, 0);
1538    }
1539
1540    #[tokio::test]
1541    async fn test_batch_dry_run() {
1542        let (manager, _temp) = create_test_manager();
1543
1544        let request = BatchRequest {
1545            operations: vec![Operation::Create {
1546                path: PathBuf::from("dry_run.txt"),
1547                content: "content".to_string(),
1548            }],
1549            atomic: false,
1550            dry_run: true,
1551        };
1552
1553        let result = manager.batch(request).await;
1554
1555        assert!(result.success);
1556        // File should NOT be created in dry run
1557        assert!(
1558            !manager
1559                .resolve_path(&PathBuf::from("dry_run.txt"))
1560                .unwrap()
1561                .exists()
1562        );
1563    }
1564
1565    #[tokio::test]
1566    async fn test_parse_and_create() {
1567        let (manager, _temp) = create_test_manager();
1568
1569        let result = manager.parse_and_create("test.txt\nHello!").await;
1570
1571        assert!(result.success);
1572        let content =
1573            fs::read_to_string(manager.resolve_path(&PathBuf::from("test.txt")).unwrap()).unwrap();
1574        assert_eq!(content, "Hello!");
1575    }
1576
1577    #[tokio::test]
1578    async fn test_parse_and_move() {
1579        let (manager, temp) = create_test_manager();
1580        fs::write(temp.path().join("src.txt"), "content").unwrap();
1581
1582        let result = manager.parse_and_move("src.txt\ndst.txt").await;
1583
1584        assert!(result.success);
1585    }
1586
1587    #[tokio::test]
1588    async fn test_parse_and_batch() {
1589        let (manager, _temp) = create_test_manager();
1590
1591        let json = r#"{"operations":[{"op":"create","path":"batch.txt","content":"test"}]}"#;
1592        let result = manager.parse_and_batch(json).await;
1593
1594        assert!(result.success);
1595    }
1596
1597    #[tokio::test]
1598    async fn test_last_result() {
1599        let (manager, _temp) = create_test_manager();
1600
1601        // Initially no result
1602        let initial = manager.get_last_result().await;
1603        let initial_str = String::from_utf8(initial).unwrap();
1604        assert!(initial_str.contains("No operations"));
1605
1606        // After an operation
1607        manager.create(&PathBuf::from("test.txt"), "content").await;
1608        let after = manager.get_last_result().await;
1609        let after_str = String::from_utf8(after).unwrap();
1610        assert!(after_str.contains("create"));
1611        assert!(after_str.contains("success"));
1612    }
1613
1614    #[test]
1615    fn test_operation_result_success() {
1616        let result = OperationResult::success("test", PathBuf::from("/test"), true);
1617        assert!(result.success);
1618        assert!(result.error.is_none());
1619        assert!(
1620            result.undo_id.is_none(),
1621            "undo_id is assigned from SafetyManager history, not generated here"
1622        );
1623    }
1624
1625    #[test]
1626    fn test_operation_result_failure() {
1627        let result = OperationResult::failure("test", PathBuf::from("/test"), "error".into());
1628        assert!(!result.success);
1629        assert!(result.error.is_some());
1630        assert!(result.undo_id.is_none());
1631    }
1632
1633    #[tokio::test]
1634    async fn test_atomic_batch_rollback_on_failure() {
1635        let (manager, temp) = create_test_manager();
1636
1637        // Create a file that will cause the second create to fail
1638        fs::write(temp.path().join("existing.txt"), "exists").unwrap();
1639
1640        let request = BatchRequest {
1641            operations: vec![
1642                Operation::Create {
1643                    path: PathBuf::from("new.txt"),
1644                    content: "content".to_string(),
1645                },
1646                Operation::Create {
1647                    path: PathBuf::from("existing.txt"), // Will fail
1648                    content: "content".to_string(),
1649                },
1650            ],
1651            atomic: true,
1652            dry_run: false,
1653        };
1654
1655        let result = manager.batch(request).await;
1656
1657        assert!(!result.success);
1658        assert_eq!(result.succeeded, 1);
1659        assert_eq!(result.failed, 1);
1660        assert_eq!(result.rollback_performed, Some(true));
1661        assert!(result.rollback_details.is_some());
1662        let details = result.rollback_details.unwrap();
1663        assert_eq!(details.rolled_back, 1);
1664        assert_eq!(details.rollback_failures, 0);
1665        // First file should be rolled back (deleted)
1666        assert!(!temp.path().join("new.txt").exists());
1667    }
1668
1669    #[tokio::test]
1670    async fn test_atomic_batch_rollback_move_operations() {
1671        let (manager, temp) = create_test_manager();
1672
1673        fs::write(temp.path().join("file1.txt"), "content1").unwrap();
1674
1675        let request = BatchRequest {
1676            operations: vec![
1677                Operation::Move {
1678                    src: PathBuf::from("file1.txt"),
1679                    dst: PathBuf::from("moved1.txt"),
1680                },
1681                Operation::Delete {
1682                    path: PathBuf::from("nonexistent.txt"), // Will fail
1683                },
1684            ],
1685            atomic: true,
1686            dry_run: false,
1687        };
1688
1689        let result = manager.batch(request).await;
1690
1691        assert!(!result.success);
1692        assert_eq!(result.rollback_performed, Some(true));
1693        // Move should be rolled back
1694        assert!(temp.path().join("file1.txt").exists());
1695        assert!(!temp.path().join("moved1.txt").exists());
1696    }
1697
1698    #[tokio::test]
1699    async fn test_atomic_batch_rollback_write_restores_content() {
1700        let (manager, temp) = create_test_manager();
1701
1702        fs::write(temp.path().join("existing.txt"), "original content").unwrap();
1703
1704        let request = BatchRequest {
1705            operations: vec![
1706                Operation::Write {
1707                    path: PathBuf::from("existing.txt"),
1708                    content: "modified content".to_string(),
1709                    append: false,
1710                },
1711                Operation::Delete {
1712                    path: PathBuf::from("nonexistent.txt"), // Will fail
1713                },
1714            ],
1715            atomic: true,
1716            dry_run: false,
1717        };
1718
1719        let result = manager.batch(request).await;
1720
1721        assert!(!result.success);
1722        assert_eq!(result.rollback_performed, Some(true));
1723        // Content should be restored
1724        let content = fs::read_to_string(temp.path().join("existing.txt")).unwrap();
1725        assert_eq!(content, "original content");
1726    }
1727
1728    #[tokio::test]
1729    async fn test_non_atomic_batch_no_rollback() {
1730        let (manager, temp) = create_test_manager();
1731
1732        let request = BatchRequest {
1733            operations: vec![
1734                Operation::Create {
1735                    path: PathBuf::from("file1.txt"),
1736                    content: "content".to_string(),
1737                },
1738                Operation::Delete {
1739                    path: PathBuf::from("nonexistent.txt"), // Will fail
1740                },
1741                Operation::Create {
1742                    path: PathBuf::from("file2.txt"),
1743                    content: "content".to_string(),
1744                },
1745            ],
1746            atomic: false, // Non-atomic
1747            dry_run: false,
1748        };
1749
1750        let result = manager.batch(request).await;
1751
1752        assert!(!result.success);
1753        assert!(result.rollback_performed.is_none());
1754        // Both files should exist (no rollback)
1755        assert!(temp.path().join("file1.txt").exists());
1756        assert!(temp.path().join("file2.txt").exists());
1757    }
1758
1759    #[tokio::test]
1760    async fn test_atomic_batch_first_op_fails_no_rollback_needed() {
1761        let (manager, temp) = create_test_manager();
1762
1763        // Create a file that will cause the first create to fail
1764        fs::write(temp.path().join("existing.txt"), "exists").unwrap();
1765
1766        let request = BatchRequest {
1767            operations: vec![
1768                Operation::Create {
1769                    path: PathBuf::from("existing.txt"), // Will fail immediately
1770                    content: "content".to_string(),
1771                },
1772                Operation::Create {
1773                    path: PathBuf::from("new.txt"),
1774                    content: "content".to_string(),
1775                },
1776            ],
1777            atomic: true,
1778            dry_run: false,
1779        };
1780
1781        let result = manager.batch(request).await;
1782
1783        assert!(!result.success);
1784        assert_eq!(result.succeeded, 0);
1785        assert_eq!(result.failed, 1);
1786        // No rollback needed since first operation failed
1787        assert!(result.rollback_performed.is_none());
1788        assert!(result.rollback_details.is_none());
1789        // Second operation should not have been attempted
1790        assert!(!temp.path().join("new.txt").exists());
1791    }
1792
1793    #[tokio::test]
1794    async fn test_atomic_batch_copy_rollback() {
1795        let (manager, temp) = create_test_manager();
1796
1797        fs::write(temp.path().join("source.txt"), "source content").unwrap();
1798
1799        let request = BatchRequest {
1800            operations: vec![
1801                Operation::Copy {
1802                    src: PathBuf::from("source.txt"),
1803                    dst: PathBuf::from("copied.txt"),
1804                },
1805                Operation::Delete {
1806                    path: PathBuf::from("nonexistent.txt"), // Will fail
1807                },
1808            ],
1809            atomic: true,
1810            dry_run: false,
1811        };
1812
1813        let result = manager.batch(request).await;
1814
1815        assert!(!result.success);
1816        assert_eq!(result.rollback_performed, Some(true));
1817        // Copy should be rolled back (deleted)
1818        assert!(temp.path().join("source.txt").exists());
1819        assert!(!temp.path().join("copied.txt").exists());
1820    }
1821
1822    #[tokio::test]
1823    async fn test_mkdir() {
1824        let (manager, temp) = create_test_manager();
1825        let path = PathBuf::from("new_directory");
1826
1827        let result = manager.mkdir(&path).await;
1828
1829        assert!(result.success);
1830        assert_eq!(result.operation, "mkdir");
1831        assert!(temp.path().join("new_directory").is_dir());
1832    }
1833
1834    #[tokio::test]
1835    async fn test_mkdir_nested() {
1836        let (manager, temp) = create_test_manager();
1837        let path = PathBuf::from("parent/child/grandchild");
1838
1839        let result = manager.mkdir(&path).await;
1840
1841        assert!(result.success);
1842        assert!(temp.path().join("parent/child/grandchild").is_dir());
1843    }
1844
1845    #[tokio::test]
1846    async fn test_mkdir_already_exists() {
1847        let (manager, temp) = create_test_manager();
1848        let path = PathBuf::from("existing_dir");
1849        fs::create_dir(temp.path().join("existing_dir")).unwrap();
1850
1851        let result = manager.mkdir(&path).await;
1852
1853        assert!(!result.success);
1854        assert!(result.error.unwrap().contains("already exists"));
1855    }
1856
1857    #[tokio::test]
1858    #[cfg(unix)]
1859    async fn test_symlink() {
1860        let (manager, temp) = create_test_manager();
1861        let target = PathBuf::from("target_file.txt");
1862        let link = PathBuf::from("link_to_target");
1863
1864        // Create target file
1865        fs::write(temp.path().join("target_file.txt"), "content").unwrap();
1866
1867        let result = manager.symlink(&target, &link).await;
1868
1869        assert!(result.success);
1870        assert_eq!(result.operation, "symlink");
1871        let link_path = temp.path().join("link_to_target");
1872        assert!(link_path.symlink_metadata().is_ok());
1873        assert_eq!(
1874            std::fs::read_link(&link_path).unwrap(),
1875            PathBuf::from("target_file.txt")
1876        );
1877    }
1878
1879    #[tokio::test]
1880    #[cfg(unix)]
1881    async fn test_symlink_relative_target_from_link_parent() {
1882        let (manager, temp) = create_test_manager();
1883        fs::create_dir(temp.path().join("sub")).unwrap();
1884        fs::write(temp.path().join("ok.txt"), "ok").unwrap();
1885
1886        let target = PathBuf::from("../ok.txt");
1887        let link = PathBuf::from("sub/link");
1888        let result = manager.symlink(&target, &link).await;
1889
1890        assert!(result.success, "{:?}", result.error);
1891        assert_eq!(
1892            std::fs::read_link(temp.path().join("sub/link")).unwrap(),
1893            PathBuf::from("../ok.txt")
1894        );
1895    }
1896
1897    #[tokio::test]
1898    #[cfg(unix)]
1899    async fn test_symlink_rejects_parent_relative_escape_via_existing_link() {
1900        let (manager, temp) = create_test_manager();
1901        let outside = TempDir::new().unwrap();
1902        fs::create_dir(temp.path().join("sub")).unwrap();
1903        std::os::unix::fs::symlink(outside.path(), temp.path().join("sub/out")).unwrap();
1904
1905        let target = PathBuf::from("out/secret.txt");
1906        let link = PathBuf::from("sub/link");
1907        let result = manager.symlink(&target, &link).await;
1908
1909        assert!(!result.success);
1910        assert!(
1911            result.error.as_ref().unwrap().contains("escapes"),
1912            "{:?}",
1913            result.error
1914        );
1915        assert!(!temp.path().join("sub/link").exists());
1916    }
1917
1918    #[tokio::test]
1919    #[cfg(unix)]
1920    async fn test_symlink_already_exists() {
1921        let (manager, temp) = create_test_manager();
1922        let target = PathBuf::from("target.txt");
1923        let link = PathBuf::from("existing_link");
1924
1925        // Create existing link path
1926        fs::write(temp.path().join("existing_link"), "content").unwrap();
1927
1928        let result = manager.symlink(&target, &link).await;
1929
1930        assert!(!result.success);
1931        assert!(result.error.unwrap().contains("already exists"));
1932    }
1933
1934    #[tokio::test]
1935    async fn test_atomic_batch_mkdir_rollback() {
1936        let (manager, temp) = create_test_manager();
1937
1938        let request = BatchRequest {
1939            operations: vec![
1940                Operation::Mkdir {
1941                    path: PathBuf::from("new_dir"),
1942                },
1943                Operation::Delete {
1944                    path: PathBuf::from("nonexistent.txt"), // Will fail
1945                },
1946            ],
1947            atomic: true,
1948            dry_run: false,
1949        };
1950
1951        let result = manager.batch(request).await;
1952
1953        assert!(!result.success);
1954        assert_eq!(result.rollback_performed, Some(true));
1955        // Directory should be rolled back (removed)
1956        assert!(!temp.path().join("new_dir").exists());
1957    }
1958
1959    fn create_test_manager_with_safety() -> (OpsManager, Arc<SafetyManager>, TempDir, TempDir) {
1960        let source_dir = TempDir::new().unwrap();
1961        let data_dir = TempDir::new().unwrap();
1962        let safety = Arc::new(SafetyManager::new(
1963            &source_dir.path().to_path_buf(),
1964            Some(crate::safety::SafetyConfig {
1965                data_dir: data_dir.path().to_path_buf(),
1966                trash_retention_days: 7,
1967                soft_delete: true,
1968            }),
1969        ));
1970        let manager = OpsManager::with_safety(
1971            source_dir.path().to_path_buf(),
1972            None,
1973            None,
1974            Arc::clone(&safety),
1975        );
1976        (manager, safety, source_dir, data_dir)
1977    }
1978
1979    #[tokio::test]
1980    async fn test_resolve_path_rejects_relative_escape() {
1981        let (manager, _temp) = create_test_manager();
1982        let err = manager
1983            .resolve_path(&PathBuf::from("../escape.txt"))
1984            .unwrap_err();
1985        assert!(err.contains("escapes"), "{err}");
1986    }
1987
1988    #[tokio::test]
1989    async fn test_resolve_path_rejects_absolute_outside_root() {
1990        let (manager, _temp) = create_test_manager();
1991        let outside = TempDir::new().unwrap();
1992        let err = manager
1993            .resolve_path(&outside.path().join("secret.txt"))
1994            .unwrap_err();
1995        assert!(err.contains("escapes"), "{err}");
1996    }
1997
1998    #[tokio::test]
1999    async fn test_create_rejects_path_jail_escape() {
2000        let (manager, temp) = create_test_manager();
2001        let result = manager
2002            .create(&PathBuf::from("../jailbreak.txt"), "nope")
2003            .await;
2004        assert!(!result.success);
2005        assert!(result.error.unwrap().contains("escapes"));
2006        assert!(!temp.path().parent().unwrap().join("jailbreak.txt").exists());
2007    }
2008
2009    #[tokio::test]
2010    async fn test_create_allows_absolute_path_inside_root() {
2011        let (manager, temp) = create_test_manager();
2012        let inside = temp.path().join("inside.txt");
2013        let result = manager.create(&inside, "ok").await;
2014        assert!(result.success);
2015        assert!(inside.exists());
2016    }
2017
2018    #[tokio::test]
2019    #[cfg(unix)]
2020    async fn test_create_rejects_symlink_escape() {
2021        let (manager, temp) = create_test_manager();
2022        let outside = TempDir::new().unwrap();
2023        std::os::unix::fs::symlink(outside.path(), temp.path().join("out")).unwrap();
2024
2025        let result = manager
2026            .create(&PathBuf::from("out/evil.txt"), "pwned")
2027            .await;
2028        assert!(!result.success);
2029        assert!(result.error.unwrap().contains("escapes"));
2030        assert!(!outside.path().join("evil.txt").exists());
2031    }
2032
2033    #[tokio::test]
2034    async fn test_create_undo_id_is_history_id_and_undo_uses_trash() {
2035        let (manager, safety, source_dir, _data) = create_test_manager_with_safety();
2036        let path = PathBuf::from("created.txt");
2037
2038        let result = manager.create(&path, "hello undo").await;
2039        assert!(result.success);
2040        let undo_id = result.undo_id.expect("create must expose history undo_id");
2041
2042        let history = safety.find_operation(undo_id).expect("history entry");
2043        assert_eq!(history.id, undo_id);
2044        assert!(history.reversible);
2045
2046        let file = source_dir.path().join("created.txt");
2047        assert!(file.exists());
2048
2049        let msg = safety.undo(undo_id).await.unwrap();
2050        assert!(msg.contains("trash"), "{msg}");
2051        assert!(!file.exists(), "undo create must not permanently delete");
2052
2053        let trash = safety.list_trash().await;
2054        assert_eq!(trash.len(), 1);
2055        let content = safety.get_trash_content(trash[0].id).unwrap();
2056        assert_eq!(content, b"hello undo");
2057    }
2058
2059    #[tokio::test]
2060    async fn test_delete_undo_id_is_history_id_not_trash_id() {
2061        let (manager, safety, source_dir, _data) = create_test_manager_with_safety();
2062        let path = PathBuf::from("to_soft_delete.txt");
2063        fs::write(source_dir.path().join("to_soft_delete.txt"), "keep me").unwrap();
2064
2065        let result = manager.delete(&path).await;
2066        assert!(result.success);
2067        let undo_id = result.undo_id.expect("delete must expose history undo_id");
2068
2069        let history = safety.find_operation(undo_id).expect("history entry");
2070        assert_eq!(history.id, undo_id);
2071        let trash_id = match history.undo_data {
2072            Some(UndoData::Delete { trash_id }) => trash_id,
2073            other => panic!("expected delete undo data, got {other:?}"),
2074        };
2075        assert_ne!(
2076            undo_id, trash_id,
2077            "undo_id must be the history id, not the trash id"
2078        );
2079        assert!(!source_dir.path().join("to_soft_delete.txt").exists());
2080
2081        safety.undo(undo_id).await.unwrap();
2082        assert!(source_dir.path().join("to_soft_delete.txt").exists());
2083        let content = fs::read_to_string(source_dir.path().join("to_soft_delete.txt")).unwrap();
2084        assert_eq!(content, "keep me");
2085    }
2086
2087    #[tokio::test]
2088    async fn test_delete_does_not_remove_file_when_soft_delete_fails() {
2089        let source_dir = TempDir::new().unwrap();
2090        let jail_dir = TempDir::new().unwrap();
2091        let data_dir = TempDir::new().unwrap();
2092        let safety = Arc::new(SafetyManager::new(
2093            &jail_dir.path().to_path_buf(),
2094            Some(crate::safety::SafetyConfig {
2095                data_dir: data_dir.path().to_path_buf(),
2096                trash_retention_days: 7,
2097                soft_delete: true,
2098            }),
2099        ));
2100        let manager = OpsManager::with_safety(source_dir.path().to_path_buf(), None, None, safety);
2101
2102        let relative = PathBuf::from("keep_me.txt");
2103        let file = source_dir.path().join("keep_me.txt");
2104        fs::write(&file, "must survive").unwrap();
2105
2106        let result = manager.delete(&relative).await;
2107
2108        assert!(!result.success, "{:?}", result.error);
2109        assert!(
2110            result.error.as_ref().unwrap().contains("escapes"),
2111            "{:?}",
2112            result.error
2113        );
2114        assert!(
2115            file.exists(),
2116            "soft-delete failure must not remove the file"
2117        );
2118        assert_eq!(fs::read_to_string(&file).unwrap(), "must survive");
2119    }
2120
2121    #[tokio::test]
2122    async fn test_move_undo_id_is_history_id() {
2123        let (manager, safety, source_dir, _data) = create_test_manager_with_safety();
2124        fs::write(source_dir.path().join("src.txt"), "moved").unwrap();
2125
2126        let result = manager
2127            .move_file(&PathBuf::from("src.txt"), &PathBuf::from("dst.txt"))
2128            .await;
2129        assert!(result.success);
2130        let undo_id = result.undo_id.expect("move must expose history undo_id");
2131        assert_eq!(safety.find_operation(undo_id).unwrap().id, undo_id);
2132
2133        safety.undo(undo_id).await.unwrap();
2134        assert!(source_dir.path().join("src.txt").exists());
2135        assert!(!source_dir.path().join("dst.txt").exists());
2136    }
2137
2138    #[tokio::test]
2139    async fn test_result_json_omits_internal_trash_id() {
2140        let (manager, _safety, source_dir, _data) = create_test_manager_with_safety();
2141        fs::write(source_dir.path().join("gone.txt"), "x").unwrap();
2142        manager.delete(&PathBuf::from("gone.txt")).await;
2143        let json = String::from_utf8(manager.get_last_result().await).unwrap();
2144        assert!(json.contains("undo_id"));
2145        assert!(!json.contains("trash_id"));
2146    }
2147}