agpm-cli 0.4.11

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
995
996
997
998
999
1000
1001
1002
1003
//! Common test utilities and fixtures for AGPM integration tests
//!
//! This module consolidates frequently used test patterns to reduce duplication
//! and improve test maintainability.
//!
//! # Quick Start Guide
//!
//! ## Creating Test Projects
//!
//! ```rust
//! let project = TestProject::new().await?;
//! ```
//!
//! ## Creating Repositories
//!
//! ### Simple v1.0.0 Repository (Most Common)
//! ```rust
//! // Old way (6 lines):
//! let repo = project.create_source_repo("official").await?;
//! repo.create_standard_resources().await?;
//! repo.commit_all("Initial commit")?;
//! repo.tag_version("v1.0.0")?;
//! let url = repo.bare_file_url(project.sources_path()).await?;
//!
//! // New way (1 line):
//! let (repo, url) = project.create_standard_v1_repo("official").await?;
//! ```
//!
//! ## Creating Manifests
//!
//! ### With ManifestBuilder (Recommended)
//! ```rust
//! // Old way (10+ lines of format! strings):
//! let manifest = format!(r#"
//! [sources]
//! official = "{}"
//! community = "{}"
//!
//! [agents]
//! my-agent = {{ source = "official", path = "agents/my-agent.md", version = "v1.0.0" }}
//! helper = {{ source = "community", path = "agents/helper.md", version = "v1.0.0" }}
//! "#, official_url, community_url);
//!
//! // New way (5 lines, type-safe):
//! let manifest = ManifestBuilder::new()
//!     .add_sources(&[("official", &official_url), ("community", &community_url)])
//!     .add_standard_agent("my-agent", "official", "agents/my-agent.md")
//!     .add_standard_agent("helper", "community", "agents/helper.md")
//!     .build();
//! ```
//!
//! ### Sequential Resources (Stress Tests)
//! ```rust
//! // Old way (loop):
//! for i in 0..10 {
//!     repo.add_resource("agents", &format!("agent-{:02}", i), ...).await?;
//! }
//!
//! // New way (1 line):
//! repo.add_sequential_resources("agents", "agent", 10).await?;
//! ```
//!
//! ## Helper Method Summary
//!
//! ### TestProject
//! - `new()` - Create test project with temp directories
//! - `create_source_repo(name)` - Create empty source repository
//! - `create_standard_v1_repo(name)` - **NEW**: Create repo with v1.0.0 tag
//! - `write_manifest(content)` - Write agpm.toml
//! - `run_agpm(args)` - Run AGPM CLI command
//!
//! ### ManifestBuilder
//! - `new()` - Create new builder
//! - `add_source(name, url)` - Add source repository
//! - `add_standard_agent(name, source, path)` - Add agent with v1.0.0
//! - `add_agent(name, config)` - Add agent with full config
//! - `add_local_agent(name, path)` - Add local agent (no source/version)
//! - See `manifest_builder` module for full API
//!
//! ### TestSourceRepo
//! - `add_resource(type, name, content)` - Add single resource file
//! - `add_sequential_resources(type, prefix, count)` - **NEW**: Add N sequential resources
//! - `create_standard_resources()` - Add agent, snippet, command
//! - `commit_all(message)` - Commit all changes
//! - `tag_version(version)` - Create version tag
//! - `bare_file_url(sources_path)` - Get file:// URL for testing
//!
//! ### Assertions
//! - `FileAssert::exists(path)` - Assert file exists
//! - `FileAssert::contains(path, text)` - Assert file contains text
//! - `DirAssert::exists(path)` - Assert directory exists
//! - `CommandOutput::assert_success()` - Assert command succeeded
//! - `CommandOutput::assert_stdout_contains(text)` - Assert stdout contains text

// Allow dead code because these utilities are used across different test files
// and not all utilities are used in every test file
#![allow(dead_code)]

use agpm_cli::lockfile::LockFile;
use agpm_cli::utils::normalize_path_for_storage;
use anyhow::{Context, Result, bail};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus, Stdio};
use tempfile::TempDir;
use tokio::fs;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio_retry::Retry;
use tokio_retry::strategy::ExponentialBackoff;

// Manifest builder for type-safe test manifest creation
mod manifest_builder;
#[allow(unused_imports)] // Used by integration tests, not stress tests
pub use manifest_builder::{
    DependencyBuilder, ManifestBuilder, ResourceConfigBuilder, TargetConfigBuilder,
    ToolConfigBuilder, ToolsConfigBuilder,
};

/// Git command builder for tests
pub struct TestGit {
    repo_path: PathBuf,
}

impl TestGit {
    fn run_git_command(&self, args: &[&str], action: &str) -> Result<std::process::Output> {
        let output = Command::new("git")
            .args(args)
            .current_dir(&self.repo_path)
            .output()
            .with_context(|| action.to_string())?;

        if !output.status.success() {
            bail!("{} failed: {}", action, String::from_utf8_lossy(&output.stderr));
        }

        Ok(output)
    }

    /// Create a new TestGit instance for the given repository path
    pub fn new(repo_path: impl Into<PathBuf>) -> Self {
        Self {
            repo_path: repo_path.into(),
        }
    }

    /// Initialize a new git repository
    pub fn init(&self) -> Result<()> {
        self.run_git_command(&["init"], "Failed to initialize git repository")?;
        Ok(())
    }

    /// Initialize a bare git repository
    pub fn init_bare(&self) -> Result<()> {
        self.run_git_command(&["init", "--bare"], "Failed to initialize bare git repository")?;
        Ok(())
    }

    /// Configure git user for tests
    pub fn config_user(&self) -> Result<()> {
        self.run_git_command(
            &["config", "user.email", "test@agpm.example"],
            "Failed to configure git user email",
        )?;

        self.run_git_command(
            &["config", "user.name", "Test User"],
            "Failed to configure git user name",
        )?;
        Ok(())
    }

    /// Add all files to staging
    pub fn add_all(&self) -> Result<()> {
        self.run_git_command(&["add", "."], "Failed to add files to git")?;
        Ok(())
    }

    /// Create a commit with the given message
    pub fn commit(&self, message: &str) -> Result<()> {
        self.run_git_command(
            &["commit", "-m", message, "--allow-empty"],
            "Failed to create git commit",
        )?;
        Ok(())
    }

    /// Create a tag
    pub fn tag(&self, tag_name: &str) -> Result<()> {
        self.run_git_command(&["tag", tag_name], &format!("Failed to create tag: {}", tag_name))?;
        Ok(())
    }

    /// Create and checkout a branch
    pub fn create_branch(&self, branch_name: &str) -> Result<()> {
        self.run_git_command(
            &["checkout", "-b", branch_name],
            &format!("Failed to create branch: {}", branch_name),
        )?;
        Ok(())
    }

    /// Checkout an existing branch
    pub fn checkout(&self, branch_name: &str) -> Result<()> {
        self.run_git_command(
            &["checkout", branch_name],
            &format!("Failed to checkout branch: {}", branch_name),
        )?;
        Ok(())
    }

    /// Ensure we're on a specific branch, creating it if it doesn't exist
    /// This is useful when the default branch name is unknown (master vs main)
    pub fn ensure_branch(&self, branch_name: &str) -> Result<()> {
        // Try to checkout the branch first
        if self.checkout(branch_name).is_ok() {
            return Ok(());
        }

        // Branch doesn't exist, create it from current HEAD
        self.create_branch(branch_name)?;
        Ok(())
    }

    /// Set the HEAD to point to a branch (making it the default branch)
    pub fn set_head(&self, branch_name: &str) -> Result<()> {
        self.run_git_command(
            &["symbolic-ref", "HEAD", &format!("refs/heads/{}", branch_name)],
            &format!("Failed to set HEAD to branch: {}", branch_name),
        )?;
        Ok(())
    }

    /// Get the current commit hash
    pub fn get_commit_hash(&self) -> Result<String> {
        let output = self.run_git_command(&["rev-parse", "HEAD"], "Failed to get commit hash")?;

        Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
    }

    /// Get the HEAD SHA (alias for get_commit_hash for compatibility)
    pub fn get_head_sha(&self) -> Result<String> {
        self.get_commit_hash()
    }

    /// Clone current repository to a bare repository
    pub fn clone_to_bare(&self, target_path: &Path) -> Result<()> {
        let output = Command::new("git")
            .args([
                "clone",
                "--bare",
                self.repo_path.to_str().unwrap(),
                target_path.to_str().unwrap(),
            ])
            .output()
            .context("Failed to create bare repository")?;
        if !output.status.success() {
            bail!("Failed to create bare repository: {}", String::from_utf8_lossy(&output.stderr));
        }
        Ok(())
    }

    /// Return the repository path
    pub fn repo_path(&self) -> &Path {
        &self.repo_path
    }

    /// Get porcelain status output
    pub fn status_porcelain(&self) -> Result<String> {
        let output =
            self.run_git_command(&["status", "--porcelain"], "Failed to get git status")?;
        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    }

    /// Check if path is ignored by git
    pub fn check_ignore(&self, path: &str) -> Result<bool> {
        let output = Command::new("git")
            .args(["check-ignore", path])
            .current_dir(&self.repo_path)
            .output()
            .with_context(|| format!("Failed to run git check-ignore for {}", path))?;

        Ok(output.status.success())
    }

    /// Add a remote repository
    pub fn remote_add(&self, name: &str, url: &str) -> Result<()> {
        self.run_git_command(
            &["remote", "add", name, url],
            &format!("Failed to add remote: {}", name),
        )?;
        Ok(())
    }

    /// Fetch from remotes
    pub fn fetch(&self) -> Result<()> {
        self.run_git_command(&["fetch"], "Failed to fetch from remotes")?;
        Ok(())
    }
}

/// Test project builder for creating test environments
pub struct TestProject {
    _temp_dir: TempDir, // Keep alive for RAII cleanup
    project_dir: PathBuf,
    cache_dir: PathBuf,
    sources_dir: PathBuf,
}

impl TestProject {
    /// Create a new test project with default structure
    pub async fn new() -> Result<Self> {
        let temp_dir = TempDir::new()?;
        let project_dir = temp_dir.path().join("project");
        let cache_dir = temp_dir.path().join(".agpm").join("cache");
        let sources_dir = temp_dir.path().join("sources");

        fs::create_dir_all(&project_dir).await?;
        fs::create_dir_all(&cache_dir).await?;
        fs::create_dir_all(&sources_dir).await?;

        Ok(Self {
            _temp_dir: temp_dir,
            project_dir,
            cache_dir,
            sources_dir,
        })
    }

    /// Get the project directory path
    pub fn project_path(&self) -> &Path {
        &self.project_dir
    }

    /// Get the cache directory path
    pub fn cache_path(&self) -> &Path {
        &self.cache_dir
    }

    /// Get the sources directory path
    pub fn sources_path(&self) -> &Path {
        &self.sources_dir
    }

    /// Write a manifest file to the project directory
    pub async fn write_manifest(&self, content: &str) -> Result<()> {
        let manifest_path = self.project_dir.join("agpm.toml");
        fs::write(&manifest_path, content)
            .await
            .with_context(|| format!("Failed to write manifest to {:?}", manifest_path))?;
        Ok(())
    }

    /// Write a lockfile to the project directory
    pub async fn write_lockfile(&self, content: &str) -> Result<()> {
        let lockfile_path = self.project_dir.join("agpm.lock");
        fs::write(&lockfile_path, content)
            .await
            .with_context(|| format!("Failed to write lockfile to {:?}", lockfile_path))?;
        Ok(())
    }

    /// Write a private manifest file (agpm.private.toml) to the project directory
    pub async fn write_private_manifest(&self, content: &str) -> Result<()> {
        let private_path = self.project_dir.join("agpm.private.toml");
        fs::write(&private_path, content)
            .await
            .with_context(|| format!("Failed to write private manifest to {:?}", private_path))?;
        Ok(())
    }

    /// Read the lockfile from the project directory
    pub async fn read_lockfile(&self) -> Result<String> {
        let lockfile_path = self.project_dir.join("agpm.lock");
        fs::read_to_string(&lockfile_path)
            .await
            .with_context(|| format!("Failed to read lockfile from {:?}", lockfile_path))
    }

    /// Load and parse the lockfile as a LockFile struct
    pub fn load_lockfile(&self) -> Result<LockFile> {
        let lockfile_path = self.project_dir.join("agpm.lock");
        LockFile::load(&lockfile_path)
    }

    /// Create a local resource file
    pub async fn create_local_resource(&self, path: &str, content: &str) -> Result<()> {
        let resource_path = self.project_dir.join(path);
        if let Some(parent) = resource_path.parent() {
            fs::create_dir_all(parent).await?;
        }
        fs::write(&resource_path, content).await?;
        Ok(())
    }

    /// Initialize a git repository inside the project directory
    pub fn init_git_repo(&self) -> Result<TestGit> {
        let git = TestGit::new(self.project_dir.clone());
        git.init()?;
        git.config_user()?;
        Ok(git)
    }

    /// Create a source repository with the given name
    pub async fn create_source_repo(&self, name: &str) -> Result<TestSourceRepo> {
        let source_dir = self.sources_dir.join(name);
        fs::create_dir_all(&source_dir).await?;

        let git = TestGit::new(&source_dir);
        git.init()?;
        git.config_user()?;

        Ok(TestSourceRepo {
            path: source_dir,
            git,
        })
    }

    /// Create a standard test repository with v1.0.0 tag
    ///
    /// This is a convenience method that creates a complete test repository
    /// with standard resources (agent, snippet, command) already tagged at v1.0.0.
    /// Returns both the repository and its bare file:// URL.
    ///
    /// This eliminates the most common test setup pattern (used 72+ times).
    ///
    /// # Arguments
    /// * `name` - The repository name
    ///
    /// # Returns
    /// A tuple of (TestSourceRepo, String) where the String is the bare file:// URL
    ///
    /// # Example
    /// ```rust
    /// let (repo, url) = project.create_standard_v1_repo("official").await?;
    /// // Repository is ready with v1.0.0 tag containing standard resources
    /// ```
    pub async fn create_standard_v1_repo(&self, name: &str) -> Result<(TestSourceRepo, String)> {
        let repo = self.create_source_repo(name).await?;
        repo.create_standard_resources().await?;
        repo.commit_all("Initial v1.0.0")?;
        repo.tag_version("v1.0.0")?;
        let url = repo.bare_file_url(self.sources_path()).await?;
        Ok((repo, url))
    }

    /// Run a AGPM command in the project directory
    pub fn run_agpm(&self, args: &[&str]) -> Result<CommandOutput> {
        self.run_agpm_with_env(args, &[])
    }

    /// Run a AGPM command with custom environment variables
    pub fn run_agpm_with_env(
        &self,
        args: &[&str],
        env_vars: &[(&str, &str)],
    ) -> Result<CommandOutput> {
        let agpm_binary = env!("CARGO_BIN_EXE_agpm");
        let mut cmd = Command::new(agpm_binary);

        cmd.args(args)
            .current_dir(&self.project_dir)
            .env("AGPM_CACHE_DIR", &self.cache_dir)
            .env("NO_COLOR", "1");

        // Add custom environment variables
        for (key, value) in env_vars {
            cmd.env(key, value);
        }

        let output = cmd.output().context("Failed to run agpm command")?;

        Ok(CommandOutput {
            stdout: String::from_utf8_lossy(&output.stdout).to_string(),
            stderr: String::from_utf8_lossy(&output.stderr).to_string(),
            success: output.status.success(),
            code: output.status.code(),
        })
    }

    /// Run a AGPM command asynchronously (can be cancelled by tokio timeout)
    ///
    /// Unlike `run_agpm()`, this uses `tokio::process::Command` so the operation
    /// can be properly cancelled by `tokio::time::timeout`. Use this for chaos
    /// tests that need deadlock detection via timeout.
    ///
    /// Debug logging is enabled via RUST_LOG to help diagnose deadlocks.
    pub async fn run_agpm_async(&self, args: &[&str]) -> Result<CommandOutput> {
        // Enable debug logging for lock tracing in spawned processes
        self.run_agpm_async_with_env(
            args,
            &[("RUST_LOG", "agpm_cli::debug=debug,agpm_cli::cache=debug")],
        )
        .await
    }

    /// Run a AGPM command asynchronously with custom environment variables
    ///
    /// Uses `kill_on_drop(true)` to ensure child processes are killed if the
    /// future is cancelled (e.g., by a timeout).
    pub async fn run_agpm_async_with_env(
        &self,
        args: &[&str],
        env_vars: &[(&str, &str)],
    ) -> Result<CommandOutput> {
        let agpm_binary = env!("CARGO_BIN_EXE_agpm");
        let mut cmd = tokio::process::Command::new(agpm_binary);

        cmd.args(args)
            .current_dir(&self.project_dir)
            .env("AGPM_CACHE_DIR", &self.cache_dir)
            .env("NO_COLOR", "1")
            // Prevent stdin inheritance which can cause hangs
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            // CRITICAL: Kill the child if the future is dropped (e.g., by timeout)
            .kill_on_drop(true);

        // Add custom environment variables
        for (key, value) in env_vars {
            cmd.env(key, value);
        }

        let child = cmd.spawn().context("Failed to spawn agpm command")?;
        let output = child.wait_with_output().await.context("Failed to wait for agpm command")?;

        Ok(CommandOutput {
            stdout: String::from_utf8_lossy(&output.stdout).to_string(),
            stderr: String::from_utf8_lossy(&output.stderr).to_string(),
            success: output.status.success(),
            code: output.status.code(),
        })
    }

    /// Run a AGPM command asynchronously with real-time streaming output.
    ///
    /// Unlike `run_agpm_async()`, this streams stdout/stderr line-by-line with
    /// a prefix for identification in concurrent test output. Returns only
    /// `ExitStatus` since output is streamed rather than captured.
    ///
    /// Use this for chaos tests where you need:
    /// - Real-time visibility into long-running operations
    /// - Prefixed output for interleaved concurrent processes
    /// - Timeout-based deadlock detection
    pub async fn run_agpm_async_streaming(
        &self,
        args: &[&str],
        prefix: &str,
    ) -> Result<ExitStatus> {
        self.run_agpm_async_streaming_with_env(args, prefix, &[]).await
    }

    /// Run a AGPM command asynchronously with streaming and custom env vars.
    pub async fn run_agpm_async_streaming_with_env(
        &self,
        args: &[&str],
        prefix: &str,
        env_vars: &[(&str, &str)],
    ) -> Result<ExitStatus> {
        let agpm_binary = env!("CARGO_BIN_EXE_agpm");

        let mut cmd = tokio::process::Command::new(agpm_binary);
        cmd.args(args)
            .current_dir(&self.project_dir)
            .env("AGPM_CACHE_DIR", &self.cache_dir)
            .env("NO_COLOR", "1")
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .kill_on_drop(true);

        for (key, value) in env_vars {
            cmd.env(key, value);
        }

        let mut child = cmd.spawn().context("Failed to spawn agpm command")?;

        let stdout = child.stdout.take().expect("stdout piped");
        let stderr = child.stderr.take().expect("stderr piped");

        let prefix_out = prefix.to_string();
        let prefix_err = prefix.to_string();

        // Spawn tasks to stream stdout and stderr with prefix
        let stdout_task = tokio::spawn(async move {
            let reader = BufReader::new(stdout);
            let mut lines = reader.lines();
            while let Ok(Some(line)) = lines.next_line().await {
                eprintln!("[{}:out] {}", prefix_out, line);
            }
        });

        let stderr_task = tokio::spawn(async move {
            let reader = BufReader::new(stderr);
            let mut lines = reader.lines();
            while let Ok(Some(line)) = lines.next_line().await {
                eprintln!("[{}:err] {}", prefix_err, line);
            }
        });

        // Wait for command to complete
        let status = child.wait().await.context("Failed to wait for agpm command")?;

        // Wait for output tasks to finish
        let _ = stdout_task.await;
        let _ = stderr_task.await;

        Ok(status)
    }
}

/// Run AGPM command asynchronously with streaming output (standalone version).
///
/// This is a standalone function for use in spawned tasks where TestProject
/// can't be borrowed. Use `TestProject::run_agpm_async_streaming` when possible.
pub async fn run_agpm_streaming(
    args: &[&str],
    prefix: &str,
    project_dir: &std::path::Path,
    cache_dir: &std::path::Path,
) -> Result<ExitStatus> {
    let agpm_binary = env!("CARGO_BIN_EXE_agpm");

    let mut cmd = tokio::process::Command::new(agpm_binary);
    cmd.args(args)
        .current_dir(project_dir)
        .env("AGPM_CACHE_DIR", cache_dir)
        .env("NO_COLOR", "1")
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .kill_on_drop(true);

    let mut child = cmd.spawn().context("Failed to spawn agpm command")?;

    let stdout = child.stdout.take().expect("stdout piped");
    let stderr = child.stderr.take().expect("stderr piped");

    let prefix_out = prefix.to_string();
    let prefix_err = prefix.to_string();

    // Spawn tasks to stream stdout and stderr with prefix
    let stdout_task = tokio::spawn(async move {
        let reader = BufReader::new(stdout);
        let mut lines = reader.lines();
        while let Ok(Some(line)) = lines.next_line().await {
            eprintln!("[{}:out] {}", prefix_out, line);
        }
    });

    let stderr_task = tokio::spawn(async move {
        let reader = BufReader::new(stderr);
        let mut lines = reader.lines();
        while let Ok(Some(line)) = lines.next_line().await {
            eprintln!("[{}:err] {}", prefix_err, line);
        }
    });

    // Wait for command to complete
    let status = child.wait().await.context("Failed to wait for agpm command")?;

    // Wait for output tasks to finish
    let _ = stdout_task.await;
    let _ = stderr_task.await;

    Ok(status)
}

/// Test source repository helper
pub struct TestSourceRepo {
    pub path: PathBuf,
    pub git: TestGit,
}

impl TestSourceRepo {
    /// Add a resource file to the repository
    pub async fn add_resource(&self, resource_type: &str, name: &str, content: &str) -> Result<()> {
        let resource_dir = self.path.join(resource_type);
        fs::create_dir_all(&resource_dir).await?;

        let file_path = resource_dir.join(format!("{}.md", name));

        // Create parent directories if the name contains slashes
        if let Some(parent) = file_path.parent() {
            fs::create_dir_all(parent).await?;
        }

        fs::write(&file_path, content).await?;
        Ok(())
    }

    /// Create a skill directory with a SKILL.md file
    ///
    /// Skills are directory-based resources that contain a SKILL.md file.
    ///
    /// # Arguments
    /// * `name` - The skill directory name
    /// * `content` - The content for SKILL.md
    ///
    /// # Example
    /// ```rust
    /// repo.create_skill("my-skill", r#"---
    /// name: My Skill
    /// description: A test skill
    /// ---
    /// # My Skill
    /// "#).await?;
    /// ```
    pub async fn create_skill(&self, name: &str, content: &str) -> Result<()> {
        let skill_dir = self.path.join("skills").join(name);
        fs::create_dir_all(&skill_dir).await?;

        let skill_md_path = skill_dir.join("SKILL.md");
        fs::write(&skill_md_path, content).await?;
        Ok(())
    }

    /// Create a file at an arbitrary path within the repository
    ///
    /// # Arguments
    /// * `path` - Relative path from the repository root
    /// * `content` - The file content
    ///
    /// # Example
    /// ```rust
    /// repo.create_file("snippets/utils.md", "# Utils").await?;
    /// ```
    pub async fn create_file(&self, path: &str, content: &str) -> Result<()> {
        let file_path = self.path.join(path);

        // Create parent directories if needed
        if let Some(parent) = file_path.parent() {
            fs::create_dir_all(parent).await?;
        }

        fs::write(&file_path, content).await?;
        Ok(())
    }

    /// Create standard test resources
    pub async fn create_standard_resources(&self) -> Result<()> {
        self.add_resource("agents", "test-agent", "# Test Agent\n\nA test agent").await?;
        self.add_resource("snippets", "test-snippet", "# Test Snippet\n\nA test snippet").await?;
        self.add_resource("commands", "test-command", "# Test Command\n\nA test command").await?;
        Ok(())
    }

    /// Add multiple sequential resources with auto-generated content
    ///
    /// Creates resources named `{prefix}-{i:02}` (e.g., "agent-00", "agent-01")
    /// with generic test content. Useful for stress tests and parallelism tests.
    ///
    /// # Arguments
    /// * `resource_type` - The resource directory (e.g., "agents", "snippets")
    /// * `prefix` - Name prefix for resources (e.g., "agent", "snippet")
    /// * `count` - Number of resources to create
    ///
    /// # Example
    /// ```rust
    /// repo.add_sequential_resources("agents", "test-agent", 10).await?;
    /// // Creates: agents/test-agent-00.md through agents/test-agent-09.md
    /// ```
    pub async fn add_sequential_resources(
        &self,
        resource_type: &str,
        prefix: &str,
        count: usize,
    ) -> Result<()> {
        for i in 0..count {
            let name = format!("{}-{:02}", prefix, i);
            let title = prefix
                .split('-')
                .map(|word| {
                    let mut chars = word.chars();
                    match chars.next() {
                        None => String::new(),
                        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
                    }
                })
                .collect::<Vec<_>>()
                .join(" ");
            let content = format!("# {} {:02}\n\nTest {} {}", title, i, resource_type, i);
            self.add_resource(resource_type, &name, &content).await?;
        }
        Ok(())
    }

    /// Commit all changes with a message
    pub fn commit_all(&self, message: &str) -> Result<()> {
        self.git.add_all()?;
        self.git.commit(message)?;
        Ok(())
    }

    /// Create a version tag
    pub fn tag_version(&self, version: &str) -> Result<()> {
        self.git.tag(version)?;
        Ok(())
    }

    /// Create multiple version tags for performance testing
    ///
    /// Creates sequential version tags (v1.0.0, v2.0.0, etc.) with
    /// separate commits for each tag. Useful for testing tag caching performance.
    ///
    /// # Arguments
    /// * `count` - Number of tags to create (creates v1.0.0 through v{count}.0.0)
    ///
    /// # Example
    /// ```rust
    /// repo.create_multiple_tags(100)?;  // Creates v1.0.0 through v100.0.0
    /// ```
    pub fn create_multiple_tags(&self, count: usize) -> Result<()> {
        for i in 1..=count {
            let version = format!("v{}.0.0", i);

            // Update content for each version
            let content = format!("# Test Repository\n\nVersion {}", version);
            let readme_path = self.path.join("README.md");
            std::fs::write(&readme_path, content)?;

            // Commit the change
            self.commit_all(&format!("Version {}", version))?;

            // Create the tag
            self.tag_version(&version)?;
        }
        Ok(())
    }

    /// Get the file:// URL for this repository
    pub fn file_url(&self) -> String {
        format!("file://{}", normalize_path_for_storage(&self.path))
    }

    /// Clone this repository to a bare repository for reliable serving
    /// Returns the path to the new bare repository
    pub async fn to_bare_repo(&self, target_path: &Path) -> Result<PathBuf> {
        let output = Command::new("git")
            .args(["clone", "--bare", self.path.to_str().unwrap(), target_path.to_str().unwrap()])
            .output()
            .context("Failed to create bare repository")?;

        if !output.status.success() {
            return Err(anyhow::anyhow!(
                "Failed to create bare repository: {}",
                String::from_utf8_lossy(&output.stderr)
            ));
        }

        // Verify the bare repository is accessible before returning.
        // Uses tokio_retry with exponential backoff for filesystem coherency.
        // Most operations complete on the first attempt; retries handle delays from
        // AV scanning (Windows) or high I/O load (any platform).
        let head_path = target_path.join("HEAD");
        let strategy = ExponentialBackoff::from_millis(10)
            .max_delay(std::time::Duration::from_millis(50))
            .take(5);

        let _ = Retry::spawn(strategy, || {
            let path = head_path.clone();
            async move { tokio::fs::read_to_string(&path).await.map_err(|e| e.to_string()) }
        })
        .await;
        // Don't fail if HEAD isn't readable - the repo was created successfully

        Ok(target_path.to_path_buf())
    }

    /// Get a file:// URL for a bare clone of this repository
    /// Creates the bare repo in the parent's sources directory
    ///
    /// # Implementation Note
    /// Automatically ensures the repository is on the 'main' branch before creating
    /// the bare clone. This prevents "rev-parse: HEAD" errors in CI environments
    /// where bare repositories need a valid default branch reference.
    pub async fn bare_file_url(&self, sources_dir: &Path) -> Result<String> {
        // Ensure we're on a proper branch before creating bare clone
        // This is critical for bare repositories to have a valid HEAD reference
        self.git.ensure_branch("main")?;

        let bare_name =
            format!("{}.git", self.path.file_name().and_then(|n| n.to_str()).unwrap_or("repo"));
        let bare_path = sources_dir.join(bare_name);
        self.to_bare_repo(&bare_path).await?;
        Ok(format!("file://{}", normalize_path_for_storage(&bare_path)))
    }
}

/// Command output helper
pub struct CommandOutput {
    pub stdout: String,
    pub stderr: String,
    pub success: bool,
    pub code: Option<i32>,
}

impl CommandOutput {
    /// Assert the command succeeded
    pub fn assert_success(&self) -> &Self {
        assert!(self.success, "Command failed with code {:?}\nStderr: {}", self.code, self.stderr);
        self
    }

    /// Assert stdout contains the given text
    pub fn assert_stdout_contains(&self, text: &str) -> &Self {
        assert!(
            self.stdout.contains(text),
            "Expected stdout to contain '{}'\nActual stdout: {}",
            text,
            self.stdout
        );
        self
    }
}

/// File assertion helpers
pub struct FileAssert;

impl FileAssert {
    /// Assert a file exists
    pub async fn exists(path: impl AsRef<Path>) {
        let path = path.as_ref();
        let exists = fs::metadata(path).await.is_ok();
        assert!(exists, "Expected file to exist: {}", path.display());
    }

    /// Assert a file does not exist
    pub async fn not_exists(path: impl AsRef<Path>) {
        let path = path.as_ref();
        let exists = fs::metadata(path).await.is_ok();
        assert!(!exists, "Expected file to not exist: {}", path.display());
    }

    /// Assert a file contains specific content
    pub async fn contains(path: impl AsRef<Path>, expected: &str) {
        let path = path.as_ref();
        let content = fs::read_to_string(path)
            .await
            .unwrap_or_else(|e| panic!("Failed to read file {}: {}", path.display(), e));
        assert!(
            content.contains(expected),
            "Expected file {} to contain '{}'\nActual content: {}",
            path.display(),
            expected,
            content
        );
    }

    /// Assert a file has exact content
    pub async fn equals(path: impl AsRef<Path>, expected: &str) {
        let path = path.as_ref();
        let content = fs::read_to_string(path)
            .await
            .unwrap_or_else(|e| panic!("Failed to read file {}: {}", path.display(), e));
        assert_eq!(content, expected, "File {} content mismatch", path.display());
    }
}

/// Directory assertion helpers
pub struct DirAssert;

impl DirAssert {
    /// Assert a directory exists
    pub async fn exists(path: impl AsRef<Path>) {
        let path = path.as_ref();
        let metadata = fs::metadata(path).await;
        let is_dir = metadata.map(|m| m.is_dir()).unwrap_or(false);
        assert!(is_dir, "Expected directory to exist: {}", path.display());
    }

    /// Assert a directory contains a file
    pub async fn contains_file(dir: impl AsRef<Path>, file_name: &str) {
        let path = dir.as_ref().join(file_name);
        let exists = fs::metadata(&path).await.is_ok();
        assert!(
            exists,
            "Expected directory {} to contain file '{}'",
            dir.as_ref().display(),
            file_name
        );
    }

    /// Assert a directory is empty
    pub async fn is_empty(path: impl AsRef<Path>) {
        let path = path.as_ref();
        let mut read_dir = fs::read_dir(path)
            .await
            .unwrap_or_else(|e| panic!("Failed to read directory {}: {}", path.display(), e));

        let mut count = 0;
        while read_dir.next_entry().await.unwrap().is_some() {
            count += 1;
        }

        assert_eq!(
            count,
            0,
            "Expected directory {} to be empty, but it contains {} entries",
            path.display(),
            count
        );
    }
}