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
//! Resource abstractions for AGPM
//!
//! This module defines the core resource types and management traits that form the foundation
//! of AGPM's resource system. Resources are the fundamental units that AGPM manages, installs,
//! and tracks across different source repositories.
//!
//! # Resource Model
//!
//! AGPM supports different types of resources, each with specific characteristics:
//! - **Agents**: AI assistant configurations and prompts
//! - **Snippets**: Reusable code templates and examples
//! - **Commands**: Slash commands for AI assistants
//! - **Scripts**: Executable scripts for automation
//! - **Hooks**: Event hooks for AI assistant lifecycles
//! - **MCP Servers**: Model Context Protocol server configurations
//! - **Skills**: Directory-based resources containing SKILL.md and supporting files
//!
//! Most resources are distributed as markdown files (.md) that may contain frontmatter metadata
//! for configuration and dependency information. Skills are unique in being directory-based
//! with a required SKILL.md file and optional supporting files.
//!
//! # Core Types
//!
//! - [`ResourceType`] - Enumeration of supported resource types
//! - [`Resource`] - Trait defining the interface for all resource types
//!
//! # Resource Management
//!
//! Resources are defined in the project's `agpm.toml` file and installed to specific
//! directories based on their type. Scripts and hooks have special handling for
//! Claude Code integration.
//!
//! # Examples
//!
//! ## Working with Resource Types
//!
//! ```rust,no_run
//! use agpm_cli::core::ResourceType;
//! use std::path::Path;
//!
//! // Convert strings to resource types
//! let agent_type: ResourceType = "agent".parse().unwrap();
//! let snippet_type: ResourceType = "snippet".parse().unwrap();
//! let script_type: ResourceType = "script".parse().unwrap();
//! let hook_type: ResourceType = "hook".parse().unwrap();
//!
//! // Get default directory names
//! assert_eq!(agent_type.default_directory(), Some(".claude/agents"));
//! assert_eq!(snippet_type.default_directory(), Some(".claude/snippets"));
//! assert_eq!(script_type.default_directory(), Some(".claude/scripts"));
//! assert_eq!(hook_type.default_directory(), None); // Hooks merged into config, not staged
//! ```
//!
//! ## Serialization Support
//!
//! ```rust,no_run
//! use agpm_cli::core::ResourceType;
//!
//! // ResourceType implements Serialize/Deserialize
//! let agent = ResourceType::Agent;
//! let json = serde_json::to_string(&agent).unwrap();
//! assert_eq!(json, "\"agent\"");
//!
//! let deserialized: ResourceType = serde_json::from_str(&json).unwrap();
//! assert_eq!(deserialized, ResourceType::Agent);
//! ```

use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::path::Path;

/// Enumeration of supported resource types in AGPM
///
/// This enum defines the different categories of resources that AGPM can manage.
/// Each resource type has specific characteristics, installation paths, and
/// manifest file requirements.
///
/// # Serialization
///
/// `ResourceType` implements [`serde::Serialize`] and [`serde::Deserialize`]
/// using lowercase string representations ("agent", "snippet") for JSON/TOML
/// compatibility.
///
/// # Resource Type Characteristics
///
/// ## Agent
/// - **Purpose**: AI assistant configurations, prompts, and behavioral definitions
/// - **Default Directory**: `.claude/agents`
/// - **Common Use Cases**: Claude Code agents, custom AI assistants, specialized prompts
///
/// ## Snippet
/// - **Purpose**: Reusable code templates, examples, and documentation fragments
/// - **Default Directory**: `.claude/snippets`
/// - **Common Use Cases**: Code templates, configuration examples, documentation
///
/// ## Script
/// - **Purpose**: Executable files that can be run by hooks or independently
/// - **Default Directory**: `.claude/scripts`
/// - **Common Use Cases**: Validation scripts, automation tools, hook executables
///
/// ## Hook
/// - **Purpose**: Event-based automation configurations for Claude Code
/// - **Staging**: Merged into `.claude/settings.local.json`, not staged to disk
/// - **Common Use Cases**: Pre/Post tool use validation, custom event handlers
///
/// # Examples
///
/// ## Basic Usage
///
/// ```rust,no_run
/// use agpm_cli::core::ResourceType;
///
/// let agent = ResourceType::Agent;
/// let snippet = ResourceType::Snippet;
///
/// assert_eq!(agent.to_string(), "agent");
/// assert_eq!(snippet.to_string(), "snippet");
/// ```
///
/// ## String Parsing
///
/// ```rust,no_run
/// use agpm_cli::core::ResourceType;
/// use std::str::FromStr;
///
/// let agent: ResourceType = "agent".parse().unwrap();
/// let snippet: ResourceType = "SNIPPET".parse().unwrap(); // Case insensitive
///
/// assert_eq!(agent, ResourceType::Agent);
/// assert_eq!(snippet, ResourceType::Snippet);
///
/// // Invalid resource type
/// assert!("invalid".parse::<ResourceType>().is_err());
/// ```
///
/// ## Directory Names
///
/// ```rust,no_run
/// use agpm_cli::core::ResourceType;
///
/// let agent = ResourceType::Agent;
/// assert_eq!(agent.default_directory(), Some(".claude/agents"));
///
/// let snippet = ResourceType::Snippet;
/// assert_eq!(snippet.default_directory(), Some(".claude/snippets"));
///
/// let script = ResourceType::Script;
/// assert_eq!(script.default_directory(), Some(".claude/scripts"));
/// ```
///
/// ## JSON Serialization
///
/// ```rust,no_run
/// use agpm_cli::core::ResourceType;
///
/// let agent = ResourceType::Agent;
/// let json = serde_json::to_string(&agent).unwrap();
/// assert_eq!(json, "\"agent\"");
///
/// let parsed: ResourceType = serde_json::from_str("\"snippet\"").unwrap();
/// assert_eq!(parsed, ResourceType::Snippet);
/// ```
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default,
)]
#[serde(rename_all = "lowercase")]
pub enum ResourceType {
    /// AI assistant configurations and prompts
    ///
    /// Agents define AI assistant behavior, including system prompts, specialized
    /// capabilities, and configuration parameters. They are typically stored as
    /// markdown files with frontmatter containing metadata.
    Agent,

    /// Reusable code templates and examples
    ///
    /// Snippets contain reusable code fragments, configuration examples, or
    /// documentation templates that can be shared across projects.
    #[default]
    Snippet,

    /// Claude Code commands
    ///
    /// Commands define custom slash commands that can be used within Claude Code
    /// to perform specific actions or automate workflows.
    Command,

    /// MCP (Model Context Protocol) servers
    ///
    /// MCP servers provide integrations with external systems and services,
    /// allowing Claude Code to access databases, APIs, and other tools.
    #[serde(rename = "mcp-server")]
    McpServer,

    /// Executable script files
    ///
    /// Scripts are executable files (.sh, .js, .py, etc.) that can be referenced
    /// by hooks or run independently. They are installed to .claude/scripts/
    Script,

    /// Hook configuration files
    ///
    /// Hooks define event-based automation in Claude Code. They are JSON files
    /// that configure scripts to run at specific events (`PreToolUse`, `PostToolUse`, etc.)
    /// and are merged into settings.local.json
    Hook,

    /// Claude Skills - directory-based resources
    ///
    /// Skills are directory-based resources (unlike single-file agents/snippets)
    /// that contain a `SKILL.md` file plus supporting files (scripts, templates,
    /// examples). They are installed to `.claude/skills/<name>/` as complete
    /// directory structures.
    Skill,
}

impl ResourceType {
    /// Get all resource types in a consistent order
    ///
    /// Returns an array containing all `ResourceType` variants. This is useful
    /// for iterating over all resource types when processing manifests, lockfiles,
    /// or performing batch operations.
    ///
    /// The order is guaranteed to be stable: Agent, Snippet, Command, `McpServer`, Script, Hook, Skill
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::core::ResourceType;
    ///
    /// // Iterate over all resource types
    /// for resource_type in ResourceType::all() {
    ///     println!("Processing {}", resource_type);
    /// }
    ///
    /// // Count total resource types
    /// assert_eq!(ResourceType::all().len(), 7);
    /// ```
    pub const fn all() -> &'static [Self] {
        &[
            Self::Agent,
            Self::Snippet,
            Self::Command,
            Self::McpServer,
            Self::Script,
            Self::Hook,
            Self::Skill,
        ]
    }

    /// Get the plural form of the resource type.
    ///
    /// Returns the plural form used in lockfile dependency references and TOML sections.
    ///
    /// # Examples
    ///
    /// ```
    /// use agpm_cli::core::ResourceType;
    ///
    /// assert_eq!(ResourceType::Agent.to_plural(), "agents");
    /// assert_eq!(ResourceType::McpServer.to_plural(), "mcp-servers");
    /// ```
    pub const fn to_plural(&self) -> &'static str {
        match self {
            Self::Agent => "agents",
            Self::Snippet => "snippets",
            Self::Command => "commands",
            Self::Script => "scripts",
            Self::Hook => "hooks",
            Self::McpServer => "mcp-servers",
            Self::Skill => "skills",
        }
    }

    /// Get the default installation directory name for this resource type
    ///
    /// Returns the conventional directory name where resources of this type
    /// are typically installed in AGPM projects.
    ///
    /// # Returns
    ///
    /// - [`Agent`] → `Some(".claude/agents")`
    /// - [`Snippet`] → `Some(".claude/snippets")`
    /// - [`Command`] → `Some(".claude/commands")`
    /// - [`McpServer`] → `None` (merged into `.mcp.json`, not staged to disk)
    /// - [`Script`] → `Some(".claude/scripts")`
    /// - [`Hook`] → `None` (merged into `.claude/settings.local.json`, not staged to disk)
    /// - [`Skill`] → `Some(".claude/skills")`
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::core::ResourceType;
    ///
    /// assert_eq!(ResourceType::Agent.default_directory(), Some(".claude/agents"));
    /// assert_eq!(ResourceType::Snippet.default_directory(), Some(".claude/snippets"));
    /// assert_eq!(ResourceType::Command.default_directory(), Some(".claude/commands"));
    /// assert_eq!(ResourceType::Script.default_directory(), Some(".claude/scripts"));
    /// // Hook and McpServer return None as they don't stage to disk
    /// assert_eq!(ResourceType::Hook.default_directory(), None);
    /// assert_eq!(ResourceType::McpServer.default_directory(), None);
    /// ```
    ///
    /// # Note
    ///
    /// This is just the default convention. Users can install resources to any
    /// directory by specifying custom paths in their manifest files.
    ///
    /// [`Agent`]: ResourceType::Agent
    /// [`Snippet`]: ResourceType::Snippet
    /// [`Command`]: ResourceType::Command
    /// [`McpServer`]: ResourceType::McpServer
    /// [`Script`]: ResourceType::Script
    /// [`Hook`]: ResourceType::Hook
    /// [`Skill`]: ResourceType::Skill
    #[must_use]
    pub const fn default_directory(&self) -> Option<&str> {
        match self {
            Self::Agent => Some(".claude/agents"),
            Self::Snippet => Some(".claude/snippets"),
            Self::Command => Some(".claude/commands"),
            Self::McpServer => None, // Merged into .mcp.json, not staged to disk
            Self::Script => Some(".claude/scripts"),
            Self::Hook => None, // Merged into .claude/settings.local.json, not staged to disk
            Self::Skill => Some(".claude/skills"),
        }
    }

    /// Parse a resource type from frontmatter dependency declaration.
    ///
    /// Accepts both singular and plural forms (e.g., "agent" or "agents").
    /// This is specifically designed for parsing dependency declarations in
    /// resource frontmatter where users may specify either form.
    ///
    /// # Arguments
    ///
    /// * `s` - The string from frontmatter (e.g., "agents", "snippet")
    ///
    /// # Returns
    ///
    /// The corresponding ResourceType, or None if not recognized.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use agpm_cli::core::ResourceType;
    ///
    /// assert_eq!(ResourceType::from_frontmatter_str("agents"), Some(ResourceType::Agent));
    /// assert_eq!(ResourceType::from_frontmatter_str("agent"), Some(ResourceType::Agent));
    /// assert_eq!(ResourceType::from_frontmatter_str("snippets"), Some(ResourceType::Snippet));
    /// assert_eq!(ResourceType::from_frontmatter_str("snippet"), Some(ResourceType::Snippet));
    /// assert_eq!(ResourceType::from_frontmatter_str("commands"), Some(ResourceType::Command));
    /// assert_eq!(ResourceType::from_frontmatter_str("command"), Some(ResourceType::Command));
    /// assert_eq!(ResourceType::from_frontmatter_str("scripts"), Some(ResourceType::Script));
    /// assert_eq!(ResourceType::from_frontmatter_str("script"), Some(ResourceType::Script));
    /// assert_eq!(ResourceType::from_frontmatter_str("hooks"), Some(ResourceType::Hook));
    /// assert_eq!(ResourceType::from_frontmatter_str("hook"), Some(ResourceType::Hook));
    /// assert_eq!(ResourceType::from_frontmatter_str("mcp-servers"), Some(ResourceType::McpServer));
    /// assert_eq!(ResourceType::from_frontmatter_str("mcp-server"), Some(ResourceType::McpServer));
    /// assert_eq!(ResourceType::from_frontmatter_str("unknown"), None);
    /// ```
    pub fn from_frontmatter_str(s: &str) -> Option<Self> {
        match s {
            "agents" | "agent" => Some(ResourceType::Agent),
            "snippets" | "snippet" => Some(ResourceType::Snippet),
            "commands" | "command" => Some(ResourceType::Command),
            "hooks" | "hook" => Some(ResourceType::Hook),
            "scripts" | "script" => Some(ResourceType::Script),
            "mcp-servers" | "mcp-server" => Some(ResourceType::McpServer),
            "skills" | "skill" => Some(ResourceType::Skill),
            _ => None,
        }
    }

    /// Get the default tool for this resource type.
    ///
    /// Returns the default tool that should be used when no explicit tool is specified
    /// in the dependency configuration. Different resource types have different defaults:
    ///
    /// - Most resources default to "claude-code"
    /// - Snippets default to "agpm" (shared infrastructure across tools)
    ///
    /// # Returns
    ///
    /// - [`ResourceType::Agent`] → `"claude-code"`
    /// - [`ResourceType::Snippet`] → `"agpm"` (shared infrastructure)
    /// - [`ResourceType::Command`] → `"claude-code"`
    /// - [`ResourceType::McpServer`] → `"claude-code"`
    /// - [`ResourceType::Script`] → `"claude-code"`
    /// - [`ResourceType::Hook`] → `"claude-code"`
    /// - [`ResourceType::Skill`] → `"claude-code"`
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::core::ResourceType;
    ///
    /// assert_eq!(ResourceType::Agent.default_tool(), "claude-code");
    /// assert_eq!(ResourceType::Snippet.default_tool(), "agpm");
    /// assert_eq!(ResourceType::Command.default_tool(), "claude-code");
    /// ```
    ///
    /// # Rationale
    ///
    /// Snippets are designed to be shared content across multiple tools (Claude Code,
    /// OpenCode, etc.). The `.agpm/snippets/` location provides shared infrastructure
    /// that can be referenced by resources from different tools. Therefore, snippets
    /// default to the "agpm" tool type.
    ///
    /// Users can still explicitly set `tool = "claude-code"` for a snippet if they want
    /// it installed to `.claude/snippets/` instead.
    #[must_use]
    pub const fn default_tool(&self) -> &'static str {
        match self {
            Self::Snippet => "agpm", // Snippets use shared infrastructure
            _ => "claude-code",      // All other resources default to claude-code
        }
    }
}

impl std::fmt::Display for ResourceType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Agent => write!(f, "agent"),
            Self::Snippet => write!(f, "snippet"),
            Self::Command => write!(f, "command"),
            Self::McpServer => write!(f, "mcp-server"),
            Self::Script => write!(f, "script"),
            Self::Hook => write!(f, "hook"),
            Self::Skill => write!(f, "skill"),
        }
    }
}

impl std::str::FromStr for ResourceType {
    type Err = crate::core::AgpmError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "agent" | "agents" => Ok(Self::Agent),
            "snippet" | "snippets" => Ok(Self::Snippet),
            "command" | "commands" => Ok(Self::Command),
            "mcp-server" | "mcp-servers" | "mcpserver" | "mcp" => Ok(Self::McpServer),
            "script" | "scripts" => Ok(Self::Script),
            "hook" | "hooks" => Ok(Self::Hook),
            "skill" | "skills" => Ok(Self::Skill),
            _ => Err(crate::core::AgpmError::InvalidResourceType {
                resource_type: s.to_string(),
            }),
        }
    }
}

/// Base trait defining the interface for all AGPM resources
///
/// This trait provides a common interface for different types of resources (agents, snippets)
/// managed by AGPM. It abstracts the core operations that can be performed on any resource,
/// including validation, installation, and metadata access.
///
/// # Design Principles
///
/// - **Type Safety**: Each resource has a specific [`ResourceType`]
/// - **Validation**: Resources can validate their own structure and dependencies
/// - **Installation**: Resources know how to install themselves to target locations
/// - **Metadata**: Resources provide structured metadata for tooling and display
/// - **Flexibility**: Resources can be profiled or configured during installation
///
/// # Implementation Requirements
///
/// Implementors of this trait should:
/// - Provide meaningful error messages in validation failures
/// - Support atomic installation operations (no partial installs on failure)
/// - Generate deterministic installation paths
/// - Include rich metadata for resource discovery and management
///
/// # Examples
///
/// ## Basic Resource Usage Pattern
///
/// ```rust,no_run
/// use agpm_cli::core::{Resource, ResourceType};
/// use anyhow::Result;
/// use std::path::Path;
///
/// fn process_resource(resource: &dyn Resource) -> Result<()> {
///     // Get basic information
///     println!("Processing resource: {}", resource.name());
///     println!("Type: {}", resource.resource_type());
///     
///     if let Some(description) = resource.description() {
///         println!("Description: {}", description);
///     }
///     
///     // Validate the resource
///     resource.validate()?;
///     
///     // Install to default location
///     let target = Path::new("./resources");
///     let install_path = resource.install_path(target);
///     resource.install(&install_path, None)?;
///     
///     Ok(())
/// }
/// ```
///
/// ## Metadata Extraction
///
/// ```rust,no_run
/// use agpm_cli::core::Resource;
/// use anyhow::Result;
///
/// fn extract_metadata(resource: &dyn Resource) -> Result<()> {
///     let metadata = resource.metadata()?;
///     
///     // Metadata is JSON Value for flexibility
///     if let Some(version) = metadata.get("version") {
///         println!("Resource version: {}", version);
///     }
///     
///     if let Some(tags) = metadata.get("tags").and_then(|t| t.as_array()) {
///         println!("Tags: {:?}", tags);
///     }
///     
///     Ok(())
/// }
/// ```
///
/// # Trait Object Usage
///
/// The trait is object-safe and can be used as a trait object:
///
/// ```rust,no_run
/// use agpm_cli::core::Resource;
/// use std::any::Any;
///
/// fn handle_resource(resource: Box<dyn Resource>) {
///     println!("Handling resource: {}", resource.name());
///     
///     // Can be downcasted to concrete types if needed
///     let any = resource.as_any();
///     // ... downcasting logic
/// }
/// ```
pub trait Resource {
    /// Get the unique name identifier for this resource
    ///
    /// The name is used to identify the resource in manifests, lockfiles,
    /// and CLI operations. It should be unique within a project's namespace.
    ///
    /// # Returns
    ///
    /// A string slice containing the resource name
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::core::Resource;
    ///
    /// fn print_resource_info(resource: &dyn Resource) {
    ///     println!("Resource name: {}", resource.name());
    /// }
    /// ```
    fn name(&self) -> &str;

    /// Get the resource type classification
    ///
    /// Returns the [`ResourceType`] enum value that identifies what kind of
    /// resource this is (Agent, Snippet, etc.).
    ///
    /// # Returns
    ///
    /// The [`ResourceType`] for this resource
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::core::{Resource, ResourceType};
    ///
    /// fn categorize_resource(resource: &dyn Resource) {
    ///     match resource.resource_type() {
    ///         ResourceType::Agent => println!("This is an AI agent"),
    ///         ResourceType::Snippet => println!("This is a code snippet"),
    ///         ResourceType::Command => println!("This is a Claude Code command"),
    ///         ResourceType::McpServer => println!("This is an MCP server"),
    ///         ResourceType::Script => println!("This is an executable script"),
    ///         ResourceType::Hook => println!("This is a hook configuration"),
    ///         ResourceType::Skill => println!("This is a Claude Skill"),
    ///     }
    /// }
    /// ```
    fn resource_type(&self) -> ResourceType;

    /// Get the human-readable description of this resource
    ///
    /// Returns an optional description that explains what the resource does
    /// or how it should be used. This is typically displayed in resource
    /// listings and help text.
    ///
    /// # Returns
    ///
    /// - `Some(description)` if the resource has a description
    /// - `None` if no description is available
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::core::Resource;
    ///
    /// fn show_resource_details(resource: &dyn Resource) {
    ///     println!("Name: {}", resource.name());
    ///     if let Some(desc) = resource.description() {
    ///         println!("Description: {}", desc);
    ///     } else {
    ///         println!("No description available");
    ///     }
    /// }
    /// ```
    fn description(&self) -> Option<&str>;

    /// Validate the resource structure and content
    ///
    /// Performs comprehensive validation of the resource including:
    /// - File structure integrity
    /// - Content format validation
    /// - Dependency constraint checking
    /// - Metadata consistency
    ///
    /// # Returns
    ///
    /// - `Ok(())` if the resource is valid
    /// - `Err(error)` with detailed validation failure information
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::core::Resource;
    /// use anyhow::Result;
    ///
    /// fn validate_before_install(resource: &dyn Resource) -> Result<()> {
    ///     resource.validate()
    ///         .map_err(|e| anyhow::anyhow!("Resource validation failed: {}", e))?;
    ///     
    ///     println!("Resource {} is valid", resource.name());
    ///     Ok(())
    /// }
    /// ```
    fn validate(&self) -> Result<()>;

    /// Install the resource to the specified target path
    ///
    /// Performs the actual installation of the resource files to the target
    /// location. This operation should be atomic - either it succeeds completely
    /// or fails without making any changes.
    ///
    /// # Arguments
    ///
    /// * `target` - The directory path where the resource should be installed
    /// * `profile` - Optional profile name for customized installation (may be unused)
    ///
    /// # Returns
    ///
    /// - `Ok(())` if installation succeeds
    /// - `Err(error)` if installation fails with detailed error information
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::core::Resource;
    /// use std::path::Path;
    /// use anyhow::Result;
    ///
    /// fn install_resource(resource: &dyn Resource) -> Result<()> {
    ///     let target = Path::new("./installed-resources");
    ///     
    ///     // Validate first
    ///     resource.validate()?;
    ///     
    ///     // Install without profile
    ///     resource.install(target, None)?;
    ///     
    ///     println!("Successfully installed {}", resource.name());
    ///     Ok(())
    /// }
    /// ```
    fn install(&self, target: &Path, profile: Option<&str>) -> Result<()>;

    /// Calculate the installation path for this resource
    ///
    /// Determines where this resource would be installed relative to a base
    /// directory. This is used for path planning and conflict detection.
    ///
    /// # Arguments
    ///
    /// * `base` - The base directory for installation
    ///
    /// # Returns
    ///
    /// The full path where this resource would be installed
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::core::Resource;
    /// use std::path::Path;
    ///
    /// fn check_install_location(resource: &dyn Resource) {
    ///     let base = Path::new("/project/resources");
    ///     let install_path = resource.install_path(base);
    ///     
    ///     println!("{} would be installed to: {}",
    ///         resource.name(),
    ///         install_path.display()
    ///     );
    /// }
    /// ```
    fn install_path(&self, base: &Path) -> std::path::PathBuf;

    /// Get structured metadata for this resource as JSON
    ///
    /// Returns resource metadata in a flexible JSON format that can include
    /// version information, tags, author details, and other custom fields.
    /// This metadata is used for resource discovery, filtering, and display.
    ///
    /// # Returns
    ///
    /// - `Ok(json_value)` containing the metadata
    /// - `Err(error)` if metadata cannot be generated or parsed
    ///
    /// # Metadata Structure
    ///
    /// While flexible, metadata typically includes:
    /// - `name`: Resource name
    /// - `type`: Resource type
    /// - `version`: Version information
    /// - `description`: Human-readable description
    /// - `tags`: Array of classification tags
    /// - `dependencies`: Dependency information
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::core::Resource;
    /// use anyhow::Result;
    ///
    /// fn show_resource_metadata(resource: &dyn Resource) -> Result<()> {
    ///     let metadata = resource.metadata()?;
    ///     
    ///     if let Some(version) = metadata.get("version") {
    ///         println!("Version: {}", version);
    ///     }
    ///     
    ///     if let Some(tags) = metadata.get("tags").and_then(|t| t.as_array()) {
    ///         print!("Tags: ");
    ///         for tag in tags {
    ///             print!("{} ", tag.as_str().unwrap_or("?"));
    ///         }
    ///         println!();
    ///     }
    ///     
    ///     Ok(())
    /// }
    /// ```
    fn metadata(&self) -> Result<serde_json::Value>;

    /// Get a reference to this resource as [`std::any::Any`] for downcasting
    ///
    /// This method enables downcasting from the [`Resource`] trait object to
    /// concrete resource implementations when needed for type-specific operations.
    ///
    /// # Returns
    ///
    /// A reference to this resource as [`std::any::Any`]
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::core::Resource;
    /// use std::any::Any;
    ///
    /// // Hypothetical concrete resource type
    /// struct MyAgent {
    ///     name: String,
    ///     // ... other fields
    /// }
    ///
    /// fn try_downcast_to_agent(resource: &dyn Resource) {
    ///     let any = resource.as_any();
    ///     
    ///     if let Some(agent) = any.downcast_ref::<MyAgent>() {
    ///         println!("Successfully downcasted to MyAgent: {}", agent.name);
    ///     } else {
    ///         println!("Resource is not a MyAgent type");
    ///     }
    /// }
    /// ```
    fn as_any(&self) -> &dyn std::any::Any;
}

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

    #[test]
    fn test_resource_type_default_directory() {
        assert_eq!(ResourceType::Agent.default_directory(), Some(".claude/agents"));
        assert_eq!(ResourceType::Snippet.default_directory(), Some(".claude/snippets"));
        assert_eq!(ResourceType::Command.default_directory(), Some(".claude/commands"));
        assert_eq!(ResourceType::McpServer.default_directory(), None);
        assert_eq!(ResourceType::Script.default_directory(), Some(".claude/scripts"));
        assert_eq!(ResourceType::Hook.default_directory(), None);
        assert_eq!(ResourceType::Skill.default_directory(), Some(".claude/skills"));
    }

    #[test]
    fn test_resource_type_display() {
        assert_eq!(ResourceType::Agent.to_string(), "agent");
        assert_eq!(ResourceType::Snippet.to_string(), "snippet");
        assert_eq!(ResourceType::Command.to_string(), "command");
        assert_eq!(ResourceType::McpServer.to_string(), "mcp-server");
        assert_eq!(ResourceType::Script.to_string(), "script");
        assert_eq!(ResourceType::Hook.to_string(), "hook");
        assert_eq!(ResourceType::Skill.to_string(), "skill");
    }

    #[test]
    fn test_resource_type_from_str() {
        use std::str::FromStr;

        assert_eq!(ResourceType::from_str("agent").unwrap(), ResourceType::Agent);
        assert_eq!(ResourceType::from_str("snippet").unwrap(), ResourceType::Snippet);
        assert_eq!(ResourceType::from_str("AGENT").unwrap(), ResourceType::Agent);
        assert_eq!(ResourceType::from_str("Snippet").unwrap(), ResourceType::Snippet);
        assert_eq!(ResourceType::from_str("command").unwrap(), ResourceType::Command);
        assert_eq!(ResourceType::from_str("COMMAND").unwrap(), ResourceType::Command);
        assert_eq!(ResourceType::from_str("mcp-server").unwrap(), ResourceType::McpServer);
        assert_eq!(ResourceType::from_str("MCP").unwrap(), ResourceType::McpServer);
        assert_eq!(ResourceType::from_str("script").unwrap(), ResourceType::Script);
        assert_eq!(ResourceType::from_str("SCRIPT").unwrap(), ResourceType::Script);
        assert_eq!(ResourceType::from_str("hook").unwrap(), ResourceType::Hook);
        assert_eq!(ResourceType::from_str("HOOK").unwrap(), ResourceType::Hook);
        assert_eq!(ResourceType::from_str("skill").unwrap(), ResourceType::Skill);
        assert_eq!(ResourceType::from_str("SKILL").unwrap(), ResourceType::Skill);

        assert!(ResourceType::from_str("invalid").is_err());
    }

    #[test]
    fn test_resource_type_serialization() {
        let agent = ResourceType::Agent;
        let json = serde_json::to_string(&agent).unwrap();
        assert_eq!(json, "\"agent\"");

        let deserialized: ResourceType = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized, ResourceType::Agent);

        // Test command serialization
        let command = ResourceType::Command;
        let json = serde_json::to_string(&command).unwrap();
        assert_eq!(json, "\"command\"");

        let deserialized: ResourceType = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized, ResourceType::Command);

        // Test mcp-server serialization
        let mcp_server = ResourceType::McpServer;
        let json = serde_json::to_string(&mcp_server).unwrap();
        assert_eq!(json, "\"mcp-server\"");

        let deserialized: ResourceType = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized, ResourceType::McpServer);

        // Test script serialization
        let script = ResourceType::Script;
        let json = serde_json::to_string(&script).unwrap();
        assert_eq!(json, "\"script\"");

        let deserialized: ResourceType = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized, ResourceType::Script);

        // Test hook serialization
        let hook = ResourceType::Hook;
        let json = serde_json::to_string(&hook).unwrap();
        assert_eq!(json, "\"hook\"");

        let deserialized: ResourceType = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized, ResourceType::Hook);

        // Test skill serialization
        let skill = ResourceType::Skill;
        let json = serde_json::to_string(&skill).unwrap();
        assert_eq!(json, "\"skill\"");

        let deserialized: ResourceType = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized, ResourceType::Skill);
    }

    #[test]
    fn test_resource_type_equality() {
        assert_eq!(ResourceType::Command, ResourceType::Command);
        assert_ne!(ResourceType::Command, ResourceType::Agent);
        assert_ne!(ResourceType::Command, ResourceType::Snippet);
        assert_eq!(ResourceType::McpServer, ResourceType::McpServer);
        assert_ne!(ResourceType::McpServer, ResourceType::Agent);
        assert_eq!(ResourceType::Script, ResourceType::Script);
        assert_ne!(ResourceType::Script, ResourceType::Hook);
        assert_eq!(ResourceType::Hook, ResourceType::Hook);
        assert_ne!(ResourceType::Hook, ResourceType::Agent);
        assert_eq!(ResourceType::Skill, ResourceType::Skill);
        assert_ne!(ResourceType::Skill, ResourceType::Agent);
    }

    #[test]
    fn test_resource_type_copy() {
        let command = ResourceType::Command;
        let copied = command; // ResourceType implements Copy, so this creates a copy
        assert_eq!(command, copied);
    }

    #[test]
    fn test_resource_type_all() {
        let all_types = ResourceType::all();
        assert_eq!(all_types.len(), 7);
        assert_eq!(all_types[0], ResourceType::Agent);
        assert_eq!(all_types[1], ResourceType::Snippet);
        assert_eq!(all_types[2], ResourceType::Command);
        assert_eq!(all_types[3], ResourceType::McpServer);
        assert_eq!(all_types[4], ResourceType::Script);
        assert_eq!(all_types[5], ResourceType::Hook);
        assert_eq!(all_types[6], ResourceType::Skill);

        // Test that we can iterate
        let mut count = 0;
        for _ in ResourceType::all() {
            count += 1;
        }
        assert_eq!(count, 7);
    }

    #[test]
    fn test_resource_type_from_frontmatter_str() {
        // Test singular forms
        assert_eq!(ResourceType::from_frontmatter_str("agent"), Some(ResourceType::Agent));
        assert_eq!(ResourceType::from_frontmatter_str("snippet"), Some(ResourceType::Snippet));
        assert_eq!(ResourceType::from_frontmatter_str("command"), Some(ResourceType::Command));
        assert_eq!(ResourceType::from_frontmatter_str("hook"), Some(ResourceType::Hook));
        assert_eq!(ResourceType::from_frontmatter_str("script"), Some(ResourceType::Script));
        assert_eq!(ResourceType::from_frontmatter_str("mcp-server"), Some(ResourceType::McpServer));
        assert_eq!(ResourceType::from_frontmatter_str("skill"), Some(ResourceType::Skill));

        // Test plural forms
        assert_eq!(ResourceType::from_frontmatter_str("agents"), Some(ResourceType::Agent));
        assert_eq!(ResourceType::from_frontmatter_str("snippets"), Some(ResourceType::Snippet));
        assert_eq!(ResourceType::from_frontmatter_str("commands"), Some(ResourceType::Command));
        assert_eq!(ResourceType::from_frontmatter_str("hooks"), Some(ResourceType::Hook));
        assert_eq!(ResourceType::from_frontmatter_str("scripts"), Some(ResourceType::Script));
        assert_eq!(
            ResourceType::from_frontmatter_str("mcp-servers"),
            Some(ResourceType::McpServer)
        );
        assert_eq!(ResourceType::from_frontmatter_str("skills"), Some(ResourceType::Skill));

        // Test unknown types
        assert_eq!(ResourceType::from_frontmatter_str("unknown"), None);
        assert_eq!(ResourceType::from_frontmatter_str("invalid"), None);
        assert_eq!(ResourceType::from_frontmatter_str(""), None);

        // Test case sensitivity (should be case-sensitive as per implementation)
        assert_eq!(ResourceType::from_frontmatter_str("Agent"), None);
        assert_eq!(ResourceType::from_frontmatter_str("AGENTS"), None);
        assert_eq!(ResourceType::from_frontmatter_str("Snippet"), None);
    }
}