agpm-cli 0.4.14

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
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
//! Stress tests for parallel installation with git worktrees

use agpm_cli::cache::Cache;
use agpm_cli::git::command_builder::GitCommand;
use agpm_cli::installer::{ResourceFilter, install_resources};
use agpm_cli::manifest::{DetailedDependency, Manifest, ResourceDependency};
use agpm_cli::resolver::DependencyResolver;
use agpm_cli::test_utils::init_test_logging;
use agpm_cli::utils::progress::MultiPhaseProgress;
use anyhow::Result;
use std::sync::Arc;
use tempfile::TempDir;
use tokio::fs;
use tracing::debug;

// Import test helpers for CLI-based tests
use crate::common::{ManifestBuilder, TestProject};

/// HEAVY STRESS TEST: Install 500 dependencies in parallel from multiple repos
#[tokio::test]
async fn test_heavy_stress_500_dependencies() -> Result<()> {
    init_test_logging(None);
    debug!("Starting test_heavy_stress_500_dependencies");

    let temp_dir = TempDir::new()?;
    let project_dir = temp_dir.path().join("project");
    fs::create_dir_all(&project_dir).await?;

    // Create 5 test repositories with 100 agents each
    let mut repo_urls = Vec::new();
    for repo_num in 0..5 {
        let repo_dir = temp_dir.path().join(format!("repo_{}", repo_num));
        fs::create_dir_all(&repo_dir).await?;
        setup_large_test_repository(&repo_dir, 100).await?;
        repo_urls.push(format!("file://{}", repo_dir.display()));
    }

    // Create cache
    let cache = Cache::with_dir(temp_dir.path().join("cache"))?;

    // Build manifest with all sources and agents
    let mut manifest = Manifest::new();

    // Add all sources
    for (repo_idx, repo_url) in repo_urls.iter().enumerate() {
        manifest.sources.insert(format!("repo_{}", repo_idx), repo_url.clone());
    }

    // Add all agents
    let mut total_agents = 0;
    for (repo_idx, _) in repo_urls.iter().enumerate() {
        for i in 0..100 {
            manifest.agents.insert(
                format!("repo{}_agent_{:03}", repo_idx, i),
                ResourceDependency::Detailed(Box::new(DetailedDependency {
                    source: Some(format!("repo_{}", repo_idx)),
                    path: format!("agents/agent_{:03}.md", i),
                    version: Some(
                        if i % 3 == 0 {
                            "v1.0.0"
                        } else {
                            "v2.0.0"
                        }
                        .to_string(),
                    ),
                    branch: None,
                    rev: None,
                    command: None,
                    args: None,
                    target: None,
                    filename: Some(format!("repo{}_agent_{:03}.md", repo_idx, i)),
                    dependencies: None,
                    tool: Some("claude-code".to_string()),
                    flatten: None,
                    install: None,
                    template_vars: Some(serde_json::Value::Object(serde_json::Map::new())),
                })),
            );
            total_agents += 1;
        }
    }

    // Resolve to lockfile
    let mut resolver = DependencyResolver::with_cache(manifest.clone(), cache.clone()).await?;
    let lockfile = resolver.resolve().await?;
    let progress = Arc::new(MultiPhaseProgress::new(false));

    println!("🚀 Starting heavy stress test with {} agents", total_agents);
    debug!("Starting parallel installation of {} agents", total_agents);
    let start = std::time::Instant::now();

    let results = install_resources(
        ResourceFilter::All,
        &Arc::new(lockfile),
        &manifest,
        &project_dir,
        cache.clone(),
        false,
        None,
        Some(progress),
        false, // verbose
        None,  // old_lockfile
        false, // trust_lockfile_checksums
        None,  // token_warning_threshold
    )
    .await?;

    let duration = start.elapsed();
    debug!("Installation completed in {:?}", duration);
    assert_eq!(results.installed_count, total_agents);

    println!("✅ Successfully installed {} agents in {:?}", total_agents, duration);
    println!("   Average: {:?} per agent", duration / total_agents as u32);
    println!("   Rate: {:.1} agents/second", total_agents as f64 / duration.as_secs_f64());

    // Verify a sample of files
    for repo_idx in 0..5 {
        for i in (0..100).step_by(10) {
            let path =
                project_dir.join(format!(".claude/agents/agpm/repo{}_agent_{:03}.md", repo_idx, i));
            assert!(path.exists(), "Agent from repo {} #{} should exist", repo_idx, i);
        }
    }

    // Don't clean up worktrees - they're reusable now
    // cache.cleanup_all_worktrees().await?;

    // Log performance (no assertion - rely on nextest timeout for hangs)
    println!("500 agents installed in {:?}", duration);

    // Give the system a moment to clean up resources before next test
    tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;

    Ok(())
}

/// Helper to create a large test repository with many files and multiple tags
async fn setup_large_test_repository(path: &std::path::PathBuf, num_files: usize) -> Result<()> {
    // Initialize repository
    GitCommand::init().current_dir(path).execute_success().await?;

    // Set default branch to main
    GitCommand::new().args(["checkout", "-b", "main"]).current_dir(path).execute_success().await?;

    // Configure git
    GitCommand::new()
        .args(["config", "user.email", "test@example.com"])
        .current_dir(path)
        .execute_success()
        .await?;

    GitCommand::new()
        .args(["config", "user.name", "Test User"])
        .current_dir(path)
        .execute_success()
        .await?;

    // Create agents directory
    let agents_dir = path.join("agents");
    fs::create_dir_all(&agents_dir).await?;

    // Create initial batch of files
    for i in 0..num_files {
        let agent_path = agents_dir.join(format!("agent_{:03}.md", i));
        let content = format!(
            "# Agent {}

\
            This is test agent number {}.

\
            ## Features
\
            - Feature 1 with detailed description
\
            - Feature 2 with implementation notes
\
            - Feature 3 with examples

\
            ## Configuration
\
            ```json
\
            {{
\
              \"id\": {},
\
              \"enabled\": true,
\
              \"priority\": {}
\
            }}
\
            ```
",
            i,
            i,
            i,
            i % 10
        );
        fs::write(&agent_path, content).await?;
    }

    // Initial commit
    GitCommand::add(".").current_dir(path).execute_success().await?;

    GitCommand::commit("Initial commit with all agents")
        .current_dir(path)
        .execute_success()
        .await?;

    // Create v1.0.0 tag
    GitCommand::new().args(["tag", "v1.0.0"]).current_dir(path).execute_success().await?;

    // Make some changes for v2.0.0
    for i in 0..5 {
        let agent_path = agents_dir.join(format!("agent_{:03}.md", i));
        let content = fs::read_to_string(&agent_path).await?;
        fs::write(
            &agent_path,
            format!(
                "{}
## Updated in v2.0.0
",
                content
            ),
        )
        .await?;
    }

    GitCommand::add(".").current_dir(path).execute_success().await?;

    GitCommand::commit("Update for v2.0.0").current_dir(path).execute_success().await?;

    // Create v2.0.0 tag
    GitCommand::new().args(["tag", "v2.0.0"]).current_dir(path).execute_success().await?;

    // More changes for v3.0.0
    for i in 5..10 {
        let agent_path = agents_dir.join(format!("agent_{:03}.md", i));
        let content = fs::read_to_string(&agent_path).await?;
        fs::write(
            &agent_path,
            format!(
                "{}
## Updated in v3.0.0
",
                content
            ),
        )
        .await?;
    }

    GitCommand::add(".").current_dir(path).execute_success().await?;

    GitCommand::commit("Update for v3.0.0").current_dir(path).execute_success().await?;

    // Create v3.0.0 tag
    GitCommand::new().args(["tag", "v3.0.0"]).current_dir(path).execute_success().await?;

    Ok(())
}

/// HEAVY STRESS TEST: Update 500 existing dependencies to new versions
#[tokio::test]
async fn test_heavy_stress_500_updates() -> Result<()> {
    init_test_logging(None);
    debug!("Starting test_heavy_stress_500_updates");

    let temp_dir = TempDir::new()?;
    let project_dir = temp_dir.path().join("project");
    fs::create_dir_all(&project_dir).await?;

    // Create 5 test repositories with 100 agents each
    let mut repo_urls = Vec::new();
    for repo_num in 0..5 {
        let repo_dir = temp_dir.path().join(format!("repo_{}", repo_num));
        fs::create_dir_all(&repo_dir).await?;
        setup_large_test_repository(&repo_dir, 100).await?;
        repo_urls.push(format!("file://{}", repo_dir.display()));
    }

    // Create cache
    let cache = Cache::with_dir(temp_dir.path().join("cache"))?;

    // Build manifest v1.0.0
    let mut manifest_v1 = Manifest::new();

    // Add all sources
    for (repo_idx, repo_url) in repo_urls.iter().enumerate() {
        manifest_v1.sources.insert(format!("repo_{}", repo_idx), repo_url.clone());
    }

    // Add all agents at v1.0.0
    let mut total_agents = 0;
    for (repo_idx, _) in repo_urls.iter().enumerate() {
        for i in 0..100 {
            manifest_v1.agents.insert(
                format!("repo{}_agent_{:03}", repo_idx, i),
                ResourceDependency::Detailed(Box::new(DetailedDependency {
                    source: Some(format!("repo_{}", repo_idx)),
                    path: format!("agents/agent_{:03}.md", i),
                    version: Some("v1.0.0".to_string()),
                    branch: None,
                    rev: None,
                    command: None,
                    args: None,
                    target: None,
                    filename: Some(format!("repo{}_agent_{:03}.md", repo_idx, i)),
                    dependencies: None,
                    tool: Some("claude-code".to_string()),
                    flatten: None,
                    install: None,
                    template_vars: Some(serde_json::Value::Object(serde_json::Map::new())),
                })),
            );
            total_agents += 1;
        }
    }

    // Resolve to lockfile
    let mut resolver_v1 =
        DependencyResolver::with_cache(manifest_v1.clone(), cache.clone()).await?;
    let lockfile_v1 = resolver_v1.resolve().await?;
    let progress = Arc::new(MultiPhaseProgress::new(false));

    println!("📦 Installing initial version (v1.0.0) of {} agents", total_agents);
    let start_install = std::time::Instant::now();

    let results = install_resources(
        ResourceFilter::All,
        &Arc::new(lockfile_v1),
        &manifest_v1,
        &project_dir,
        cache.clone(),
        false,
        None,
        Some(progress),
        false, // verbose
        None,  // old_lockfile
        false, // trust_lockfile_checksums
        None,  // token_warning_threshold
    )
    .await?;
    assert_eq!(results.installed_count, total_agents);

    let install_duration = start_install.elapsed();
    println!("   Initial install took {:?}", install_duration);

    // Don't clean up worktrees between installs - they're reusable
    // cache.cleanup_all_worktrees().await?;

    // Build manifest v2.0.0
    let mut manifest_v2 = Manifest::new();

    // Add all sources
    for (repo_idx, repo_url) in repo_urls.iter().enumerate() {
        manifest_v2.sources.insert(format!("repo_{}", repo_idx), repo_url.clone());
    }

    // Add all agents at v2.0.0
    for (repo_idx, _) in repo_urls.iter().enumerate() {
        for i in 0..100 {
            manifest_v2.agents.insert(
                format!("repo{}_agent_{:03}", repo_idx, i),
                ResourceDependency::Detailed(Box::new(DetailedDependency {
                    source: Some(format!("repo_{}", repo_idx)),
                    path: format!("agents/agent_{:03}.md", i),
                    version: Some("v2.0.0".to_string()),
                    branch: None,
                    rev: None,
                    command: None,
                    args: None,
                    target: None,
                    filename: Some(format!("repo{}_agent_{:03}.md", repo_idx, i)),
                    dependencies: None,
                    tool: Some("claude-code".to_string()),
                    flatten: None,
                    install: None,
                    template_vars: Some(serde_json::Value::Object(serde_json::Map::new())),
                })),
            );
        }
    }

    // Resolve to lockfile
    let mut resolver_v2 =
        DependencyResolver::with_cache(manifest_v2.clone(), cache.clone()).await?;
    let lockfile_v2 = resolver_v2.resolve().await?;

    let progress2 = Arc::new(MultiPhaseProgress::new(false));

    println!("🔄 Updating all {} agents to v2.0.0", total_agents);
    let start_update = std::time::Instant::now();

    let results = install_resources(
        ResourceFilter::All,
        &Arc::new(lockfile_v2),
        &manifest_v2,
        &project_dir,
        cache.clone(),
        false,
        None,
        Some(progress2),
        false, // verbose
        None,  // old_lockfile
        false, // trust_lockfile_checksums
        None,  // token_warning_threshold
    )
    .await?;

    let update_duration = start_update.elapsed();
    // Only agents 0-4 from each repo have different content in v2.0.0 (see setup_large_test_repository)
    // So only 5 agents * 5 repos = 25 agents actually get updated
    assert_eq!(
        results.installed_count, 500,
        "Should process all 500 agents (25 with content changes)"
    );

    println!("✅ Successfully updated {} agents to v2.0.0 in {:?}", total_agents, update_duration);
    println!("   Average: {:?} per agent", update_duration / results.installed_count as u32);
    println!(
        "   Rate: {:.1} agents/second",
        results.installed_count as f64 / update_duration.as_secs_f64()
    );

    // Verify files are updated (check a sample)
    for repo_idx in 0..5 {
        for i in (0..5).step_by(1) {
            let path =
                project_dir.join(format!(".claude/agents/agpm/repo{}_agent_{:03}.md", repo_idx, i));
            assert!(path.exists(), "Updated agent from repo {} #{} should exist", repo_idx, i);

            // For the first 5 agents of each repo, they should have v2.0.0 content
            let content = fs::read_to_string(&path).await?;
            assert!(
                content.contains("Updated in v2.0.0"),
                "Agent repo {} #{} should have v2.0.0 content",
                repo_idx,
                i
            );
        }
    }

    // Don't clean up worktrees - they're reusable now
    // cache.cleanup_all_worktrees().await?;

    // Log performance (no assertion - rely on nextest timeout for hangs)
    println!("500 agent updates completed in {:?}", update_duration);

    // Give the system a moment to clean up resources
    tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;

    Ok(())
}

/// MIXED REPOS TEST: Install dependencies from both file:// and https:// repositories
///
/// Uses CLI helpers to get proper SSH host key handling for remote test environments.
#[tokio::test]
async fn test_mixed_repos_file_and_https() -> Result<()> {
    init_test_logging(None);
    debug!("Starting test_mixed_repos_file_and_https");

    let project = TestProject::new().await?;

    // Create 2 local test repositories
    let mut local_urls = Vec::new();
    for repo_num in 0..2 {
        let repo = project.create_source_repo(&format!("local_repo_{}", repo_num)).await?;
        // Add 50 agents to each repo
        for i in 0..50 {
            repo.add_resource(
                "agents",
                &format!("agent_{:03}", i),
                &format!("# Agent {}\n\nTest agent", i),
            )
            .await?;
        }
        repo.commit_all("Initial commit")?;
        repo.tag_version("v1.0.0")?;
        local_urls.push(repo.bare_file_url(project.sources_path()).await?);
    }

    // Community agents from agpm-community repo
    let community_agents = [
        (
            "community_agent_0",
            "agents/awesome-claude-code-subagents/categories/01-core-development/api-designer.md",
        ),
        (
            "community_agent_1",
            "agents/awesome-claude-code-subagents/categories/01-core-development/backend-developer.md",
        ),
        (
            "community_agent_2",
            "agents/awesome-claude-code-subagents/categories/01-core-development/frontend-developer.md",
        ),
        (
            "community_agent_3",
            "agents/awesome-claude-code-subagents/categories/02-language-specialists/python-pro.md",
        ),
        (
            "community_agent_4",
            "agents/awesome-claude-code-subagents/categories/02-language-specialists/rust-engineer.md",
        ),
        (
            "community_agent_5",
            "agents/awesome-claude-code-subagents/categories/02-language-specialists/javascript-pro.md",
        ),
        (
            "community_agent_6",
            "agents/awesome-claude-code-subagents/categories/03-infrastructure/database-administrator.md",
        ),
        (
            "community_agent_7",
            "agents/awesome-claude-code-subagents/categories/04-quality-security/code-reviewer.md",
        ),
        (
            "community_agent_8",
            "agents/awesome-claude-code-subagents/categories/04-quality-security/test-automator.md",
        ),
        (
            "community_agent_9",
            "agents/awesome-claude-code-subagents/categories/04-quality-security/security-auditor.md",
        ),
    ];

    // Build manifest using ManifestBuilder
    let mut builder = ManifestBuilder::new()
        .add_source("local_repo_0", &local_urls[0])
        .add_source("local_repo_1", &local_urls[1])
        .add_source("community", "https://github.com/aig787/agpm-community.git");

    // Add 50 agents from each local repo
    for repo_idx in 0..2 {
        for i in 0..50 {
            let name = format!("local_repo{}_agent_{:03}", repo_idx, i);
            let source = format!("local_repo_{}", repo_idx);
            let path = format!("agents/agent_{:03}.md", i);
            let filename = format!("{}.md", name);
            builder = builder.add_agent(&name, |d| {
                d.source(&source).path(&path).version("v1.0.0").filename(&filename)
            });
        }
    }

    // Add community agents
    for (name, path) in community_agents.iter() {
        let filename = format!("{}.md", name);
        builder = builder.add_agent(name, |d| {
            d.source("community").path(path).version("main").filename(&filename)
        });
    }

    let manifest = builder.build();
    project.write_manifest(&manifest).await?;

    let total_resources = 100 + community_agents.len(); // 50 * 2 local + community

    println!(
        "🌐 Starting mixed repository test: {} local agents + {} community agents",
        100,
        community_agents.len()
    );
    let start = std::time::Instant::now();

    // Use CLI which has GIT_SSH_COMMAND set for remote environments
    let result = project.run_agpm(&["install"])?;
    result.assert_success();

    let duration = start.elapsed();

    println!("✅ Successfully installed {} resources in {:?}", total_resources, duration);
    println!("   Local file:// repos: 100 agents");
    println!("   Remote https:// repo: {} agents", community_agents.len());
    println!("   Average: {:?} per resource", duration / total_resources as u32);

    // Verify local files exist
    for repo_idx in 0..2 {
        for i in (0..50).step_by(10) {
            let path = project
                .project_path()
                .join(format!(".claude/agents/agpm/local_repo{}_agent_{:03}.md", repo_idx, i));
            assert!(path.exists(), "Local agent from repo {} #{} should exist", repo_idx, i);
        }
    }

    // Verify community files exist
    for (name, _) in community_agents.iter() {
        let path = project.project_path().join(format!(".claude/agents/agpm/{}.md", name));
        assert!(path.exists(), "Community agent '{}' should exist", name);
    }

    Ok(())
}

/// COMMUNITY REPO TEST: Parallel checkout performance from real agpm-community repository
///
/// Uses CLI helpers to get proper SSH host key handling for remote test environments.
#[tokio::test]
async fn test_community_repo_parallel_checkout_performance() -> Result<()> {
    init_test_logging(None);
    debug!("Starting test_community_repo_parallel_checkout_performance");

    let project = TestProject::new().await?;

    // All available agents from the setup_project.sh script
    let community_agents = [
        (
            "api-designer",
            "agents/awesome-claude-code-subagents/categories/01-core-development/api-designer.md",
        ),
        (
            "backend-developer",
            "agents/awesome-claude-code-subagents/categories/01-core-development/backend-developer.md",
        ),
        (
            "frontend-developer",
            "agents/awesome-claude-code-subagents/categories/01-core-development/frontend-developer.md",
        ),
        (
            "python-pro",
            "agents/awesome-claude-code-subagents/categories/02-language-specialists/python-pro.md",
        ),
        (
            "rust-engineer",
            "agents/awesome-claude-code-subagents/categories/02-language-specialists/rust-engineer.md",
        ),
        (
            "javascript-pro",
            "agents/awesome-claude-code-subagents/categories/02-language-specialists/javascript-pro.md",
        ),
        (
            "database-administrator",
            "agents/awesome-claude-code-subagents/categories/03-infrastructure/database-administrator.md",
        ),
        (
            "code-reviewer",
            "agents/awesome-claude-code-subagents/categories/04-quality-security/code-reviewer.md",
        ),
        (
            "test-automator",
            "agents/awesome-claude-code-subagents/categories/04-quality-security/test-automator.md",
        ),
        (
            "security-auditor",
            "agents/awesome-claude-code-subagents/categories/04-quality-security/security-auditor.md",
        ),
        (
            "devops-engineer",
            "agents/awesome-claude-code-subagents/categories/03-infrastructure/devops-engineer.md",
        ),
        (
            "cloud-architect",
            "agents/awesome-claude-code-subagents/categories/03-infrastructure/cloud-architect.md",
        ),
        (
            "documentation-engineer",
            "agents/awesome-claude-code-subagents/categories/06-developer-experience/documentation-engineer.md",
        ),
        (
            "ml-engineer",
            "agents/awesome-claude-code-subagents/categories/05-data-ai/ml-engineer.md",
        ),
        (
            "multi-agent-coordinator",
            "agents/awesome-claude-code-subagents/categories/09-meta-orchestration/multi-agent-coordinator.md",
        ),
    ];

    // Build manifest using ManifestBuilder
    let mut builder = ManifestBuilder::new()
        .add_source("community", "https://github.com/aig787/agpm-community.git");

    for (name, path) in community_agents.iter() {
        builder = builder.add_agent(name, |d| d.source("community").path(path).version("main"));
    }

    let manifest = builder.build();
    project.write_manifest(&manifest).await?;

    let total_agents = community_agents.len();

    println!("📦 Testing parallel checkout from agpm-community repository");
    println!("   Repository: https://github.com/aig787/agpm-community.git");
    println!("   Agents: {}", total_agents);

    let start = std::time::Instant::now();

    // Use CLI which has GIT_SSH_COMMAND set for remote environments
    let result = project.run_agpm(&["install"])?;
    result.assert_success();

    let duration = start.elapsed();

    println!("✅ Successfully installed {} community agents in {:?}", total_agents, duration);
    println!("   Average: {:?} per agent", duration / total_agents as u32);
    println!("   Rate: {:.1} agents/second", total_agents as f64 / duration.as_secs_f64());

    // Verify all community agents were installed
    for (name, _) in community_agents.iter() {
        let path = project.project_path().join(format!(".claude/agents/agpm/{}.md", name));
        assert!(path.exists(), "Community agent '{}' should exist", name);

        // Verify the file has content (not empty)
        let content = fs::read_to_string(&path).await?;
        assert!(!content.is_empty(), "Community agent '{}' should have content", name);
        assert!(
            content.contains("# ") || content.contains("## "),
            "Community agent '{}' should look like a valid markdown file",
            name
        );
    }

    // Log performance (no assertion - rely on nextest timeout for hangs)
    println!("{} community agents installed in {:?}", total_agents, duration);

    Ok(())
}

/// COMMUNITY REPO 500 DEPENDENCIES TEST: Install 500 dependencies from community repo with filename collision handling
///
/// Uses CLI helpers to get proper SSH host key handling for remote test environments.
#[tokio::test]
async fn test_community_repo_500_dependencies() -> Result<()> {
    init_test_logging(None);
    debug!("Starting test_community_repo_500_dependencies");

    let project = TestProject::new().await?;

    // The 15 agents available in agpm-community
    let community_agents = [
        (
            "api-designer",
            "agents/awesome-claude-code-subagents/categories/01-core-development/api-designer.md",
        ),
        (
            "backend-developer",
            "agents/awesome-claude-code-subagents/categories/01-core-development/backend-developer.md",
        ),
        (
            "frontend-developer",
            "agents/awesome-claude-code-subagents/categories/01-core-development/frontend-developer.md",
        ),
        (
            "python-pro",
            "agents/awesome-claude-code-subagents/categories/02-language-specialists/python-pro.md",
        ),
        (
            "rust-engineer",
            "agents/awesome-claude-code-subagents/categories/02-language-specialists/rust-engineer.md",
        ),
        (
            "javascript-pro",
            "agents/awesome-claude-code-subagents/categories/02-language-specialists/javascript-pro.md",
        ),
        (
            "database-administrator",
            "agents/awesome-claude-code-subagents/categories/03-infrastructure/database-administrator.md",
        ),
        (
            "code-reviewer",
            "agents/awesome-claude-code-subagents/categories/04-quality-security/code-reviewer.md",
        ),
        (
            "test-automator",
            "agents/awesome-claude-code-subagents/categories/04-quality-security/test-automator.md",
        ),
        (
            "security-auditor",
            "agents/awesome-claude-code-subagents/categories/04-quality-security/security-auditor.md",
        ),
        (
            "devops-engineer",
            "agents/awesome-claude-code-subagents/categories/03-infrastructure/devops-engineer.md",
        ),
        (
            "cloud-architect",
            "agents/awesome-claude-code-subagents/categories/03-infrastructure/cloud-architect.md",
        ),
        (
            "documentation-engineer",
            "agents/awesome-claude-code-subagents/categories/06-developer-experience/documentation-engineer.md",
        ),
        (
            "ml-engineer",
            "agents/awesome-claude-code-subagents/categories/05-data-ai/ml-engineer.md",
        ),
        (
            "multi-agent-coordinator",
            "agents/awesome-claude-code-subagents/categories/09-meta-orchestration/multi-agent-coordinator.md",
        ),
    ];

    // Build manifest using ManifestBuilder
    let mut builder = ManifestBuilder::new()
        .add_source("community", "https://github.com/aig787/agpm-community.git");

    // Create 500 dependencies by cycling through the available agents
    for i in 0..500 {
        let agent_index = i % community_agents.len();
        let (agent_name_base, agent_path) = community_agents[agent_index];

        // Create unique name for each instance to handle collisions
        let unique_agent_name = format!("{}-{:03}", agent_name_base, i);
        let unique_filename = format!("{}-{:03}.md", agent_name_base, i);

        builder = builder.add_agent(&unique_agent_name, |d| {
            d.source("community").path(agent_path).version("main").filename(&unique_filename)
        });
    }

    let manifest = builder.build();
    project.write_manifest(&manifest).await?;

    // Install all dependencies in parallel
    let start = std::time::Instant::now();

    // Use CLI which has GIT_SSH_COMMAND set for remote environments
    let result = project.run_agpm(&["install"])?;
    result.assert_success();

    let duration = start.elapsed();

    println!("Installed 500 community dependencies in {:?}", duration);

    // Verify agents were installed
    let agents_dir = project.project_path().join(".claude/agents/agpm");
    assert!(agents_dir.exists(), "Agents directory should exist");

    let mut agent_files = tokio::fs::read_dir(&agents_dir).await?;
    let mut count = 0;
    while let Some(entry) = agent_files.next_entry().await? {
        if entry.file_name().to_string_lossy().ends_with(".md") {
            count += 1;
        }
    }

    assert_eq!(count, 500, "Should have installed exactly 500 agent files");

    // Verify a few random agents have valid content
    for i in [0, 100, 250, 499] {
        let agent_name_base = community_agents[i % community_agents.len()].0;
        let unique_filename = format!("{}-{:03}.md", agent_name_base, i);
        let agent_path = agents_dir.join(&unique_filename);
        assert!(agent_path.exists(), "Agent {} should exist", unique_filename);

        let content = tokio::fs::read_to_string(&agent_path).await?;
        assert!(!content.is_empty(), "Agent {} should have content", unique_filename);
        assert!(
            content.contains("# ") || content.contains("## "),
            "Agent '{}' should look like a valid markdown file",
            unique_filename
        );
    }

    // Log performance (no assertion - rely on nextest timeout for hangs)
    println!("500 community dependencies installed in {:?}", duration);

    Ok(())
}

/// STRESS TEST: Verify trust_lockfile_checksums mode skips checksum verification
///
/// This test ensures that when `trust_lockfile_checksums = true`, the installer
/// skips expensive checksum verification, providing a fast path for repeated
/// installations where the lockfile is trusted.
#[tokio::test]
async fn test_stress_trust_lockfile_checksums_mode() -> Result<()> {
    init_test_logging(None);
    debug!("Starting test_stress_trust_lockfile_checksums_mode");

    let temp_dir = TempDir::new()?;
    let project_dir = temp_dir.path().join("project");
    fs::create_dir_all(&project_dir).await?;

    // Create a test repository with 50 agents
    let repo_dir = temp_dir.path().join("repo");
    fs::create_dir_all(&repo_dir).await?;
    setup_large_test_repository(&repo_dir, 50).await?;
    let repo_url = format!("file://{}", repo_dir.display());

    // Create cache
    let cache = Cache::with_dir(temp_dir.path().join("cache"))?;

    // Build manifest
    let mut manifest = Manifest::new();
    manifest.sources.insert("repo".to_string(), repo_url);

    for i in 0..50 {
        manifest.agents.insert(
            format!("agent_{:03}", i),
            ResourceDependency::Detailed(Box::new(DetailedDependency {
                source: Some("repo".to_string()),
                path: format!("agents/agent_{:03}.md", i),
                version: Some("v1.0.0".to_string()),
                branch: None,
                rev: None,
                command: None,
                args: None,
                target: None,
                filename: Some(format!("agent_{:03}.md", i)),
                dependencies: None,
                tool: Some("claude-code".to_string()),
                flatten: None,
                install: None,
                template_vars: Some(serde_json::Value::Object(serde_json::Map::new())),
            })),
        );
    }

    // Resolve to lockfile
    let mut resolver = DependencyResolver::with_cache(manifest.clone(), cache.clone()).await?;
    let lockfile = resolver.resolve().await?;
    let lockfile_arc = Arc::new(lockfile);

    // First install: trust_lockfile_checksums = false (normal mode)
    println!("🔒 Installing with checksum verification (trust=false)");
    let start_untrusted = std::time::Instant::now();
    let progress1 = Arc::new(MultiPhaseProgress::new(false));

    let results_untrusted = install_resources(
        ResourceFilter::All,
        &lockfile_arc,
        &manifest,
        &project_dir,
        cache.clone(),
        false,
        None,
        Some(progress1),
        false, // verbose
        None,  // old_lockfile
        false, // trust_lockfile_checksums = false
        None,  // token_warning_threshold
    )
    .await?;

    let duration_untrusted = start_untrusted.elapsed();
    assert_eq!(results_untrusted.installed_count, 50);
    println!("   Untrusted mode: {:?}", duration_untrusted);

    // Delete installed files to force reinstall
    let agents_dir = project_dir.join(".claude/agents/agpm");
    if agents_dir.exists() {
        tokio::fs::remove_dir_all(&agents_dir).await?;
    }

    // Second install: trust_lockfile_checksums = true (trust mode)
    println!("✅ Installing with trusted checksums (trust=true)");
    let start_trusted = std::time::Instant::now();
    let progress2 = Arc::new(MultiPhaseProgress::new(false));

    let results_trusted = install_resources(
        ResourceFilter::All,
        &lockfile_arc,
        &manifest,
        &project_dir,
        cache.clone(),
        false,
        None,
        Some(progress2),
        false, // verbose
        None,  // old_lockfile
        true,  // trust_lockfile_checksums = true
        None,  // token_warning_threshold
    )
    .await?;

    let duration_trusted = start_trusted.elapsed();
    assert_eq!(results_trusted.installed_count, 50);
    println!("   Trusted mode: {:?}", duration_trusted);

    // Verify files were installed correctly
    assert!(agents_dir.exists(), "Agents directory should exist");
    let mut agent_count = 0;
    let mut entries = tokio::fs::read_dir(&agents_dir).await?;
    while let Some(entry) = entries.next_entry().await? {
        if entry.file_name().to_string_lossy().ends_with(".md") {
            agent_count += 1;
        }
    }
    assert_eq!(agent_count, 50, "Should have installed 50 agents");

    // Log comparison (trust mode should generally be faster, but we don't assert
    // on timing as it depends on system load)
    println!(
        "📊 Performance comparison: untrusted={:?}, trusted={:?}",
        duration_untrusted, duration_trusted
    );

    Ok(())
}