agpm-cli 0.4.9

AGent Package Manager - A Git-based package manager for coding agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
//! Common utilities and traits for CLI commands

use anyhow::{Context, Result};
use colored::Colorize;
use std::io::{self, IsTerminal, Write};
use std::path::{Path, PathBuf};
use tokio::io::{AsyncBufReadExt, BufReader};

use crate::manifest::{Manifest, find_manifest};

/// Common trait for CLI command execution pattern
pub trait CommandExecutor: Sized {
    /// Execute the command, finding the manifest automatically
    fn execute(self) -> impl std::future::Future<Output = Result<()>> + Send
    where
        Self: Send,
    {
        async move {
            let manifest_path = if let Ok(path) = find_manifest() {
                path
            } else {
                // Check if legacy CCPM files exist and offer interactive migration
                match handle_legacy_ccpm_migration().await {
                    Ok(Some(path)) => path,
                    Ok(None) => {
                        return Err(anyhow::anyhow!(
                            "No agpm.toml found in current directory or any parent directory. \
                             Run 'agpm init' to create a new project."
                        ));
                    }
                    Err(e) => return Err(e),
                }
            };
            self.execute_from_path(manifest_path).await
        }
    }

    /// Execute the command with a specific manifest path
    fn execute_from_path(
        self,
        manifest_path: PathBuf,
    ) -> impl std::future::Future<Output = Result<()>> + Send;
}

/// Common context for CLI commands that need manifest and project information
#[derive(Debug)]
pub struct CommandContext {
    /// Parsed project manifest (agpm.toml)
    pub manifest: Manifest,
    /// Path to the manifest file
    pub manifest_path: PathBuf,
    /// Project root directory (containing agpm.toml)
    pub project_dir: PathBuf,
    /// Path to the lockfile (agpm.lock)
    pub lockfile_path: PathBuf,
}

impl CommandContext {
    /// Create a new command context from a manifest and project directory
    pub fn new(manifest: Manifest, project_dir: PathBuf) -> Result<Self> {
        let lockfile_path = project_dir.join("agpm.lock");
        Ok(Self {
            manifest,
            manifest_path: project_dir.join("agpm.toml"),
            project_dir,
            lockfile_path,
        })
    }

    /// Create a new command context from a manifest path
    ///
    /// # Errors
    /// Returns an error if the manifest file doesn't exist or cannot be read
    pub fn from_manifest_path(manifest_path: impl AsRef<Path>) -> Result<Self> {
        let manifest_path = manifest_path.as_ref();

        if !manifest_path.exists() {
            return Err(anyhow::anyhow!("Manifest file {} not found", manifest_path.display()));
        }

        let project_dir = manifest_path
            .parent()
            .ok_or_else(|| anyhow::anyhow!("Invalid manifest path"))?
            .to_path_buf();

        let manifest = Manifest::load(manifest_path).with_context(|| {
            format!("Failed to parse manifest file: {}", manifest_path.display())
        })?;

        let lockfile_path = project_dir.join("agpm.lock");

        Ok(Self {
            manifest,
            manifest_path: manifest_path.to_path_buf(),
            project_dir,
            lockfile_path,
        })
    }

    /// Load an existing lockfile if it exists
    ///
    /// # Errors
    /// Returns an error if the lockfile exists but cannot be parsed
    pub fn load_lockfile(&self) -> Result<Option<crate::lockfile::LockFile>> {
        if self.lockfile_path.exists() {
            let lockfile =
                crate::lockfile::LockFile::load(&self.lockfile_path).with_context(|| {
                    format!("Failed to load lockfile: {}", self.lockfile_path.display())
                })?;
            Ok(Some(lockfile))
        } else {
            Ok(None)
        }
    }

    /// Load an existing lockfile with automatic regeneration for invalid files
    ///
    /// If the lockfile exists but is invalid or corrupted, this method will
    /// offer to automatically regenerate it. This provides a better user
    /// experience by recovering from common lockfile issues.
    ///
    /// # Arguments
    ///
    /// * `can_regenerate` - Whether automatic regeneration should be offered
    /// * `operation_name` - Name of the operation for error messages (e.g., "list")
    ///
    /// # Returns
    ///
    /// * `Ok(Some(lockfile))` - Successfully loaded or regenerated lockfile
    /// * `Ok(None)` - No lockfile exists (not an error)
    /// * `Err` - Critical error that cannot be recovered from
    ///
    /// # Behavior
    ///
    /// - **Interactive mode** (TTY): Prompts user with Y/n confirmation
    /// - **Non-interactive mode** (CI/CD): Fails with helpful error message
    /// - **Backup strategy**: Copies invalid lockfile to `agpm.lock.invalid` before regeneration
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use anyhow::Result;
    /// # use agpm_cli::cli::common::CommandContext;
    /// # use agpm_cli::manifest::Manifest;
    /// # use std::path::PathBuf;
    /// # async fn example() -> Result<()> {
    /// let manifest = Manifest::load(&PathBuf::from("agpm.toml"))?;
    /// let project_dir = PathBuf::from(".");
    /// let ctx = CommandContext::new(manifest, project_dir)?;
    /// match ctx.load_lockfile_with_regeneration(true, "list") {
    ///     Ok(Some(lockfile)) => println!("Loaded lockfile"),
    ///     Ok(None) => println!("No lockfile found"),
    ///     Err(e) => eprintln!("Error: {}", e),
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn load_lockfile_with_regeneration(
        &self,
        can_regenerate: bool,
        operation_name: &str,
    ) -> Result<Option<crate::lockfile::LockFile>> {
        // If lockfile doesn't exist, that's not an error
        if !self.lockfile_path.exists() {
            return Ok(None);
        }

        // Try to load the lockfile
        match crate::lockfile::LockFile::load(&self.lockfile_path) {
            Ok(lockfile) => Ok(Some(lockfile)),
            Err(e) => {
                // Analyze the error to see if it's recoverable
                let error_msg = e.to_string();
                let can_auto_recover = can_regenerate
                    && (error_msg.contains("Invalid TOML syntax")
                        || error_msg.contains("Lockfile version")
                        || error_msg.contains("missing field")
                        || error_msg.contains("invalid type")
                        || error_msg.contains("expected"));

                if !can_auto_recover {
                    // Not a recoverable error, return the original error
                    return Err(e);
                }

                // This is a recoverable error, offer regeneration
                let backup_path = self.lockfile_path.with_extension("lock.invalid");

                // Create user-friendly message
                let regenerate_message = format!(
                    "The lockfile appears to be invalid or corrupted.\n\n\
                     Error: {}\n\n\
                     Note: The lockfile format is not yet stable as this is beta software.\n\n\
                     The invalid lockfile will be backed up to: {}",
                    error_msg,
                    backup_path.display()
                );

                // Check if we're in interactive mode
                if io::stdin().is_terminal() {
                    // Interactive mode: prompt user
                    println!("{}", regenerate_message);
                    print!("Would you like to regenerate the lockfile automatically? [Y/n] ");
                    io::stdout().flush().unwrap();

                    let mut input = String::new();
                    match io::stdin().read_line(&mut input) {
                        Ok(_) => {
                            let response = input.trim().to_lowercase();
                            if response.is_empty() || response == "y" || response == "yes" {
                                // User agreed to regenerate
                                self.backup_and_regenerate_lockfile(&backup_path, operation_name)?;
                                Ok(None) // Return None so caller creates new lockfile
                            } else {
                                // User declined, return the original error
                                Err(crate::core::AgpmError::InvalidLockfileError {
                                    file: self.lockfile_path.display().to_string(),
                                    reason: format!(
                                        "{} (User declined automatic regeneration)",
                                        error_msg
                                    ),
                                    can_regenerate: true,
                                }
                                .into())
                            }
                        }
                        Err(_) => {
                            // Failed to read input, fall back to non-interactive behavior
                            Err(self.create_non_interactive_error(&error_msg, operation_name))
                        }
                    }
                } else {
                    // Non-interactive mode: fail with helpful message
                    Err(self.create_non_interactive_error(&error_msg, operation_name))
                }
            }
        }
    }

    /// Backup the invalid lockfile and display regeneration instructions
    fn backup_and_regenerate_lockfile(
        &self,
        backup_path: &Path,
        operation_name: &str,
    ) -> Result<()> {
        // Backup the invalid lockfile
        if let Err(e) = std::fs::copy(&self.lockfile_path, backup_path) {
            eprintln!("Warning: Failed to backup invalid lockfile: {}", e);
        } else {
            println!("✓ Backed up invalid lockfile to: {}", backup_path.display());
        }

        // Remove the invalid lockfile
        if let Err(e) = std::fs::remove_file(&self.lockfile_path) {
            return Err(anyhow::anyhow!("Failed to remove invalid lockfile: {}", e));
        }

        println!("✓ Removed invalid lockfile");
        println!("Note: Run 'agpm install' to regenerate the lockfile");

        // If this is not an install command, suggest running install
        if operation_name != "install" {
            println!("Alternatively, run 'agpm {} --regenerate' if available", operation_name);
        }

        Ok(())
    }

    /// Create a non-interactive error message for CI/CD environments
    fn create_non_interactive_error(
        &self,
        error_msg: &str,
        _operation_name: &str,
    ) -> anyhow::Error {
        let backup_path = self.lockfile_path.with_extension("lock.invalid");

        crate::core::AgpmError::InvalidLockfileError {
            file: self.lockfile_path.display().to_string(),
            reason: format!(
                "{}\n\n\
                 To fix this issue:\n\
                 1. Backup the invalid lockfile: cp agpm.lock {}\n\
                 2. Remove the invalid lockfile: rm agpm.lock\n\
                 3. Regenerate it: agpm install\n\n\
                 Note: The lockfile format is not yet stable as this is beta software.",
                error_msg,
                backup_path.display()
            ),
            can_regenerate: true,
        }
        .into()
    }

    /// Save a lockfile to the project directory
    ///
    /// # Errors
    /// Returns an error if the lockfile cannot be written
    pub fn save_lockfile(&self, lockfile: &crate::lockfile::LockFile) -> Result<()> {
        lockfile
            .save(&self.lockfile_path)
            .with_context(|| format!("Failed to save lockfile: {}", self.lockfile_path.display()))
    }
}

/// Handle legacy CCPM files by offering interactive migration.
///
/// This function searches for ccpm.toml and ccpm.lock files in the current
/// directory and parent directories. If found, it prompts the user to migrate
/// and performs the migration if they accept.
///
/// # Behavior
///
/// - **Interactive mode**: Prompts user with Y/n confirmation (stdin is a TTY)
/// - **Non-interactive mode**: Returns `Ok(None)` if stdin is not a TTY (e.g., CI/CD)
/// - **Search scope**: Traverses from current directory to filesystem root
///
/// # Returns
///
/// - `Ok(Some(PathBuf))` with the path to agpm.toml if migration succeeded
/// - `Ok(None)` if no legacy files were found OR user declined OR non-interactive mode
/// - `Err` if migration failed
///
/// # Examples
///
/// ```no_run
/// # use anyhow::Result;
/// # async fn example() -> Result<()> {
/// use agpm_cli::cli::common::handle_legacy_ccpm_migration;
///
/// match handle_legacy_ccpm_migration().await? {
///     Some(path) => println!("Migrated to: {}", path.display()),
///     None => println!("No migration performed"),
/// }
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if:
/// - Unable to access current directory
/// - Unable to perform migration operations
pub async fn handle_legacy_ccpm_migration() -> Result<Option<PathBuf>> {
    let current_dir = std::env::current_dir()?;
    let legacy_dir = find_legacy_ccpm_directory(&current_dir);

    let Some(dir) = legacy_dir else {
        return Ok(None);
    };

    // Check if we're in an interactive terminal
    if !std::io::stdin().is_terminal() {
        // Non-interactive mode: Don't prompt, just inform and exit
        eprintln!("{}", "Legacy CCPM files detected (non-interactive mode).".yellow());
        eprintln!(
            "Run {} to migrate manually.",
            format!("agpm migrate --path {}", dir.display()).cyan()
        );
        return Ok(None);
    }

    // Found legacy files - prompt for migration
    let ccpm_toml = dir.join("ccpm.toml");
    let ccpm_lock = dir.join("ccpm.lock");

    let mut files = Vec::new();
    if ccpm_toml.exists() {
        files.push("ccpm.toml");
    }
    if ccpm_lock.exists() {
        files.push("ccpm.lock");
    }

    let files_str = files.join(" and ");

    println!("{}", "Legacy CCPM files detected!".yellow().bold());
    println!("{} {} found in {}", "→".cyan(), files_str, dir.display());
    println!();

    // Prompt user for migration
    print!("{} ", "Would you like to migrate to AGPM now? [Y/n]:".green());
    io::stdout().flush()?;

    // Use async I/O for proper integration with Tokio runtime
    let mut reader = BufReader::new(tokio::io::stdin());
    let mut response = String::new();
    reader.read_line(&mut response).await?;
    let response = response.trim().to_lowercase();

    if response.is_empty() || response == "y" || response == "yes" {
        println!();
        println!("{}", "🚀 Starting migration...".cyan());

        // Perform the migration with automatic installation
        let migrate_cmd = super::migrate::MigrateCommand::new(Some(dir.clone()), false, false);

        migrate_cmd.execute().await?;

        // Return the path to the newly created agpm.toml
        Ok(Some(dir.join("agpm.toml")))
    } else {
        println!();
        println!("{}", "Migration cancelled.".yellow());
        println!(
            "Run {} to migrate manually.",
            format!("agpm migrate --path {}", dir.display()).cyan()
        );
        Ok(None)
    }
}

/// Check for legacy CCPM files and return a migration message if found.
///
/// This function searches for ccpm.toml and ccpm.lock files in the current
/// directory and parent directories, similar to how `find_manifest` works.
/// If legacy files are found, it returns a helpful error message suggesting
/// to run the migration command.
///
/// # Returns
///
/// - `Some(String)` with migration instructions if legacy files are found
/// - `None` if no legacy files are detected
#[must_use]
pub fn check_for_legacy_ccpm_files() -> Option<String> {
    check_for_legacy_ccpm_files_from(std::env::current_dir().ok()?)
}

/// Find the directory containing legacy CCPM files.
///
/// Searches for ccpm.toml or ccpm.lock starting from the given directory
/// and walking up the directory tree.
///
/// # Returns
///
/// - `Some(PathBuf)` with the directory containing legacy files
/// - `None` if no legacy files are found
fn find_legacy_ccpm_directory(start_dir: &Path) -> Option<PathBuf> {
    let mut dir = start_dir;

    loop {
        let ccpm_toml = dir.join("ccpm.toml");
        let ccpm_lock = dir.join("ccpm.lock");

        if ccpm_toml.exists() || ccpm_lock.exists() {
            return Some(dir.to_path_buf());
        }

        dir = dir.parent()?;
    }
}

/// Check for legacy CCPM files starting from a specific directory.
///
/// This is the internal implementation that allows for testing without
/// changing the current working directory.
fn check_for_legacy_ccpm_files_from(start_dir: PathBuf) -> Option<String> {
    let current = start_dir;
    let mut dir = current.as_path();

    loop {
        let ccpm_toml = dir.join("ccpm.toml");
        let ccpm_lock = dir.join("ccpm.lock");

        if ccpm_toml.exists() || ccpm_lock.exists() {
            let mut files = Vec::new();
            if ccpm_toml.exists() {
                files.push("ccpm.toml");
            }
            if ccpm_lock.exists() {
                files.push("ccpm.lock");
            }

            let files_str = files.join(" and ");
            let location = if dir == current {
                "current directory".to_string()
            } else {
                format!("parent directory: {}", dir.display())
            };

            return Some(format!(
                "{}\n\n{} {} found in {}.\n{}\n  {}\n\n{}",
                "Legacy CCPM files detected!".yellow().bold(),
                "→".cyan(),
                files_str,
                location,
                "Run the migration command to upgrade:".yellow(),
                format!("agpm migrate --path {}", dir.display()).cyan().bold(),
                "Or run 'agpm init' to create a new AGPM project.".dimmed()
            ));
        }

        dir = dir.parent()?;
    }
}

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

    #[test]
    fn test_command_context_from_manifest_path() {
        let temp_dir = TempDir::new().unwrap();
        let manifest_path = temp_dir.path().join("agpm.toml");

        // Create a test manifest
        std::fs::write(
            &manifest_path,
            r#"
[sources]
test = "https://github.com/test/repo.git"

[agents]
"#,
        )
        .unwrap();

        let context = CommandContext::from_manifest_path(&manifest_path).unwrap();

        assert_eq!(context.manifest_path, manifest_path);
        assert_eq!(context.project_dir, temp_dir.path());
        assert_eq!(context.lockfile_path, temp_dir.path().join("agpm.lock"));
        assert!(context.manifest.sources.contains_key("test"));
    }

    #[test]
    fn test_command_context_missing_manifest() {
        let result = CommandContext::from_manifest_path("/nonexistent/agpm.toml");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not found"));
    }

    #[test]
    fn test_command_context_invalid_manifest() {
        let temp_dir = TempDir::new().unwrap();
        let manifest_path = temp_dir.path().join("agpm.toml");

        // Create an invalid manifest
        std::fs::write(&manifest_path, "invalid toml {{").unwrap();

        let result = CommandContext::from_manifest_path(&manifest_path);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Failed to parse manifest"));
    }

    #[test]
    fn test_load_lockfile_exists() {
        let temp_dir = TempDir::new().unwrap();
        let manifest_path = temp_dir.path().join("agpm.toml");
        let lockfile_path = temp_dir.path().join("agpm.lock");

        // Create test files
        std::fs::write(&manifest_path, "[sources]\n").unwrap();
        std::fs::write(
            &lockfile_path,
            r#"
version = 1

[[sources]]
name = "test"
url = "https://github.com/test/repo.git"
commit = "abc123"
fetched_at = "2024-01-01T00:00:00Z"
"#,
        )
        .unwrap();

        let context = CommandContext::from_manifest_path(&manifest_path).unwrap();
        let lockfile = context.load_lockfile().unwrap();

        assert!(lockfile.is_some());
        let lockfile = lockfile.unwrap();
        assert_eq!(lockfile.sources.len(), 1);
        assert_eq!(lockfile.sources[0].name, "test");
    }

    #[test]
    fn test_load_lockfile_not_exists() {
        let temp_dir = TempDir::new().unwrap();
        let manifest_path = temp_dir.path().join("agpm.toml");

        std::fs::write(&manifest_path, "[sources]\n").unwrap();

        let context = CommandContext::from_manifest_path(&manifest_path).unwrap();
        let lockfile = context.load_lockfile().unwrap();

        assert!(lockfile.is_none());
    }

    #[test]
    fn test_save_lockfile() {
        let temp_dir = TempDir::new().unwrap();
        let manifest_path = temp_dir.path().join("agpm.toml");

        std::fs::write(&manifest_path, "[sources]\n").unwrap();

        let context = CommandContext::from_manifest_path(&manifest_path).unwrap();

        let lockfile = crate::lockfile::LockFile {
            version: 1,
            sources: vec![],
            agents: vec![],
            snippets: vec![],
            commands: vec![],
            scripts: vec![],
            hooks: vec![],
            mcp_servers: vec![],
        };

        context.save_lockfile(&lockfile).unwrap();

        assert!(context.lockfile_path.exists());
        let saved_content = std::fs::read_to_string(&context.lockfile_path).unwrap();
        assert!(saved_content.contains("version = 1"));
    }

    #[test]
    fn test_check_for_legacy_ccpm_no_files() {
        let temp_dir = TempDir::new().unwrap();
        let result = check_for_legacy_ccpm_files_from(temp_dir.path().to_path_buf());
        assert!(result.is_none());
    }

    #[test]
    fn test_check_for_legacy_ccpm_toml_only() {
        let temp_dir = TempDir::new().unwrap();
        std::fs::write(temp_dir.path().join("ccpm.toml"), "[sources]\n").unwrap();

        let result = check_for_legacy_ccpm_files_from(temp_dir.path().to_path_buf());
        assert!(result.is_some());
        let msg = result.unwrap();
        assert!(msg.contains("Legacy CCPM files detected"));
        assert!(msg.contains("ccpm.toml"));
        assert!(msg.contains("agpm migrate"));
    }

    #[test]
    fn test_check_for_legacy_ccpm_lock_only() {
        let temp_dir = TempDir::new().unwrap();
        std::fs::write(temp_dir.path().join("ccpm.lock"), "# lock\n").unwrap();

        let result = check_for_legacy_ccpm_files_from(temp_dir.path().to_path_buf());
        assert!(result.is_some());
        let msg = result.unwrap();
        assert!(msg.contains("ccpm.lock"));
    }

    #[test]
    fn test_check_for_legacy_ccpm_both_files() {
        let temp_dir = TempDir::new().unwrap();
        std::fs::write(temp_dir.path().join("ccpm.toml"), "[sources]\n").unwrap();
        std::fs::write(temp_dir.path().join("ccpm.lock"), "# lock\n").unwrap();

        let result = check_for_legacy_ccpm_files_from(temp_dir.path().to_path_buf());
        assert!(result.is_some());
        let msg = result.unwrap();
        assert!(msg.contains("ccpm.toml and ccpm.lock"));
    }

    #[test]
    fn test_find_legacy_ccpm_directory_no_files() {
        let temp_dir = TempDir::new().unwrap();
        let result = find_legacy_ccpm_directory(temp_dir.path());
        assert!(result.is_none());
    }

    #[test]
    fn test_find_legacy_ccpm_directory_in_current_dir() {
        let temp_dir = TempDir::new().unwrap();
        std::fs::write(temp_dir.path().join("ccpm.toml"), "[sources]\n").unwrap();

        let result = find_legacy_ccpm_directory(temp_dir.path());
        assert!(result.is_some());
        assert_eq!(result.unwrap(), temp_dir.path());
    }

    #[test]
    fn test_find_legacy_ccpm_directory_in_parent() {
        let temp_dir = TempDir::new().unwrap();
        let parent = temp_dir.path();
        let child = parent.join("subdir");
        std::fs::create_dir(&child).unwrap();

        // Create legacy file in parent
        std::fs::write(parent.join("ccpm.toml"), "[sources]\n").unwrap();

        // Search from child directory
        let result = find_legacy_ccpm_directory(&child);
        assert!(result.is_some());
        assert_eq!(result.unwrap(), parent);
    }

    #[test]
    fn test_find_legacy_ccpm_directory_finds_lock_file() {
        let temp_dir = TempDir::new().unwrap();
        std::fs::write(temp_dir.path().join("ccpm.lock"), "# lock\n").unwrap();

        let result = find_legacy_ccpm_directory(temp_dir.path());
        assert!(result.is_some());
        assert_eq!(result.unwrap(), temp_dir.path());
    }

    #[tokio::test]
    async fn test_handle_legacy_ccpm_migration_no_files() {
        let temp_dir = TempDir::new().unwrap();
        let original_dir = std::env::current_dir().unwrap();

        // Change to temp directory with no legacy files
        std::env::set_current_dir(temp_dir.path()).unwrap();

        let result = handle_legacy_ccpm_migration().await;

        // Restore original directory
        std::env::set_current_dir(original_dir).unwrap();

        assert!(result.is_ok());
        assert!(result.unwrap().is_none());
    }

    #[cfg(test)]
    mod lockfile_regeneration_tests {
        use super::*;
        use crate::manifest::Manifest;
        use tempfile::TempDir;

        #[test]
        fn test_load_lockfile_with_regeneration_valid_lockfile() {
            let temp_dir = TempDir::new().unwrap();
            let project_dir = temp_dir.path();
            let manifest_path = project_dir.join("agpm.toml");
            let lockfile_path = project_dir.join("agpm.lock");

            // Create a minimal manifest
            let manifest_content = r#"[sources]
example = "https://github.com/example/repo.git"

[agents]
test = { source = "example", path = "test.md", version = "v1.0.0" }
"#;
            std::fs::write(&manifest_path, manifest_content).unwrap();

            // Create a valid lockfile
            let lockfile_content = r#"version = 1

[[sources]]
name = "example"
url = "https://github.com/example/repo.git"
commit = "abc123def456789012345678901234567890abcd"
fetched_at = "2024-01-01T00:00:00Z"

[[agents]]
name = "test"
source = "example"
path = "test.md"
version = "v1.0.0"
resolved_commit = "abc123def456789012345678901234567890abcd"
checksum = "sha256:examplechecksum"
installed_at = ".claude/agents/test.md"
"#;
            std::fs::write(&lockfile_path, lockfile_content).unwrap();

            // Test loading valid lockfile
            let manifest = Manifest::load(&manifest_path).unwrap();
            let ctx = CommandContext::new(manifest, project_dir.to_path_buf()).unwrap();

            let result = ctx.load_lockfile_with_regeneration(true, "test").unwrap();
            assert!(result.is_some());
        }

        #[test]
        fn test_load_lockfile_with_regeneration_invalid_toml() {
            let temp_dir = TempDir::new().unwrap();
            let project_dir = temp_dir.path();
            let manifest_path = project_dir.join("agpm.toml");
            let lockfile_path = project_dir.join("agpm.lock");

            // Create a minimal manifest
            let manifest_content = r#"[sources]
example = "https://github.com/example/repo.git"
"#;
            std::fs::write(&manifest_path, manifest_content).unwrap();

            // Create an invalid TOML lockfile
            std::fs::write(&lockfile_path, "invalid toml [[[").unwrap();

            // Test loading invalid lockfile in non-interactive mode
            let manifest = Manifest::load(&manifest_path).unwrap();
            let ctx = CommandContext::new(manifest, project_dir.to_path_buf()).unwrap();

            // This should return an error in non-interactive mode
            let result = ctx.load_lockfile_with_regeneration(true, "test");
            assert!(result.is_err());

            let error_msg = result.unwrap_err().to_string();
            assert!(error_msg.contains("Invalid or corrupted lockfile detected"));
            assert!(error_msg.contains("beta software"));
            assert!(error_msg.contains("cp agpm.lock"));
        }

        #[test]
        fn test_load_lockfile_with_regeneration_missing_lockfile() {
            let temp_dir = TempDir::new().unwrap();
            let project_dir = temp_dir.path();
            let manifest_path = project_dir.join("agpm.toml");

            // Create a minimal manifest
            let manifest_content = r#"[sources]
example = "https://github.com/example/repo.git"
"#;
            std::fs::write(&manifest_path, manifest_content).unwrap();

            // Test loading non-existent lockfile
            let manifest = Manifest::load(&manifest_path).unwrap();
            let ctx = CommandContext::new(manifest, project_dir.to_path_buf()).unwrap();

            let result = ctx.load_lockfile_with_regeneration(true, "test").unwrap();
            assert!(result.is_none()); // Should return None for missing lockfile
        }

        #[test]
        fn test_load_lockfile_with_regeneration_version_incompatibility() {
            let temp_dir = TempDir::new().unwrap();
            let project_dir = temp_dir.path();
            let manifest_path = project_dir.join("agpm.toml");
            let lockfile_path = project_dir.join("agpm.lock");

            // Create a minimal manifest
            let manifest_content = r#"[sources]
example = "https://github.com/example/repo.git"
"#;
            std::fs::write(&manifest_path, manifest_content).unwrap();

            // Create a lockfile with future version
            let lockfile_content = r#"version = 999

[[sources]]
name = "example"
url = "https://github.com/example/repo.git"
commit = "abc123def456789012345678901234567890abcd"
fetched_at = "2024-01-01T00:00:00Z"
"#;
            std::fs::write(&lockfile_path, lockfile_content).unwrap();

            // Test loading future version lockfile
            let manifest = Manifest::load(&manifest_path).unwrap();
            let ctx = CommandContext::new(manifest, project_dir.to_path_buf()).unwrap();

            let result = ctx.load_lockfile_with_regeneration(true, "test");
            assert!(result.is_err());

            let error_msg = result.unwrap_err().to_string();
            assert!(error_msg.contains("version") || error_msg.contains("newer"));
        }

        #[test]
        fn test_load_lockfile_with_regeneration_cannot_regenerate() {
            let temp_dir = TempDir::new().unwrap();
            let project_dir = temp_dir.path();
            let manifest_path = project_dir.join("agpm.toml");
            let lockfile_path = project_dir.join("agpm.lock");

            // Create a minimal manifest
            let manifest_content = r#"[sources]
example = "https://github.com/example/repo.git"
"#;
            std::fs::write(&manifest_path, manifest_content).unwrap();

            // Create an invalid TOML lockfile
            std::fs::write(&lockfile_path, "invalid toml [[[").unwrap();

            // Test with can_regenerate = false
            let manifest = Manifest::load(&manifest_path).unwrap();
            let ctx = CommandContext::new(manifest, project_dir.to_path_buf()).unwrap();

            let result = ctx.load_lockfile_with_regeneration(false, "test");
            assert!(result.is_err());

            // Should return the original error, not the enhanced one
            let error_msg = result.unwrap_err().to_string();
            assert!(!error_msg.contains("Invalid or corrupted lockfile detected"));
            assert!(
                error_msg.contains("Failed to load lockfile")
                    || error_msg.contains("Invalid TOML syntax")
            );
        }

        #[test]
        fn test_backup_and_regenerate_lockfile() {
            let temp_dir = TempDir::new().unwrap();
            let project_dir = temp_dir.path();
            let manifest_path = project_dir.join("agpm.toml");
            let lockfile_path = project_dir.join("agpm.lock");

            // Create a minimal manifest
            let manifest_content = r#"[sources]
example = "https://github.com/example/repo.git"
"#;
            std::fs::write(&manifest_path, manifest_content).unwrap();

            // Create an invalid lockfile
            std::fs::write(&lockfile_path, "invalid content").unwrap();

            // Test backup and regeneration
            let manifest = Manifest::load(&manifest_path).unwrap();
            let ctx = CommandContext::new(manifest, project_dir.to_path_buf()).unwrap();

            let backup_path = lockfile_path.with_extension("lock.invalid");

            // This should backup the file and remove the original
            ctx.backup_and_regenerate_lockfile(&backup_path, "test").unwrap();

            // Check that backup was created
            assert!(backup_path.exists());
            assert_eq!(std::fs::read_to_string(&backup_path).unwrap(), "invalid content");

            // Check that original was removed
            assert!(!lockfile_path.exists());
        }

        #[test]
        fn test_create_non_interactive_error() {
            let temp_dir = TempDir::new().unwrap();
            let project_dir = temp_dir.path();
            let manifest_path = project_dir.join("agpm.toml");

            // Create a minimal manifest
            let manifest_content = r#"[sources]
example = "https://github.com/example/repo.git"
"#;
            std::fs::write(&manifest_path, manifest_content).unwrap();

            // Test non-interactive error creation
            let manifest = Manifest::load(&manifest_path).unwrap();
            let ctx = CommandContext::new(manifest, project_dir.to_path_buf()).unwrap();

            let error = ctx.create_non_interactive_error("Invalid TOML syntax", "test");
            let error_msg = error.to_string();

            assert!(error_msg.contains("Invalid TOML syntax"));
            assert!(error_msg.contains("beta software"));
            assert!(error_msg.contains("cp agpm.lock"));
            assert!(error_msg.contains("rm agpm.lock"));
            assert!(error_msg.contains("agpm install"));
        }
    }

    // Note: Testing interactive behavior (user input) requires mocking stdin,
    // which is complex with tokio::io::stdin(). The non-interactive TTY check
    // will be automatically triggered in CI environments, providing implicit
    // integration testing.
}