Skip to main content

ragfs_fuse/
semantic.rs

1//! Semantic operations for intelligent file management.
2//!
3//! This module provides AI-powered file operations based on vector embeddings:
4//! - File organization by topic/similarity
5//! - Duplicate detection
6//! - Cleanup analysis
7//! - Similar file discovery
8//!
9//! All operations follow a Propose-Review-Apply pattern for safety.
10
11use chrono::{DateTime, Utc};
12use ragfs_core::{
13    Chunk, DistanceMetric, Embedder, EmbeddingConfig, FileRecord, SearchQuery, VectorStore,
14};
15use serde::{Deserialize, Serialize};
16use std::collections::{HashMap, HashSet};
17use std::fs;
18use std::path::{Path, PathBuf};
19use std::sync::Arc;
20use tokio::sync::RwLock;
21use tracing::{debug, info, warn};
22use uuid::Uuid;
23
24/// Request to organize files in a directory.
25#[derive(Debug, Clone, Serialize, Deserialize)]
26pub struct OrganizeRequest {
27    /// Directory scope (relative to source root)
28    pub scope: PathBuf,
29    /// Organization strategy
30    pub strategy: OrganizeStrategy,
31    /// Maximum number of groups to create
32    #[serde(default = "default_max_groups")]
33    pub max_groups: usize,
34    /// Minimum similarity threshold for grouping (0.0-1.0)
35    #[serde(default = "default_similarity_threshold")]
36    pub similarity_threshold: f32,
37}
38
39fn default_max_groups() -> usize {
40    10
41}
42
43fn default_similarity_threshold() -> f32 {
44    0.7
45}
46
47/// Strategy for organizing files.
48#[derive(Debug, Clone, Serialize, Deserialize)]
49#[serde(rename_all = "snake_case")]
50pub enum OrganizeStrategy {
51    /// Group by semantic topic/content similarity
52    ByTopic,
53    /// Group by file type first, then by content
54    ByType,
55    /// Group by project/module structure
56    ByProject,
57    /// Custom grouping with specified categories
58    Custom { categories: Vec<String> },
59}
60
61/// A proposed semantic operation plan.
62#[derive(Debug, Clone, Serialize, Deserialize)]
63pub struct SemanticPlan {
64    /// Unique plan identifier
65    pub id: Uuid,
66    /// When the plan was created
67    pub created_at: DateTime<Utc>,
68    /// Type of operation
69    pub operation: PlanOperation,
70    /// Human-readable description
71    pub description: String,
72    /// Proposed file operations
73    pub actions: Vec<PlanAction>,
74    /// Status of the plan
75    pub status: PlanStatus,
76    /// Estimated impact (files affected)
77    pub impact: PlanImpact,
78}
79
80/// Type of semantic operation.
81#[derive(Debug, Clone, Serialize, Deserialize)]
82#[serde(rename_all = "snake_case")]
83pub enum PlanOperation {
84    /// Organize files into groups
85    Organize {
86        scope: PathBuf,
87        strategy: OrganizeStrategy,
88    },
89    /// Clean up files
90    Cleanup { scope: PathBuf },
91    /// Deduplicate files
92    Dedupe { scope: PathBuf },
93}
94
95/// A single action in a plan.
96#[derive(Debug, Clone, Serialize, Deserialize)]
97pub struct PlanAction {
98    /// Type of action
99    pub action: ActionType,
100    /// Confidence score (0.0-1.0)
101    pub confidence: f32,
102    /// Reason for this action
103    pub reason: String,
104}
105
106/// Type of file action.
107#[derive(Debug, Clone, Serialize, Deserialize)]
108#[serde(rename_all = "snake_case")]
109pub enum ActionType {
110    /// Move a file to a new location
111    Move { from: PathBuf, to: PathBuf },
112    /// Create a new directory
113    Mkdir { path: PathBuf },
114    /// Delete a file (will use soft delete)
115    Delete { path: PathBuf },
116    /// Create a symlink
117    Symlink { target: PathBuf, link: PathBuf },
118}
119
120/// Status of a plan.
121#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
122#[serde(rename_all = "snake_case")]
123pub enum PlanStatus {
124    /// Plan is pending review
125    Pending,
126    /// Plan was approved and is being executed
127    Approved,
128    /// Plan was rejected
129    Rejected,
130    /// Plan was executed successfully
131    Completed,
132    /// Plan execution failed
133    Failed { error: String },
134}
135
136/// Impact summary of a plan.
137#[derive(Debug, Clone, Default, Serialize, Deserialize)]
138pub struct PlanImpact {
139    /// Total files affected
140    pub files_affected: usize,
141    /// Directories created
142    pub dirs_created: usize,
143    /// Files moved
144    pub files_moved: usize,
145    /// Files deleted
146    pub files_deleted: usize,
147}
148
149/// Analysis of cleanup candidates.
150#[derive(Debug, Clone, Serialize, Deserialize)]
151pub struct CleanupAnalysis {
152    /// When the analysis was performed
153    pub analyzed_at: DateTime<Utc>,
154    /// Total files analyzed
155    pub total_files: usize,
156    /// Cleanup candidates
157    pub candidates: Vec<CleanupCandidate>,
158    /// Potential space savings in bytes
159    pub potential_savings_bytes: u64,
160}
161
162/// A file that could be cleaned up.
163#[derive(Debug, Clone, Serialize, Deserialize)]
164pub struct CleanupCandidate {
165    /// File path
166    pub path: PathBuf,
167    /// Reason for cleanup suggestion
168    pub reason: CleanupReason,
169    /// Confidence score (0.0-1.0)
170    pub confidence: f32,
171    /// File size in bytes
172    pub size_bytes: u64,
173}
174
175/// Reason a file is suggested for cleanup.
176#[derive(Debug, Clone, Serialize, Deserialize)]
177#[serde(rename_all = "snake_case")]
178pub enum CleanupReason {
179    /// File appears to be a duplicate
180    Duplicate {
181        similar_to: PathBuf,
182        similarity: f32,
183    },
184    /// File hasn't been accessed in a long time
185    Stale { last_accessed: DateTime<Utc> },
186    /// Temporary file pattern
187    Temporary,
188    /// Generated file that can be recreated
189    Generated { source: PathBuf },
190    /// Empty or near-empty file
191    Empty,
192}
193
194/// Groups of duplicate/similar files.
195#[derive(Debug, Clone, Serialize, Deserialize)]
196pub struct DuplicateGroups {
197    /// When the analysis was performed
198    pub analyzed_at: DateTime<Utc>,
199    /// Minimum similarity threshold used
200    pub threshold: f32,
201    /// Groups of similar files
202    pub groups: Vec<DuplicateGroup>,
203    /// Total potential savings if duplicates removed
204    pub potential_savings_bytes: u64,
205}
206
207/// A group of similar files.
208#[derive(Debug, Clone, Serialize, Deserialize)]
209pub struct DuplicateGroup {
210    /// Group identifier
211    pub id: Uuid,
212    /// Representative file (keep this one)
213    pub representative: PathBuf,
214    /// Similar files (candidates for removal)
215    pub duplicates: Vec<DuplicateEntry>,
216    /// Total size of duplicates
217    pub wasted_bytes: u64,
218}
219
220/// A duplicate file entry.
221#[derive(Debug, Clone, Serialize, Deserialize)]
222pub struct DuplicateEntry {
223    /// File path
224    pub path: PathBuf,
225    /// Similarity to representative (0.0-1.0)
226    pub similarity: f32,
227    /// File size
228    pub size_bytes: u64,
229}
230
231/// Result of finding similar files.
232#[derive(Debug, Clone, Serialize, Deserialize)]
233pub struct SimilarFilesResult {
234    /// Source file
235    pub source: PathBuf,
236    /// Similar files found
237    pub similar: Vec<SimilarFile>,
238}
239
240/// A similar file.
241#[derive(Debug, Clone, Serialize, Deserialize)]
242pub struct SimilarFile {
243    /// File path
244    pub path: PathBuf,
245    /// Similarity score (0.0-1.0)
246    pub similarity: f32,
247    /// Preview of content
248    #[serde(skip_serializing_if = "Option::is_none")]
249    pub preview: Option<String>,
250}
251
252/// Configuration for semantic operations.
253#[derive(Debug, Clone)]
254pub struct SemanticConfig {
255    /// Minimum similarity for duplicate detection
256    pub duplicate_threshold: f32,
257    /// Number of results for similar file search
258    pub similar_limit: usize,
259    /// Maximum plan retention (in hours)
260    pub plan_retention_hours: u32,
261    /// Base directory for persistence (plans, etc.)
262    pub data_dir: PathBuf,
263}
264
265impl Default for SemanticConfig {
266    fn default() -> Self {
267        let data_dir = dirs::data_local_dir()
268            .unwrap_or_else(|| PathBuf::from("."))
269            .join("ragfs");
270
271        Self {
272            duplicate_threshold: 0.95,
273            similar_limit: 10,
274            plan_retention_hours: 24,
275            data_dir,
276        }
277    }
278}
279
280/// Result of executing a plan action.
281#[derive(Debug, Clone, Serialize, Deserialize)]
282pub struct ActionResult {
283    /// Whether the action succeeded
284    pub success: bool,
285    /// ID for undoing this action (if reversible)
286    #[serde(skip_serializing_if = "Option::is_none")]
287    pub undo_id: Option<Uuid>,
288    /// Error message if failed
289    #[serde(skip_serializing_if = "Option::is_none")]
290    pub error: Option<String>,
291    /// When the action was executed
292    pub executed_at: DateTime<Utc>,
293}
294
295/// Semantic manager for intelligent file operations.
296pub struct SemanticManager {
297    /// Source directory root
298    source: PathBuf,
299    /// Vector store for similarity search
300    store: Option<Arc<dyn VectorStore>>,
301    /// Embedder for generating embeddings
302    embedder: Option<Arc<dyn Embedder>>,
303    /// Configuration
304    config: SemanticConfig,
305    /// Pending plans (`plan_id` -> plan)
306    pending_plans: Arc<RwLock<HashMap<Uuid, SemanticPlan>>>,
307    /// Last similar files result
308    last_similar_result: Arc<RwLock<Option<SimilarFilesResult>>>,
309    /// Cached cleanup analysis
310    cleanup_cache: Arc<RwLock<Option<CleanupAnalysis>>>,
311    /// Cached duplicate groups
312    dedupe_cache: Arc<RwLock<Option<DuplicateGroups>>>,
313    /// Directory for storing plans
314    plans_dir: PathBuf,
315    /// Operations manager for executing actions
316    ops_manager: Option<Arc<crate::ops::OpsManager>>,
317}
318
319impl SemanticManager {
320    /// Create a new semantic manager.
321    pub fn new(
322        source: PathBuf,
323        store: Option<Arc<dyn VectorStore>>,
324        embedder: Option<Arc<dyn Embedder>>,
325        config: Option<SemanticConfig>,
326    ) -> Self {
327        let config = config.unwrap_or_default();
328
329        // Create index hash for isolation (same pattern as SafetyManager)
330        let index_hash = blake3::hash(source.to_string_lossy().as_bytes())
331            .to_hex()
332            .chars()
333            .take(16)
334            .collect::<String>();
335
336        let plans_dir = config.data_dir.join("plans").join(&index_hash);
337
338        // Ensure plans directory exists
339        if let Err(e) = fs::create_dir_all(&plans_dir) {
340            warn!("Failed to create plans directory: {e}");
341        }
342
343        // Load existing plans from disk
344        let plans = Self::load_plans(&plans_dir);
345        info!("Loaded {} existing semantic plans", plans.len());
346
347        Self {
348            source,
349            store,
350            embedder,
351            config,
352            pending_plans: Arc::new(RwLock::new(plans)),
353            last_similar_result: Arc::new(RwLock::new(None)),
354            cleanup_cache: Arc::new(RwLock::new(None)),
355            dedupe_cache: Arc::new(RwLock::new(None)),
356            plans_dir,
357            ops_manager: None,
358        }
359    }
360
361    /// Create a semantic manager with an operations manager for plan execution.
362    pub fn with_ops(
363        source: PathBuf,
364        store: Option<Arc<dyn VectorStore>>,
365        embedder: Option<Arc<dyn Embedder>>,
366        config: Option<SemanticConfig>,
367        ops_manager: Arc<crate::ops::OpsManager>,
368    ) -> Self {
369        let mut manager = Self::new(source, store, embedder, config);
370        manager.ops_manager = Some(ops_manager);
371        manager
372    }
373
374    /// Construct a manager whose plan execution always uses recoverable, jailed
375    /// operations. `data_dir` must match the caller's trash/history/undo tools.
376    pub fn with_safety(
377        source: PathBuf,
378        store: Option<Arc<dyn VectorStore>>,
379        embedder: Option<Arc<dyn Embedder>>,
380        config: Option<SemanticConfig>,
381        data_dir: PathBuf,
382    ) -> Self {
383        let safety = Arc::new(crate::SafetyManager::new(
384            &source,
385            Some(crate::SafetyConfig {
386                data_dir,
387                trash_retention_days: 7,
388                soft_delete: true,
389            }),
390        ));
391        let ops = Arc::new(crate::OpsManager::with_safety(
392            source.clone(),
393            store.clone(),
394            None,
395            safety,
396        ));
397        Self::with_ops(source, store, embedder, config, ops)
398    }
399
400    /// Set the operations manager.
401    pub fn set_ops_manager(&mut self, ops_manager: Arc<crate::ops::OpsManager>) {
402        self.ops_manager = Some(ops_manager);
403    }
404
405    /// Load all plans from disk.
406    fn load_plans(plans_dir: &PathBuf) -> HashMap<Uuid, SemanticPlan> {
407        let mut plans = HashMap::new();
408
409        if !plans_dir.exists() {
410            return plans;
411        }
412
413        let entries = match fs::read_dir(plans_dir) {
414            Ok(e) => e,
415            Err(e) => {
416                warn!("Failed to read plans directory: {e}");
417                return plans;
418            }
419        };
420
421        for entry in entries.flatten() {
422            let path = entry.path();
423            if path.extension().is_some_and(|e| e == "json")
424                && let Ok(content) = fs::read_to_string(&path)
425            {
426                match serde_json::from_str::<SemanticPlan>(&content) {
427                    Ok(plan) => {
428                        plans.insert(plan.id, plan);
429                    }
430                    Err(e) => {
431                        warn!("Failed to parse plan file {:?}: {e}", path);
432                    }
433                }
434            }
435        }
436
437        plans
438    }
439
440    /// Save a single plan to disk.
441    fn save_plan(&self, plan: &SemanticPlan) -> std::io::Result<()> {
442        let plan_path = self.plans_dir.join(format!("{}.json", plan.id));
443        let temp_path = self.plans_dir.join(format!("{}.json.tmp", plan.id));
444
445        // Write to temp file first for atomic operation
446        let content = serde_json::to_string_pretty(plan)?;
447        fs::write(&temp_path, content)?;
448
449        // Atomic rename
450        fs::rename(&temp_path, &plan_path)?;
451
452        Ok(())
453    }
454
455    /// Delete a plan file from disk.
456    fn delete_plan_file(&self, plan_id: Uuid) -> std::io::Result<()> {
457        let plan_path = self.plans_dir.join(format!("{plan_id}.json"));
458        if plan_path.exists() {
459            fs::remove_file(&plan_path)?;
460        }
461        Ok(())
462    }
463
464    /// Purge expired plans from memory and disk.
465    pub async fn purge_expired_plans(&self) -> usize {
466        let now = Utc::now();
467        let retention = chrono::Duration::hours(i64::from(self.config.plan_retention_hours));
468        let cutoff = now - retention;
469
470        let mut plans = self.pending_plans.write().await;
471        let expired: Vec<Uuid> = plans
472            .iter()
473            .filter(|(_, p)| {
474                // Purge completed/rejected/failed plans past retention
475                // Keep pending plans regardless of age
476                matches!(
477                    p.status,
478                    PlanStatus::Completed | PlanStatus::Rejected | PlanStatus::Failed { .. }
479                ) && p.created_at < cutoff
480            })
481            .map(|(id, _)| *id)
482            .collect();
483
484        let mut purged = 0;
485        for id in &expired {
486            plans.remove(id);
487            if let Err(e) = self.delete_plan_file(*id) {
488                warn!("Failed to delete expired plan file {}: {e}", id);
489            } else {
490                purged += 1;
491            }
492        }
493
494        if purged > 0 {
495            info!("Purged {} expired semantic plans", purged);
496        }
497
498        purged
499    }
500
501    /// Check if semantic operations are available.
502    #[must_use]
503    pub fn is_available(&self) -> bool {
504        self.store.is_some() && self.embedder.is_some()
505    }
506
507    /// Resolve a path and reject anything that escapes the source root.
508    fn resolve_path(&self, path: &Path) -> Result<PathBuf, String> {
509        ragfs_core::resolve_under_root(&self.source, path)
510    }
511
512    /// Canonicalize for comparison; keep the original path if it is gone.
513    fn canonical_or_owned(path: &Path) -> PathBuf {
514        path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
515    }
516
517    /// Async canonicalize so FUSE-driven tokio workers are not blocked on stat.
518    async fn canonical_or_owned_async(path: PathBuf) -> PathBuf {
519        tokio::fs::canonicalize(&path).await.unwrap_or(path)
520    }
521
522    /// Find files similar to a given path.
523    pub async fn find_similar(&self, path: &PathBuf) -> Result<SimilarFilesResult, String> {
524        let full_path = self.resolve_path(path)?;
525        let store = self.store.as_ref().ok_or("Vector store not available")?;
526        let embedder = self.embedder.as_ref().ok_or("Embedder not available")?;
527
528        debug!("Finding files similar to: {}", full_path.display());
529
530        // Read the file content
531        let content =
532            std::fs::read_to_string(&full_path).map_err(|e| format!("Failed to read file: {e}"))?;
533
534        // Generate embedding for the content
535        let config = EmbeddingConfig::default();
536        let embedding_output = embedder
537            .embed_query(&content, &config)
538            .await
539            .map_err(|e| format!("Failed to generate embedding: {e}"))?;
540
541        // Search for similar files
542        let query = SearchQuery {
543            embedding: embedding_output.embedding,
544            text: None,
545            limit: self.config.similar_limit + 1, // +1 to exclude self
546            filters: Vec::new(),
547            metric: DistanceMetric::Cosine,
548            scope_prefix: None,
549        };
550        let results = store
551            .search(query)
552            .await
553            .map_err(|e| format!("Search failed: {e}"))?;
554
555        // Convert results, excluding the source file itself.
556        // Index paths may be non-canonical; compare after canonicalize.
557        let source_canonical = Self::canonical_or_owned_async(full_path.clone()).await;
558        let similar_limit = self.config.similar_limit;
559        let similar: Vec<SimilarFile> = tokio::task::spawn_blocking(move || {
560            results
561                .into_iter()
562                .filter(|r| Self::canonical_or_owned(&r.file_path) != source_canonical)
563                .take(similar_limit)
564                .map(|r| SimilarFile {
565                    path: r.file_path,
566                    similarity: r.score, // score is already similarity (higher = more similar)
567                    preview: Some(truncate_content(&r.content, 200)),
568                })
569                .collect()
570        })
571        .await
572        .map_err(|e| format!("Failed to canonicalize similar-file paths: {e}"))?;
573
574        let result = SimilarFilesResult {
575            source: full_path,
576            similar,
577        };
578
579        // Cache the result
580        *self.last_similar_result.write().await = Some(result.clone());
581
582        info!("Found {} similar files", result.similar.len());
583        Ok(result)
584    }
585
586    /// Get the last similar files result.
587    pub async fn get_last_similar_result(&self) -> Option<SimilarFilesResult> {
588        self.last_similar_result.read().await.clone()
589    }
590
591    /// Analyze files for cleanup candidates.
592    pub async fn analyze_cleanup(&self) -> Result<CleanupAnalysis, String> {
593        let store = self.store.as_ref().ok_or("Vector store not available")?;
594
595        debug!("Analyzing files for cleanup candidates");
596
597        // Get all file records from the store
598        let stats = store
599            .stats()
600            .await
601            .map_err(|e| format!("Failed to get stats: {e}"))?;
602
603        let mut candidates = Vec::new();
604        let mut potential_savings: u64 = 0;
605
606        // For now, we'll focus on duplicate detection as the primary cleanup criterion
607        // This could be expanded to include stale file detection, etc.
608
609        // Get duplicate groups and convert high-confidence duplicates to cleanup candidates
610        if let Ok(dupes) = self.find_duplicates().await {
611            for group in &dupes.groups {
612                for dup in &group.duplicates {
613                    if dup.similarity >= self.config.duplicate_threshold {
614                        candidates.push(CleanupCandidate {
615                            path: dup.path.clone(),
616                            reason: CleanupReason::Duplicate {
617                                similar_to: group.representative.clone(),
618                                similarity: dup.similarity,
619                            },
620                            confidence: dup.similarity,
621                            size_bytes: dup.size_bytes,
622                        });
623                        potential_savings += dup.size_bytes;
624                    }
625                }
626            }
627        }
628
629        let analysis = CleanupAnalysis {
630            analyzed_at: Utc::now(),
631            total_files: stats.total_files as usize,
632            candidates,
633            potential_savings_bytes: potential_savings,
634        };
635
636        // Cache the result
637        *self.cleanup_cache.write().await = Some(analysis.clone());
638
639        info!(
640            "Cleanup analysis: {} candidates, {} bytes potential savings",
641            analysis.candidates.len(),
642            analysis.potential_savings_bytes
643        );
644
645        Ok(analysis)
646    }
647
648    /// Get cached cleanup analysis.
649    pub async fn get_cleanup_analysis(&self) -> Option<CleanupAnalysis> {
650        self.cleanup_cache.read().await.clone()
651    }
652
653    /// Find duplicate file groups.
654    pub async fn find_duplicates(&self) -> Result<DuplicateGroups, String> {
655        let store = self.store.as_ref().ok_or("Vector store not available")?;
656        let _embedder = self.embedder.as_ref().ok_or("Embedder not available")?;
657
658        debug!("Finding duplicate files");
659
660        // Get all chunks and files from the store
661        let all_chunks = store
662            .get_all_chunks()
663            .await
664            .map_err(|e| format!("Failed to get chunks: {e}"))?;
665
666        let all_files = store
667            .get_all_files()
668            .await
669            .map_err(|e| format!("Failed to get files: {e}"))?;
670
671        if all_files.is_empty() {
672            return Ok(DuplicateGroups {
673                analyzed_at: Utc::now(),
674                threshold: self.config.duplicate_threshold,
675                groups: Vec::new(),
676                potential_savings_bytes: 0,
677            });
678        }
679
680        // Build a map of file_path -> chunks with embeddings
681        let mut file_chunks: HashMap<PathBuf, Vec<&Chunk>> = HashMap::new();
682        for chunk in &all_chunks {
683            if chunk.embedding.is_some() {
684                file_chunks
685                    .entry(chunk.file_path.clone())
686                    .or_default()
687                    .push(chunk);
688            }
689        }
690
691        // Build file info map
692        let file_info: HashMap<PathBuf, &FileRecord> =
693            all_files.iter().map(|f| (f.path.clone(), f)).collect();
694
695        // Calculate average embedding for each file
696        let file_embeddings: HashMap<PathBuf, Vec<f32>> = file_chunks
697            .iter()
698            .filter_map(|(path, chunks)| {
699                let embeddings: Vec<&Vec<f32>> =
700                    chunks.iter().filter_map(|c| c.embedding.as_ref()).collect();
701
702                if embeddings.is_empty() {
703                    return None;
704                }
705
706                // Average the embeddings
707                let dim = embeddings[0].len();
708                let mut avg = vec![0.0f32; dim];
709                for emb in &embeddings {
710                    for (i, &v) in emb.iter().enumerate() {
711                        avg[i] += v;
712                    }
713                }
714                let count = embeddings.len() as f32;
715                for v in &mut avg {
716                    *v /= count;
717                }
718
719                // Normalize the averaged embedding
720                let norm: f32 = avg.iter().map(|x| x * x).sum::<f32>().sqrt();
721                if norm > 0.0 {
722                    for v in &mut avg {
723                        *v /= norm;
724                    }
725                }
726
727                Some((path.clone(), avg))
728            })
729            .collect();
730
731        // Find similar file pairs using cosine similarity
732        let file_paths: Vec<&PathBuf> = file_embeddings.keys().collect();
733        let mut similarity_pairs: Vec<(PathBuf, PathBuf, f32)> = Vec::new();
734
735        for (i, path_a) in file_paths.iter().enumerate() {
736            let emb_a = &file_embeddings[*path_a];
737            for path_b in file_paths.iter().skip(i + 1) {
738                let emb_b = &file_embeddings[*path_b];
739                let similarity = cosine_similarity(emb_a, emb_b);
740
741                if similarity >= self.config.duplicate_threshold {
742                    similarity_pairs.push(((*path_a).clone(), (*path_b).clone(), similarity));
743                }
744            }
745        }
746
747        // Cluster similar files using Union-Find
748        let mut groups: Vec<DuplicateGroup> = Vec::new();
749        let mut processed: HashSet<PathBuf> = HashSet::new();
750
751        for (path_a, path_b, similarity) in similarity_pairs {
752            if processed.contains(&path_a) || processed.contains(&path_b) {
753                continue;
754            }
755
756            // Find or create group for path_a
757            let size_a = file_info.get(&path_a).map_or(0, |f| f.size_bytes);
758            let size_b = file_info.get(&path_b).map_or(0, |f| f.size_bytes);
759
760            // Use the larger file as representative
761            let (representative, duplicate, dup_similarity, dup_size) = if size_a >= size_b {
762                (path_a.clone(), path_b.clone(), similarity, size_b)
763            } else {
764                (path_b.clone(), path_a.clone(), similarity, size_a)
765            };
766
767            // Check if representative already has a group
768            if let Some(group) = groups
769                .iter_mut()
770                .find(|g| g.representative == representative)
771            {
772                group.duplicates.push(DuplicateEntry {
773                    path: duplicate.clone(),
774                    similarity: dup_similarity,
775                    size_bytes: dup_size,
776                });
777                group.wasted_bytes += dup_size;
778                processed.insert(duplicate);
779            } else {
780                // Create new group
781                groups.push(DuplicateGroup {
782                    id: Uuid::new_v4(),
783                    representative: representative.clone(),
784                    duplicates: vec![DuplicateEntry {
785                        path: duplicate.clone(),
786                        similarity: dup_similarity,
787                        size_bytes: dup_size,
788                    }],
789                    wasted_bytes: dup_size,
790                });
791                processed.insert(representative);
792                processed.insert(duplicate);
793            }
794        }
795
796        let potential_savings: u64 = groups.iter().map(|g| g.wasted_bytes).sum();
797
798        info!(
799            "Found {} duplicate groups with {} bytes potential savings",
800            groups.len(),
801            potential_savings
802        );
803
804        let result = DuplicateGroups {
805            analyzed_at: Utc::now(),
806            threshold: self.config.duplicate_threshold,
807            groups,
808            potential_savings_bytes: potential_savings,
809        };
810
811        // Cache the result
812        *self.dedupe_cache.write().await = Some(result.clone());
813
814        Ok(result)
815    }
816
817    /// Get cached duplicate groups.
818    pub async fn get_duplicate_groups(&self) -> Option<DuplicateGroups> {
819        self.dedupe_cache.read().await.clone()
820    }
821
822    /// Create an organization plan.
823    pub async fn create_organize_plan(
824        &self,
825        request: OrganizeRequest,
826    ) -> Result<SemanticPlan, String> {
827        let scope_path = Self::canonical_or_owned_async(self.resolve_path(&request.scope)?).await;
828        let store = self.store.as_ref().ok_or("Vector store not available")?;
829        let embedder = self.embedder.as_ref();
830
831        debug!(
832            "Creating organization plan for: {}",
833            request.scope.display()
834        );
835
836        // Get all chunks and files
837        let all_chunks = store
838            .get_all_chunks()
839            .await
840            .map_err(|e| format!("Failed to get chunks: {e}"))?;
841
842        let all_files = store
843            .get_all_files()
844            .await
845            .map_err(|e| format!("Failed to get files: {e}"))?;
846
847        let scope_for_cmp = scope_path.clone();
848        let file_paths: Vec<PathBuf> = all_files.iter().map(|f| f.path.clone()).collect();
849        let chunk_paths: Vec<PathBuf> = all_chunks.iter().map(|c| c.file_path.clone()).collect();
850        let (in_scope_files, in_scope_chunks) = tokio::task::spawn_blocking(move || {
851            let files: HashSet<PathBuf> = file_paths
852                .into_iter()
853                .filter(|p| Self::canonical_or_owned(p).starts_with(&scope_for_cmp))
854                .collect();
855            let chunks: HashSet<PathBuf> = chunk_paths
856                .into_iter()
857                .filter(|p| Self::canonical_or_owned(p).starts_with(&scope_for_cmp))
858                .collect();
859            (files, chunks)
860        })
861        .await
862        .map_err(|e| format!("Failed to canonicalize scoped paths: {e}"))?;
863
864        let scoped_files: Vec<&FileRecord> = all_files
865            .iter()
866            .filter(|f| in_scope_files.contains(&f.path))
867            .collect();
868
869        if scoped_files.is_empty() {
870            return Ok(SemanticPlan {
871                id: Uuid::new_v4(),
872                created_at: Utc::now(),
873                operation: PlanOperation::Organize {
874                    scope: request.scope.clone(),
875                    strategy: request.strategy.clone(),
876                },
877                description: format!("No files found in scope: {}", request.scope.display()),
878                actions: Vec::new(),
879                status: PlanStatus::Pending,
880                impact: PlanImpact::default(),
881            });
882        }
883
884        // Build file embeddings map
885        let mut file_chunks: HashMap<PathBuf, Vec<&Chunk>> = HashMap::new();
886        for chunk in &all_chunks {
887            if chunk.embedding.is_some() && in_scope_chunks.contains(&chunk.file_path) {
888                file_chunks
889                    .entry(chunk.file_path.clone())
890                    .or_default()
891                    .push(chunk);
892            }
893        }
894
895        // Calculate average embedding for each file
896        let file_embeddings: HashMap<PathBuf, Vec<f32>> = file_chunks
897            .iter()
898            .filter_map(|(path, chunks)| {
899                let embeddings: Vec<&Vec<f32>> =
900                    chunks.iter().filter_map(|c| c.embedding.as_ref()).collect();
901
902                if embeddings.is_empty() {
903                    return None;
904                }
905
906                let dim = embeddings[0].len();
907                let mut avg = vec![0.0f32; dim];
908                for emb in &embeddings {
909                    for (i, &v) in emb.iter().enumerate() {
910                        avg[i] += v;
911                    }
912                }
913                let count = embeddings.len() as f32;
914                for v in &mut avg {
915                    *v /= count;
916                }
917
918                // Normalize
919                let norm: f32 = avg.iter().map(|x| x * x).sum::<f32>().sqrt();
920                if norm > 0.0 {
921                    for v in &mut avg {
922                        *v /= norm;
923                    }
924                }
925
926                Some((path.clone(), avg))
927            })
928            .collect();
929
930        // Generate actions based on strategy
931        let (actions, description) = match &request.strategy {
932            OrganizeStrategy::ByTopic => self.plan_by_topic(
933                &file_embeddings,
934                &scope_path,
935                request.max_groups,
936                request.similarity_threshold,
937            ),
938            OrganizeStrategy::ByType => self.plan_by_type(&scoped_files, &scope_path),
939            OrganizeStrategy::ByProject => self.plan_by_project(&scoped_files, &scope_path),
940            OrganizeStrategy::Custom { categories } => {
941                self.plan_by_custom(&file_embeddings, &scope_path, categories, embedder)
942                    .await
943            }
944        };
945
946        let dirs_created = actions
947            .iter()
948            .filter(|a| matches!(a.action, ActionType::Mkdir { .. }))
949            .count();
950        let files_moved = actions
951            .iter()
952            .filter(|a| matches!(a.action, ActionType::Move { .. }))
953            .count();
954
955        let plan = SemanticPlan {
956            id: Uuid::new_v4(),
957            created_at: Utc::now(),
958            operation: PlanOperation::Organize {
959                scope: request.scope,
960                strategy: request.strategy,
961            },
962            description,
963            actions,
964            status: PlanStatus::Pending,
965            impact: PlanImpact {
966                files_affected: files_moved,
967                dirs_created,
968                files_moved,
969                files_deleted: 0,
970            },
971        };
972
973        // Store the plan in memory
974        self.pending_plans
975            .write()
976            .await
977            .insert(plan.id, plan.clone());
978
979        // Persist to disk
980        if let Err(e) = self.save_plan(&plan) {
981            warn!("Failed to persist plan {}: {e}", plan.id);
982        }
983
984        info!(
985            "Created organization plan: {} with {} actions",
986            plan.id,
987            plan.actions.len()
988        );
989        Ok(plan)
990    }
991
992    /// Plan organization by semantic topic using clustering.
993    fn plan_by_topic(
994        &self,
995        file_embeddings: &HashMap<PathBuf, Vec<f32>>,
996        scope_path: &PathBuf,
997        max_groups: usize,
998        similarity_threshold: f32,
999    ) -> (Vec<PlanAction>, String) {
1000        if file_embeddings.is_empty() {
1001            return (Vec::new(), "No files with embeddings found".to_string());
1002        }
1003
1004        // Simple clustering: find centroids and group files
1005        let file_paths: Vec<&PathBuf> = file_embeddings.keys().collect();
1006        let num_files = file_paths.len();
1007        let num_clusters = max_groups.min(num_files);
1008
1009        // Initialize clusters with k random files (here we use evenly spaced indices)
1010        let step = if num_files > num_clusters {
1011            num_files / num_clusters
1012        } else {
1013            1
1014        };
1015        let mut centroids: Vec<Vec<f32>> = (0..num_clusters)
1016            .map(|i| file_embeddings[file_paths[i * step.min(num_files - 1)]].clone())
1017            .collect();
1018
1019        // Simple k-means iterations
1020        let mut cluster_assignments: HashMap<PathBuf, usize> = HashMap::new();
1021
1022        for _ in 0..5 {
1023            // Assign each file to nearest centroid
1024            cluster_assignments.clear();
1025            for path in &file_paths {
1026                let emb = &file_embeddings[*path];
1027                let mut best_cluster = 0;
1028                let mut best_sim = -1.0f32;
1029
1030                for (cluster_idx, centroid) in centroids.iter().enumerate() {
1031                    let sim = cosine_similarity(emb, centroid);
1032                    if sim > best_sim {
1033                        best_sim = sim;
1034                        best_cluster = cluster_idx;
1035                    }
1036                }
1037
1038                cluster_assignments.insert((*path).clone(), best_cluster);
1039            }
1040
1041            // Update centroids
1042            for (cluster_idx, centroid) in centroids.iter_mut().enumerate() {
1043                let members: Vec<&PathBuf> = cluster_assignments
1044                    .iter()
1045                    .filter(|&(_, c)| *c == cluster_idx)
1046                    .map(|(p, _)| p)
1047                    .collect();
1048
1049                if members.is_empty() {
1050                    continue;
1051                }
1052
1053                let dim = centroid.len();
1054                let mut new_centroid = vec![0.0f32; dim];
1055
1056                for path in &members {
1057                    let emb = &file_embeddings[*path];
1058                    for (i, &v) in emb.iter().enumerate() {
1059                        new_centroid[i] += v;
1060                    }
1061                }
1062
1063                let count = members.len() as f32;
1064                for v in &mut new_centroid {
1065                    *v /= count;
1066                }
1067
1068                // Normalize
1069                let norm: f32 = new_centroid.iter().map(|x| x * x).sum::<f32>().sqrt();
1070                if norm > 0.0 {
1071                    for v in &mut new_centroid {
1072                        *v /= norm;
1073                    }
1074                }
1075
1076                *centroid = new_centroid;
1077            }
1078        }
1079
1080        // Generate actions
1081        let mut actions = Vec::new();
1082
1083        // Create topic directories
1084        for cluster_idx in 0..num_clusters {
1085            let topic_dir = scope_path.join(format!("topic_{}", cluster_idx + 1));
1086            actions.push(PlanAction {
1087                action: ActionType::Mkdir { path: topic_dir },
1088                confidence: 1.0,
1089                reason: format!("Create directory for topic cluster {}", cluster_idx + 1),
1090            });
1091        }
1092
1093        // Move files to their clusters
1094        for (path, &cluster_idx) in &cluster_assignments {
1095            let file_name = path.file_name().unwrap_or_default();
1096            let topic_dir = scope_path.join(format!("topic_{}", cluster_idx + 1));
1097            let new_path = topic_dir.join(file_name);
1098
1099            if new_path != *path {
1100                // Calculate confidence based on distance to centroid
1101                let emb = &file_embeddings[path];
1102                let centroid = &centroids[cluster_idx];
1103                let confidence = cosine_similarity(emb, centroid).max(similarity_threshold);
1104
1105                actions.push(PlanAction {
1106                    action: ActionType::Move {
1107                        from: path.clone(),
1108                        to: new_path,
1109                    },
1110                    confidence,
1111                    reason: format!(
1112                        "Move to topic cluster {} based on content similarity",
1113                        cluster_idx + 1
1114                    ),
1115                });
1116            }
1117        }
1118
1119        let description = format!(
1120            "Organize {} files into {} topic clusters",
1121            file_paths.len(),
1122            num_clusters
1123        );
1124
1125        (actions, description)
1126    }
1127
1128    /// Plan organization by file type.
1129    fn plan_by_type(
1130        &self,
1131        files: &[&FileRecord],
1132        scope_path: &PathBuf,
1133    ) -> (Vec<PlanAction>, String) {
1134        let mut actions = Vec::new();
1135        let mut type_dirs: HashSet<String> = HashSet::new();
1136
1137        for file in files {
1138            // Determine type directory based on extension or MIME type
1139            let type_dir = if let Some(ext) = file.path.extension() {
1140                ext.to_string_lossy().to_string()
1141            } else {
1142                // Use MIME type category
1143                file.mime_type
1144                    .split('/')
1145                    .next()
1146                    .unwrap_or("other")
1147                    .to_string()
1148            };
1149
1150            // Create type directory if needed
1151            if type_dirs.insert(type_dir.clone()) {
1152                actions.push(PlanAction {
1153                    action: ActionType::Mkdir {
1154                        path: scope_path.join(&type_dir),
1155                    },
1156                    confidence: 1.0,
1157                    reason: format!("Create directory for {type_dir} files"),
1158                });
1159            }
1160
1161            // Move file
1162            let file_name = file.path.file_name().unwrap_or_default();
1163            let new_path = scope_path.join(&type_dir).join(file_name);
1164
1165            if new_path != file.path {
1166                actions.push(PlanAction {
1167                    action: ActionType::Move {
1168                        from: file.path.clone(),
1169                        to: new_path,
1170                    },
1171                    confidence: 1.0,
1172                    reason: format!("Move to {type_dir} directory based on file type"),
1173                });
1174            }
1175        }
1176
1177        let description = format!(
1178            "Organize {} files into {} type-based directories",
1179            files.len(),
1180            type_dirs.len()
1181        );
1182
1183        (actions, description)
1184    }
1185
1186    /// Plan organization by project structure (based on imports/dependencies).
1187    fn plan_by_project(
1188        &self,
1189        files: &[&FileRecord],
1190        scope_path: &PathBuf,
1191    ) -> (Vec<PlanAction>, String) {
1192        // For project-based organization, we look at file paths to infer structure
1193        // This is a simplified implementation
1194        let mut actions = Vec::new();
1195        let mut project_dirs: HashSet<String> = HashSet::new();
1196
1197        for file in files {
1198            // Use the first directory component after scope as "project"
1199            let relative = file.path.strip_prefix(scope_path).unwrap_or(&file.path);
1200            let project = relative.components().next().map_or_else(
1201                || "root".to_string(),
1202                |c| c.as_os_str().to_string_lossy().to_string(),
1203            );
1204
1205            if project_dirs.insert(project.clone()) && !project.contains('.') {
1206                actions.push(PlanAction {
1207                    action: ActionType::Mkdir {
1208                        path: scope_path.join(&project),
1209                    },
1210                    confidence: 0.8,
1211                    reason: format!("Create project directory: {project}"),
1212                });
1213            }
1214        }
1215
1216        let description = format!(
1217            "Organize {} files into {} project directories",
1218            files.len(),
1219            project_dirs.len()
1220        );
1221
1222        (actions, description)
1223    }
1224
1225    /// Plan organization by custom categories.
1226    ///
1227    /// Generates embeddings for category names and assigns files to the
1228    /// best matching category using cosine similarity.
1229    async fn plan_by_custom(
1230        &self,
1231        file_embeddings: &HashMap<PathBuf, Vec<f32>>,
1232        scope_path: &PathBuf,
1233        categories: &[String],
1234        embedder: Option<&Arc<dyn Embedder>>,
1235    ) -> (Vec<PlanAction>, String) {
1236        let mut actions = Vec::new();
1237
1238        // Create category directories
1239        for category in categories {
1240            actions.push(PlanAction {
1241                action: ActionType::Mkdir {
1242                    path: scope_path.join(category),
1243                },
1244                confidence: 1.0,
1245                reason: format!("Create custom category directory: {category}"),
1246            });
1247        }
1248
1249        // Try to generate embeddings for categories and assign files automatically
1250        if let Some(embedder) = embedder {
1251            let category_texts: Vec<&str> = categories.iter().map(String::as_str).collect();
1252            let config = EmbeddingConfig::default();
1253
1254            match embedder.embed_text(&category_texts, &config).await {
1255                Ok(category_embeddings) if category_embeddings.len() == categories.len() => {
1256                    // Minimum similarity threshold for assignment
1257                    const MIN_SIMILARITY: f32 = 0.3;
1258                    let mut assigned_count = 0;
1259
1260                    for (file_path, file_emb) in file_embeddings {
1261                        // Find best matching category
1262                        let best = category_embeddings
1263                            .iter()
1264                            .zip(categories.iter())
1265                            .map(|(emb, cat)| (cat, cosine_similarity(file_emb, &emb.embedding)))
1266                            .max_by(|a, b| {
1267                                a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal)
1268                            });
1269
1270                        if let Some((category, score)) = best
1271                            && score >= MIN_SIMILARITY
1272                            && let Some(file_name) = file_path.file_name()
1273                        {
1274                            let new_path = scope_path.join(category).join(file_name);
1275                            if new_path != *file_path {
1276                                actions.push(PlanAction {
1277                                    action: ActionType::Move {
1278                                        from: file_path.clone(),
1279                                        to: new_path,
1280                                    },
1281                                    confidence: score,
1282                                    reason: format!(
1283                                        "Move to category '{category}' (similarity: {score:.2})"
1284                                    ),
1285                                });
1286                                assigned_count += 1;
1287                            }
1288                        }
1289                    }
1290
1291                    let description = format!(
1292                        "Organize {} files into {} custom categories ({} files assigned)",
1293                        file_embeddings.len(),
1294                        categories.len(),
1295                        assigned_count
1296                    );
1297                    return (actions, description);
1298                }
1299                Ok(_) => {
1300                    warn!(
1301                        "Category embedding count mismatch, falling back to directory creation only"
1302                    );
1303                }
1304                Err(e) => {
1305                    warn!(
1306                        "Failed to embed categories: {}, falling back to directory creation only",
1307                        e
1308                    );
1309                }
1310            }
1311        }
1312
1313        // Fallback: just create directories without automatic assignment
1314        let description = format!(
1315            "Created {} custom category directories for {} files (manual assignment needed)",
1316            categories.len(),
1317            file_embeddings.len()
1318        );
1319
1320        (actions, description)
1321    }
1322
1323    /// List all pending plans.
1324    pub async fn list_pending_plans(&self) -> Vec<SemanticPlan> {
1325        self.pending_plans
1326            .read()
1327            .await
1328            .values()
1329            .filter(|p| p.status == PlanStatus::Pending)
1330            .cloned()
1331            .collect()
1332    }
1333
1334    /// Get a specific plan.
1335    pub async fn get_plan(&self, plan_id: Uuid) -> Option<SemanticPlan> {
1336        self.pending_plans.read().await.get(&plan_id).cloned()
1337    }
1338
1339    /// Execute a single action via `OpsManager`.
1340    async fn execute_action(&self, action: &ActionType) -> Result<ActionResult, String> {
1341        let ops = self
1342            .ops_manager
1343            .as_ref()
1344            .ok_or("OpsManager not configured - cannot execute plan actions")?;
1345
1346        let result = match action {
1347            ActionType::Move { from, to } => ops.move_file(from, to).await,
1348            ActionType::Mkdir { path } => ops.mkdir(path).await,
1349            ActionType::Delete { path } => ops.delete(path).await,
1350            ActionType::Symlink { target, link } => ops.symlink(target, link).await,
1351        };
1352
1353        Ok(ActionResult {
1354            success: result.success,
1355            undo_id: result.undo_id,
1356            error: if result.success {
1357                None
1358            } else {
1359                Some(result.error.unwrap_or_else(|| "Unknown error".to_string()))
1360            },
1361            executed_at: Utc::now(),
1362        })
1363    }
1364
1365    /// Approve and execute a plan.
1366    pub async fn approve_plan(&self, plan_id: Uuid) -> Result<SemanticPlan, String> {
1367        // Verify OpsManager is available before starting
1368        if self.ops_manager.is_none() {
1369            return Err("OpsManager not configured - cannot execute plan actions".to_string());
1370        }
1371
1372        let mut plans = self.pending_plans.write().await;
1373        let plan = plans
1374            .get_mut(&plan_id)
1375            .ok_or_else(|| "Plan not found".to_string())?;
1376
1377        if plan.status != PlanStatus::Pending {
1378            return Err(format!("Plan is not pending: {:?}", plan.status));
1379        }
1380
1381        info!(
1382            "Approving plan: {} with {} actions",
1383            plan_id,
1384            plan.actions.len()
1385        );
1386        plan.status = PlanStatus::Approved;
1387
1388        // Execute actions sequentially, stopping on first failure
1389        let total_actions = plan.actions.len();
1390        let mut completed_actions = 0;
1391
1392        // Clone actions to avoid holding lock during execution
1393        let actions_to_execute: Vec<ActionType> =
1394            plan.actions.iter().map(|a| a.action.clone()).collect();
1395
1396        // Release write lock during execution to avoid deadlock
1397        drop(plans);
1398
1399        for (idx, action) in actions_to_execute.iter().enumerate() {
1400            debug!(
1401                "Executing action {}/{}: {:?}",
1402                idx + 1,
1403                total_actions,
1404                action
1405            );
1406
1407            match self.execute_action(action).await {
1408                Ok(result) if result.success => {
1409                    completed_actions += 1;
1410                    debug!(
1411                        "Action {}/{} succeeded (undo_id: {:?})",
1412                        idx + 1,
1413                        total_actions,
1414                        result.undo_id
1415                    );
1416                }
1417                Ok(result) => {
1418                    // Action failed
1419                    let error_msg = result.error.unwrap_or_else(|| "Unknown error".to_string());
1420                    warn!("Action {}/{} failed: {}", idx + 1, total_actions, error_msg);
1421
1422                    // Update plan status to failed
1423                    let mut plans = self.pending_plans.write().await;
1424                    if let Some(plan) = plans.get_mut(&plan_id) {
1425                        plan.status = PlanStatus::Failed {
1426                            error: format!(
1427                                "Action {} of {} failed: {}",
1428                                idx + 1,
1429                                total_actions,
1430                                error_msg
1431                            ),
1432                        };
1433
1434                        let result = plan.clone();
1435                        if let Err(e) = self.save_plan(&result) {
1436                            warn!("Failed to persist failed plan {}: {e}", plan_id);
1437                        }
1438                        return Ok(result);
1439                    }
1440                    return Err("Plan disappeared during execution".to_string());
1441                }
1442                Err(e) => {
1443                    // Execution error (OpsManager issue)
1444                    warn!(
1445                        "Failed to execute action {}/{}: {}",
1446                        idx + 1,
1447                        total_actions,
1448                        e
1449                    );
1450
1451                    let mut plans = self.pending_plans.write().await;
1452                    if let Some(plan) = plans.get_mut(&plan_id) {
1453                        plan.status = PlanStatus::Failed { error: e.clone() };
1454
1455                        let result = plan.clone();
1456                        if let Err(e) = self.save_plan(&result) {
1457                            warn!("Failed to persist failed plan {}: {e}", plan_id);
1458                        }
1459                        return Ok(result);
1460                    }
1461                    return Err("Plan disappeared during execution".to_string());
1462                }
1463            }
1464        }
1465
1466        // All actions completed successfully
1467        let mut plans = self.pending_plans.write().await;
1468        if let Some(plan) = plans.get_mut(&plan_id) {
1469            plan.status = PlanStatus::Completed;
1470            info!(
1471                "Plan {} completed successfully: {} actions executed",
1472                plan_id, completed_actions
1473            );
1474
1475            let result = plan.clone();
1476            if let Err(e) = self.save_plan(&result) {
1477                warn!("Failed to persist completed plan {}: {e}", plan_id);
1478            }
1479            return Ok(result);
1480        }
1481
1482        Err("Plan disappeared during execution".to_string())
1483    }
1484
1485    /// Reject a plan.
1486    pub async fn reject_plan(&self, plan_id: Uuid) -> Result<SemanticPlan, String> {
1487        let mut plans = self.pending_plans.write().await;
1488        let plan = plans
1489            .get_mut(&plan_id)
1490            .ok_or_else(|| "Plan not found".to_string())?;
1491
1492        if plan.status != PlanStatus::Pending {
1493            return Err(format!("Plan is not pending: {:?}", plan.status));
1494        }
1495
1496        info!("Rejecting plan: {}", plan_id);
1497        plan.status = PlanStatus::Rejected;
1498
1499        let result = plan.clone();
1500
1501        // Persist the status change
1502        if let Err(e) = self.save_plan(&result) {
1503            warn!("Failed to persist rejected plan {}: {e}", plan_id);
1504        }
1505
1506        Ok(result)
1507    }
1508
1509    /// Get cleanup analysis as JSON bytes (for FUSE read).
1510    pub async fn get_cleanup_json(&self) -> Vec<u8> {
1511        if let Some(analysis) = self.get_cleanup_analysis().await {
1512            serde_json::to_string_pretty(&analysis)
1513                .unwrap_or_else(|_| "{}".to_string())
1514                .into_bytes()
1515        } else {
1516            // Return a message indicating analysis hasn't been run
1517            let msg = serde_json::json!({
1518                "message": "No cleanup analysis available. Run analyze_cleanup first.",
1519                "hint": "Write any content to .semantic/.cleanup to trigger analysis"
1520            });
1521            serde_json::to_string_pretty(&msg)
1522                .unwrap_or_default()
1523                .into_bytes()
1524        }
1525    }
1526
1527    /// Get duplicate groups as JSON bytes (for FUSE read).
1528    pub async fn get_dedupe_json(&self) -> Vec<u8> {
1529        if let Some(groups) = self.get_duplicate_groups().await {
1530            serde_json::to_string_pretty(&groups)
1531                .unwrap_or_else(|_| "{}".to_string())
1532                .into_bytes()
1533        } else {
1534            let msg = serde_json::json!({
1535                "message": "No duplicate analysis available. Run find_duplicates first.",
1536                "hint": "Write any content to .semantic/.dedupe to trigger analysis"
1537            });
1538            serde_json::to_string_pretty(&msg)
1539                .unwrap_or_default()
1540                .into_bytes()
1541        }
1542    }
1543
1544    /// Get similar files result as JSON bytes (for FUSE read).
1545    pub async fn get_similar_json(&self) -> Vec<u8> {
1546        if let Some(result) = self.get_last_similar_result().await {
1547            serde_json::to_string_pretty(&result)
1548                .unwrap_or_else(|_| "{}".to_string())
1549                .into_bytes()
1550        } else {
1551            let msg = serde_json::json!({
1552                "message": "No similar files search performed yet.",
1553                "hint": "Write a file path to .semantic/.similar to find similar files"
1554            });
1555            serde_json::to_string_pretty(&msg)
1556                .unwrap_or_default()
1557                .into_bytes()
1558        }
1559    }
1560
1561    /// Get pending plans directory listing.
1562    pub async fn get_pending_plan_ids(&self) -> Vec<String> {
1563        self.pending_plans
1564            .read()
1565            .await
1566            .iter()
1567            .filter(|(_, p)| p.status == PlanStatus::Pending)
1568            .map(|(id, _)| id.to_string())
1569            .collect()
1570    }
1571
1572    /// Get a plan as JSON bytes (for FUSE read).
1573    pub async fn get_plan_json(&self, plan_id: &str) -> Vec<u8> {
1574        if let Ok(uuid) = Uuid::parse_str(plan_id)
1575            && let Some(plan) = self.get_plan(uuid).await
1576        {
1577            return serde_json::to_string_pretty(&plan)
1578                .unwrap_or_else(|_| "{}".to_string())
1579                .into_bytes();
1580        }
1581        let msg = serde_json::json!({
1582            "error": "Plan not found",
1583            "plan_id": plan_id
1584        });
1585        serde_json::to_string_pretty(&msg)
1586            .unwrap_or_default()
1587            .into_bytes()
1588    }
1589}
1590
1591/// Truncate content for preview.
1592fn truncate_content(content: &str, max_len: usize) -> String {
1593    if content.len() <= max_len {
1594        content.to_string()
1595    } else {
1596        format!("{}...", &content[..max_len])
1597    }
1598}
1599
1600/// Calculate cosine similarity between two embeddings.
1601fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
1602    if a.len() != b.len() {
1603        return 0.0;
1604    }
1605
1606    let dot: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
1607    let norm_a: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
1608    let norm_b: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();
1609
1610    if norm_a == 0.0 || norm_b == 0.0 {
1611        return 0.0;
1612    }
1613
1614    (dot / (norm_a * norm_b)).clamp(-1.0, 1.0)
1615}
1616
1617#[cfg(test)]
1618mod tests {
1619    use super::*;
1620
1621    #[test]
1622    fn test_organize_request_serialization() {
1623        let request = OrganizeRequest {
1624            scope: PathBuf::from("docs/"),
1625            strategy: OrganizeStrategy::ByTopic,
1626            max_groups: 5,
1627            similarity_threshold: 0.8,
1628        };
1629
1630        let json = serde_json::to_string(&request).unwrap();
1631        let parsed: OrganizeRequest = serde_json::from_str(&json).unwrap();
1632
1633        assert_eq!(parsed.scope, request.scope);
1634        assert_eq!(parsed.max_groups, 5);
1635    }
1636
1637    #[test]
1638    fn test_organize_request_defaults() {
1639        let json = r#"{"scope":"src/","strategy":"by_topic"}"#;
1640        let request: OrganizeRequest = serde_json::from_str(json).unwrap();
1641
1642        assert_eq!(request.max_groups, 10);
1643        assert!((request.similarity_threshold - 0.7).abs() < f32::EPSILON);
1644    }
1645
1646    #[test]
1647    fn test_plan_status_serialization() {
1648        let status = PlanStatus::Failed {
1649            error: "test error".to_string(),
1650        };
1651        let json = serde_json::to_string(&status).unwrap();
1652        assert!(json.contains("failed"));
1653        assert!(json.contains("test error"));
1654    }
1655
1656    #[test]
1657    fn test_cleanup_reason_variants() {
1658        let duplicate = CleanupReason::Duplicate {
1659            similar_to: PathBuf::from("/original.txt"),
1660            similarity: 0.98,
1661        };
1662        let json = serde_json::to_string(&duplicate).unwrap();
1663        assert!(json.contains("duplicate"));
1664
1665        let stale = CleanupReason::Stale {
1666            last_accessed: Utc::now(),
1667        };
1668        let json = serde_json::to_string(&stale).unwrap();
1669        assert!(json.contains("stale"));
1670    }
1671
1672    #[test]
1673    fn test_semantic_config_default() {
1674        let config = SemanticConfig::default();
1675        assert!((config.duplicate_threshold - 0.95).abs() < f32::EPSILON);
1676        assert_eq!(config.similar_limit, 10);
1677        assert_eq!(config.plan_retention_hours, 24);
1678    }
1679
1680    #[test]
1681    fn test_truncate_content() {
1682        assert_eq!(truncate_content("short", 100), "short");
1683        assert_eq!(truncate_content("hello world", 5), "hello...");
1684    }
1685
1686    #[test]
1687    fn test_action_type_serialization() {
1688        let action = ActionType::Move {
1689            from: PathBuf::from("/old/path.txt"),
1690            to: PathBuf::from("/new/path.txt"),
1691        };
1692        let json = serde_json::to_string(&action).unwrap();
1693        assert!(json.contains("move"));
1694        assert!(json.contains("/old/path.txt"));
1695    }
1696
1697    #[test]
1698    fn test_similar_file_serialization() {
1699        let similar = SimilarFile {
1700            path: PathBuf::from("/doc.txt"),
1701            similarity: 0.85,
1702            preview: Some("This is a preview...".to_string()),
1703        };
1704        let json = serde_json::to_string(&similar).unwrap();
1705        assert!(json.contains("0.85"));
1706        assert!(json.contains("preview"));
1707    }
1708
1709    #[tokio::test]
1710    async fn test_semantic_manager_without_store() {
1711        let manager = SemanticManager::new(PathBuf::from("/tmp"), None, None, None);
1712        assert!(!manager.is_available());
1713    }
1714
1715    #[tokio::test]
1716    async fn test_pending_plans_empty() {
1717        let manager = SemanticManager::new(PathBuf::from("/tmp"), None, None, None);
1718        let plans = manager.list_pending_plans().await;
1719        assert!(plans.is_empty());
1720    }
1721
1722    #[tokio::test]
1723    async fn test_get_plan_not_found() {
1724        let manager = SemanticManager::new(PathBuf::from("/tmp"), None, None, None);
1725        let plan = manager.get_plan(Uuid::new_v4()).await;
1726        assert!(plan.is_none());
1727    }
1728
1729    #[tokio::test]
1730    async fn test_get_cleanup_json_empty() {
1731        let manager = SemanticManager::new(PathBuf::from("/tmp"), None, None, None);
1732        let json = manager.get_cleanup_json().await;
1733        let json_str = String::from_utf8(json).unwrap();
1734        assert!(json_str.contains("No cleanup analysis"));
1735    }
1736
1737    #[tokio::test]
1738    async fn test_get_dedupe_json_empty() {
1739        let manager = SemanticManager::new(PathBuf::from("/tmp"), None, None, None);
1740        let json = manager.get_dedupe_json().await;
1741        let json_str = String::from_utf8(json).unwrap();
1742        assert!(json_str.contains("No duplicate analysis"));
1743    }
1744
1745    #[tokio::test]
1746    async fn test_get_similar_json_empty() {
1747        let manager = SemanticManager::new(PathBuf::from("/tmp"), None, None, None);
1748        let json = manager.get_similar_json().await;
1749        let json_str = String::from_utf8(json).unwrap();
1750        assert!(json_str.contains("No similar files search"));
1751    }
1752
1753    #[tokio::test]
1754    async fn test_plan_by_custom_without_embedder() {
1755        // Test the fallback behavior when embedder is None
1756        let manager = SemanticManager::new(PathBuf::from("/tmp/test"), None, None, None);
1757        let mut file_embeddings = HashMap::new();
1758        file_embeddings.insert(PathBuf::from("/tmp/test/doc1.txt"), vec![0.1, 0.2, 0.3]);
1759        file_embeddings.insert(PathBuf::from("/tmp/test/doc2.txt"), vec![0.4, 0.5, 0.6]);
1760
1761        let scope_path = PathBuf::from("/tmp/test");
1762        let categories = vec!["code".to_string(), "docs".to_string()];
1763
1764        let (actions, description) = manager
1765            .plan_by_custom(&file_embeddings, &scope_path, &categories, None)
1766            .await;
1767
1768        // Should create 2 category directories but no file moves (no embedder)
1769        let mkdir_count = actions
1770            .iter()
1771            .filter(|a| matches!(a.action, ActionType::Mkdir { .. }))
1772            .count();
1773        let move_count = actions
1774            .iter()
1775            .filter(|a| matches!(a.action, ActionType::Move { .. }))
1776            .count();
1777
1778        assert_eq!(mkdir_count, 2, "Should create 2 category directories");
1779        assert_eq!(move_count, 0, "Should not move files without embedder");
1780        assert!(
1781            description.contains("manual assignment needed"),
1782            "Description should indicate manual assignment needed"
1783        );
1784    }
1785
1786    #[test]
1787    fn test_custom_categories_serialization() {
1788        let request = OrganizeRequest {
1789            scope: PathBuf::from("src/"),
1790            strategy: OrganizeStrategy::Custom {
1791                categories: vec!["code".to_string(), "docs".to_string(), "tests".to_string()],
1792            },
1793            max_groups: 10,
1794            similarity_threshold: 0.7,
1795        };
1796
1797        let json = serde_json::to_string(&request).unwrap();
1798        assert!(json.contains("custom"));
1799        assert!(json.contains("code"));
1800        assert!(json.contains("docs"));
1801        assert!(json.contains("tests"));
1802
1803        let parsed: OrganizeRequest = serde_json::from_str(&json).unwrap();
1804        if let OrganizeStrategy::Custom { categories } = parsed.strategy {
1805            assert_eq!(categories.len(), 3);
1806        } else {
1807            panic!("Expected Custom strategy");
1808        }
1809    }
1810
1811    #[tokio::test]
1812    async fn test_find_similar_rejects_escaped_path() {
1813        let temp = tempfile::TempDir::new().unwrap();
1814        let manager = SemanticManager::new(temp.path().to_path_buf(), None, None, None);
1815        let err = manager
1816            .find_similar(&PathBuf::from("../secret.txt"))
1817            .await
1818            .unwrap_err();
1819        assert!(err.contains("escapes"), "{err}");
1820    }
1821
1822    #[tokio::test]
1823    async fn test_find_similar_rejects_absolute_outside_root() {
1824        let temp = tempfile::TempDir::new().unwrap();
1825        let outside = tempfile::TempDir::new().unwrap();
1826        let manager = SemanticManager::new(temp.path().to_path_buf(), None, None, None);
1827        let err = manager
1828            .find_similar(&outside.path().join("other.txt"))
1829            .await
1830            .unwrap_err();
1831        assert!(err.contains("escapes"), "{err}");
1832    }
1833
1834    #[tokio::test]
1835    async fn test_create_organize_plan_rejects_escaped_scope() {
1836        let temp = tempfile::TempDir::new().unwrap();
1837        let manager = SemanticManager::new(temp.path().to_path_buf(), None, None, None);
1838        let request = OrganizeRequest {
1839            scope: PathBuf::from("../../etc"),
1840            strategy: OrganizeStrategy::ByTopic,
1841            max_groups: 5,
1842            similarity_threshold: 0.8,
1843        };
1844        let err = manager.create_organize_plan(request).await.unwrap_err();
1845        assert!(err.contains("escapes"), "{err}");
1846    }
1847
1848    #[test]
1849    fn test_canonical_or_owned_equalizes_dot_components() {
1850        let temp = tempfile::TempDir::new().unwrap();
1851        let file = temp.path().join("a.txt");
1852        std::fs::write(&file, "x").unwrap();
1853        let dotted = temp.path().join(".").join("a.txt");
1854        assert_eq!(
1855            SemanticManager::canonical_or_owned(&dotted),
1856            SemanticManager::canonical_or_owned(&file)
1857        );
1858        let scope = temp.path().join("docs");
1859        std::fs::create_dir(&scope).unwrap();
1860        let nested = scope.join("a.txt");
1861        std::fs::write(&nested, "x").unwrap();
1862        let dotted_nested = temp.path().join(".").join("docs").join("a.txt");
1863        assert!(
1864            SemanticManager::canonical_or_owned(&dotted_nested)
1865                .starts_with(SemanticManager::canonical_or_owned(&scope))
1866        );
1867    }
1868}
1869
1870#[cfg(test)]
1871mod safe_execution_tests {
1872    use super::*;
1873
1874    #[tokio::test]
1875    async fn safe_plan_delete_is_recoverable_and_cannot_escape_root() {
1876        let source = tempfile::tempdir().unwrap();
1877        let data = tempfile::tempdir().unwrap();
1878        let outside = tempfile::tempdir().unwrap();
1879        let file = source.path().join("note.txt");
1880        let external = outside.path().join("private.txt");
1881        fs::write(&file, "recoverable").unwrap();
1882        fs::write(&external, "untouched").unwrap();
1883        let manager = SemanticManager::with_safety(
1884            source.path().to_path_buf(),
1885            None,
1886            None,
1887            Some(SemanticConfig {
1888                data_dir: data.path().to_path_buf(),
1889                ..Default::default()
1890            }),
1891            data.path().to_path_buf(),
1892        );
1893        for (path, succeeds) in [(&file, true), (&external, false)] {
1894            let id = Uuid::new_v4();
1895            let plan = SemanticPlan {
1896                id,
1897                created_at: Utc::now(),
1898                operation: PlanOperation::Cleanup {
1899                    scope: PathBuf::from("."),
1900                },
1901                description: "test".into(),
1902                actions: vec![PlanAction {
1903                    action: ActionType::Delete { path: path.clone() },
1904                    confidence: 1.0,
1905                    reason: "test".into(),
1906                }],
1907                status: PlanStatus::Pending,
1908                impact: PlanImpact::default(),
1909            };
1910            manager.pending_plans.write().await.insert(id, plan);
1911            let result = manager.approve_plan(id).await.unwrap();
1912            assert_eq!(result.status == PlanStatus::Completed, succeeds);
1913            assert!(manager.approve_plan(id).await.is_err());
1914        }
1915        assert!(!file.exists());
1916        assert_eq!(fs::read_to_string(&external).unwrap(), "untouched");
1917        // Reopen the same safety store, as a separate MCP undo call does.
1918        let safety = crate::SafetyManager::new(
1919            &source.path().to_path_buf(),
1920            Some(crate::SafetyConfig {
1921                data_dir: data.path().to_path_buf(),
1922                trash_retention_days: 7,
1923                soft_delete: true,
1924            }),
1925        );
1926        let entry = safety
1927            .read_history(None)
1928            .into_iter()
1929            .find(|e| e.success && e.reversible)
1930            .unwrap();
1931        safety.undo(entry.id).await.unwrap();
1932        assert_eq!(fs::read_to_string(&file).unwrap(), "recoverable");
1933    }
1934}