agpm-cli 0.4.8

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
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
//! Extract dependency metadata from resource files.
//!
//! This module handles the extraction of transitive dependency information
//! from resource files. Supports YAML frontmatter in Markdown files and
//! JSON fields in JSON configuration files.
//!
//! # Template Support
//!
//! When a `ProjectConfig` is provided, frontmatter is rendered as a Tera template
//! before parsing. This allows dependency paths to reference project variables:
//!
//! ```yaml
//! dependencies:
//!   snippets:
//!     - path: standards/{{ agpm.project.language }}-guide.md
//! ```

use anyhow::{Context, Result};
use serde_json::{Map, Value as JsonValue};
use std::collections::HashMap;
use std::path::Path;
use tera::{Context as TeraContext, Tera};

use crate::manifest::{DependencyMetadata, ProjectConfig};

/// Metadata extractor for resource files.
///
/// Extracts dependency information embedded in resource files:
/// - Markdown files (.md): YAML frontmatter between `---` delimiters
/// - JSON files (.json): `dependencies` field in the JSON structure
/// - Other files: No dependencies supported
pub struct MetadataExtractor;

impl MetadataExtractor {
    /// Extract dependency metadata from a file's content.
    ///
    /// # Arguments
    /// * `path` - Path to the file (used to determine file type)
    /// * `content` - Content of the file
    /// * `project_config` - Optional project configuration for template rendering
    ///
    /// # Returns
    /// * `DependencyMetadata` - Extracted metadata (may be empty)
    ///
    /// # Template Support
    ///
    /// If `project_config` is provided, frontmatter is rendered as a Tera template
    /// before parsing, allowing references to project variables like:
    /// `{{ agpm.project.language }}`
    pub fn extract(
        path: &Path,
        content: &str,
        project_config: Option<&ProjectConfig>,
    ) -> Result<DependencyMetadata> {
        let extension = path.extension().and_then(|s| s.to_str()).unwrap_or("");

        match extension {
            "md" => Self::extract_markdown_frontmatter(content, project_config, path),
            "json" => Self::extract_json_field(content, project_config, path),
            _ => {
                // Scripts and other files don't support embedded dependencies
                Ok(DependencyMetadata::default())
            }
        }
    }

    /// Extract YAML frontmatter from Markdown content.
    ///
    /// Looks for content between `---` delimiters at the start of the file.
    /// Uses two-phase extraction to respect per-resource templating settings.
    fn extract_markdown_frontmatter(
        content: &str,
        project_config: Option<&ProjectConfig>,
        path: &Path,
    ) -> Result<DependencyMetadata> {
        // Check if content starts with frontmatter delimiter
        if !content.starts_with("---\n") && !content.starts_with("---\r\n") {
            return Ok(DependencyMetadata::default());
        }

        // Find the end of frontmatter
        let search_start = if content.starts_with("---\n") {
            4
        } else {
            5
        };

        let end_pattern = if content.contains("\r\n") {
            "\r\n---\r\n"
        } else {
            "\n---\n"
        };

        if let Some(end_pos) = content[search_start..].find(end_pattern) {
            let frontmatter = &content[search_start..search_start + end_pos];

            // Phase 1: Check if templating is disabled via agpm.templating field
            let templating_disabled = if let Some(_config) = project_config {
                Self::is_templating_disabled_yaml(frontmatter)
            } else {
                false
            };

            // Phase 2: Template the frontmatter if config available and not disabled
            let templated_frontmatter = if let Some(config) = project_config {
                if templating_disabled {
                    tracing::debug!("Templating disabled via agpm.templating field in frontmatter");
                    frontmatter.to_string()
                } else {
                    Self::template_content(frontmatter, config, path)?
                }
            } else {
                frontmatter.to_string()
            };

            // Parse YAML frontmatter
            match serde_yaml::from_str::<DependencyMetadata>(&templated_frontmatter) {
                Ok(metadata) => {
                    // Validate resource types (catch tool names used as types)
                    Self::validate_resource_types(&metadata, path)?;
                    Ok(metadata)
                }
                Err(e) => {
                    // Provide detailed error message for common issues
                    let error_msg = e.to_string();
                    if error_msg.contains("unknown field") {
                        tracing::warn!(
                            "Warning: YAML frontmatter contains unknown field(s): {}. \
                            Supported fields are: path, version, tool",
                            e
                        );
                        eprintln!(
                            "Warning: YAML frontmatter contains unknown field(s).\n\
                            Supported fields in dependencies are:\n\
                            - path: Path to the dependency file (required)\n\
                            - version: Version constraint (optional)\n\
                            - tool: Target tool (optional: claude-code, opencode, agpm)\n\
                            \nError: {}",
                            e
                        );
                    } else {
                        tracing::warn!("Warning: Unable to parse YAML frontmatter: {}", e);
                        eprintln!("Warning: Unable to parse YAML frontmatter: {}", e);
                    }
                    Ok(DependencyMetadata::default())
                }
            }
        } else {
            // No closing delimiter found
            Ok(DependencyMetadata::default())
        }
    }

    /// Extract dependencies field from JSON content.
    ///
    /// Looks for a `dependencies` field in the top-level JSON object.
    /// Uses two-phase extraction to respect per-resource templating settings.
    fn extract_json_field(
        content: &str,
        project_config: Option<&ProjectConfig>,
        path: &Path,
    ) -> Result<DependencyMetadata> {
        // Phase 1: Check if templating is disabled via agpm.templating field
        let templating_disabled = if let Some(_config) = project_config {
            Self::is_templating_disabled_json(content)
        } else {
            false
        };

        // Phase 2: Template the content if config available and not disabled
        let templated_content = if let Some(config) = project_config {
            if templating_disabled {
                tracing::debug!("Templating disabled via agpm.templating field in JSON");
                content.to_string()
            } else {
                Self::template_content(content, config, path)?
            }
        } else {
            content.to_string()
        };

        let json: JsonValue = serde_json::from_str(&templated_content)
            .with_context(|| "Failed to parse JSON content")?;

        if let Some(deps) = json.get("dependencies") {
            // The dependencies field should match our expected structure
            match serde_json::from_value::<HashMap<String, Vec<crate::manifest::DependencySpec>>>(
                deps.clone(),
            ) {
                Ok(dependencies) => {
                    let metadata = DependencyMetadata {
                        dependencies: Some(dependencies),
                    };
                    // Validate resource types (catch tool names used as types)
                    Self::validate_resource_types(&metadata, path)?;
                    Ok(metadata)
                }
                Err(e) => {
                    // Provide detailed error message for common issues
                    let error_msg = e.to_string();
                    if error_msg.contains("unknown field") {
                        tracing::warn!(
                            "Warning: JSON dependencies contain unknown field(s): {}. \
                            Supported fields are: path, version, tool",
                            e
                        );
                        eprintln!(
                            "Warning: JSON dependencies contain unknown field(s).\n\
                            Supported fields in dependencies are:\n\
                            - path: Path to the dependency file (required)\n\
                            - version: Version constraint (optional)\n\
                            - tool: Target tool (optional: claude-code, opencode, agpm)\n\
                            \nError: {}",
                            e
                        );
                    } else {
                        tracing::warn!("Warning: Unable to parse dependencies field: {}", e);
                        eprintln!("Warning: Unable to parse dependencies field: {}", e);
                    }
                    Ok(DependencyMetadata::default())
                }
            }
        } else {
            Ok(DependencyMetadata::default())
        }
    }

    /// Check if templating is disabled in YAML frontmatter.
    ///
    /// Parses the YAML to check for `agpm.templating: false` field.
    /// Templating is opt-in: disabled by default unless explicitly set to true.
    fn is_templating_disabled_yaml(frontmatter: &str) -> bool {
        // Try to parse as raw YAML value to check agpm.templating field
        if let Ok(value) = serde_yaml::from_str::<serde_yaml::Value>(frontmatter) {
            value
                .get("agpm")
                .and_then(|agpm| agpm.get("templating"))
                .and_then(|v| v.as_bool())
                .map(|b| !b)
                .unwrap_or(true) // Opt-in: disabled by default
        } else {
            true // Opt-in: disabled by default
        }
    }

    /// Check if templating is disabled in JSON content.
    ///
    /// Parses the JSON to check for `agpm.templating: false` field.
    /// Templating is opt-in: disabled by default unless explicitly set to true.
    fn is_templating_disabled_json(content: &str) -> bool {
        // Try to parse JSON to check agpm.templating field
        if let Ok(json) = serde_json::from_str::<JsonValue>(content) {
            json.get("agpm")
                .and_then(|agpm| agpm.get("templating"))
                .and_then(|v| v.as_bool())
                .map(|b| !b)
                .unwrap_or(true) // Opt-in: disabled by default
        } else {
            true // Opt-in: disabled by default
        }
    }

    /// Template content using project variables.
    ///
    /// Renders the content as a Tera template with project variables available
    /// under `agpm.project.*`.
    ///
    /// # Arguments
    ///
    /// * `content` - The content to template
    /// * `project_config` - Project configuration containing template variables
    ///
    /// # Returns
    ///
    /// Templated content string, or an error if templating fails
    ///
    /// # Error Handling
    ///
    /// If a template variable is undefined, returns an error with a helpful message.
    /// Use Tera's `default` filter for optional variables:
    /// ```yaml
    /// path: standards/{{ agpm.project.language | default(value="generic") }}-guide.md
    /// ```
    fn template_content(
        content: &str,
        project_config: &ProjectConfig,
        path: &Path,
    ) -> Result<String> {
        // Only template if content contains template syntax
        if !content.contains("{{") && !content.contains("{%") {
            return Ok(content.to_string());
        }

        let mut tera = Tera::default();
        tera.autoescape_on(vec![]); // Disable autoescaping for raw content

        let mut context = TeraContext::new();

        // Build agpm.project context (same structure as content templates)
        let mut agpm = Map::new();
        agpm.insert("project".to_string(), project_config.to_json_value());
        context.insert("agpm", &agpm);

        // Render template - errors (including undefined vars) are returned to caller
        tera.render_str(content, &context).map_err(|e| {
            // Extract detailed error information from Tera error
            let error_details = Self::format_tera_error(&e);

            anyhow::Error::new(e).context(format!(
                "Failed to render frontmatter template in '{}'.\n\
                 Error details:\n{}\n\n\
                 Hint: Use {{{{ var | default(value=\"fallback\") }}}} for optional variables",
                path.display(),
                error_details
            ))
        })
    }

    /// Format a Tera error with detailed information about what went wrong.
    ///
    /// Tera errors can contain various types of issues:
    /// - Missing variables (e.g., "Variable `foo` not found")
    /// - Syntax errors (e.g., "Unexpected end of template")
    /// - Filter/function errors (e.g., "Filter `unknown` not found")
    ///
    /// This function extracts the root cause and formats it in a user-friendly way,
    /// filtering out unhelpful internal template names like '__tera_one_off'.
    ///
    /// # Arguments
    ///
    /// * `error` - The Tera error to format
    fn format_tera_error(error: &tera::Error) -> String {
        use std::error::Error;

        let mut messages = Vec::new();

        // Walk the entire error chain and collect all messages
        let mut all_messages = vec![error.to_string()];
        let mut current_error: Option<&dyn Error> = error.source();
        while let Some(err) = current_error {
            all_messages.push(err.to_string());
            current_error = err.source();
        }

        // Process messages to extract useful information
        for msg in all_messages {
            // Clean up the message by removing internal template names
            let cleaned = msg
                .replace("while rendering '__tera_one_off'", "")
                .replace("Failed to render '__tera_one_off'", "Template rendering failed")
                .replace("Failed to parse '__tera_one_off'", "Template syntax error")
                .replace("'__tera_one_off'", "template")
                .trim()
                .to_string();

            // Only keep non-empty, useful messages
            if !cleaned.is_empty()
                && cleaned != "Template rendering failed"
                && cleaned != "Template syntax error"
            {
                messages.push(cleaned);
            }
        }

        // If we got useful messages, return them
        if !messages.is_empty() {
            messages.join("\n  → ")
        } else {
            // Fallback: extract just the error kind
            "Template syntax error (see details above)".to_string()
        }
    }

    /// Validate that resource type names are correct (not tool names).
    ///
    /// Common mistake: using tool names (claude-code, opencode) as section headers
    /// instead of resource types (agents, snippets, commands).
    ///
    /// # Arguments
    /// * `metadata` - The metadata to validate
    /// * `file_path` - Path to the file being validated (for error messages)
    ///
    /// # Returns
    /// * `Ok(())` if validation passes
    /// * `Err` with helpful error message if tool names detected
    fn validate_resource_types(metadata: &DependencyMetadata, file_path: &Path) -> Result<()> {
        const VALID_RESOURCE_TYPES: &[&str] =
            &["agents", "commands", "snippets", "hooks", "mcp-servers", "scripts"];
        const TOOL_NAMES: &[&str] = &["claude-code", "opencode", "agpm"];

        if let Some(ref dependencies) = metadata.dependencies {
            for resource_type in dependencies.keys() {
                if !VALID_RESOURCE_TYPES.contains(&resource_type.as_str()) {
                    if TOOL_NAMES.contains(&resource_type.as_str()) {
                        // Specific error for tool name confusion
                        anyhow::bail!(
                            "Invalid resource type '{}' in dependencies section of '{}'.\n\n\
                            You used a tool name ('{}') as a section header, but AGPM expects resource types.\n\n\
                            ✗ Wrong:\n  dependencies:\n    {}:\n      - path: ...\n\n\
                            ✓ Correct:\n  dependencies:\n    agents:  # or snippets, commands, etc.\n      - path: ...\n        tool: {}  # Specify tool here\n\n\
                            Valid resource types: {}",
                            resource_type,
                            file_path.display(),
                            resource_type,
                            resource_type,
                            resource_type,
                            VALID_RESOURCE_TYPES.join(", ")
                        );
                    } else {
                        // Generic error for unknown types
                        anyhow::bail!(
                            "Unknown resource type '{}' in dependencies section of '{}'.\n\
                            Valid resource types: {}",
                            resource_type,
                            file_path.display(),
                            VALID_RESOURCE_TYPES.join(", ")
                        );
                    }
                }
            }
        }
        Ok(())
    }

    /// Extract metadata from file content without knowing the file type.
    ///
    /// Tries to detect the format automatically.
    pub fn extract_auto(content: &str) -> Result<DependencyMetadata> {
        use std::path::PathBuf;

        // Try YAML frontmatter first (for Markdown)
        if (content.starts_with("---\n") || content.starts_with("---\r\n"))
            && let Ok(metadata) =
                Self::extract_markdown_frontmatter(content, None, &PathBuf::from("unknown.md"))
            && metadata.has_dependencies()
        {
            return Ok(metadata);
        }

        // Try JSON format
        if content.trim_start().starts_with('{')
            && let Ok(metadata) =
                Self::extract_json_field(content, None, &PathBuf::from("unknown.json"))
            && metadata.has_dependencies()
        {
            return Ok(metadata);
        }

        // No metadata found
        Ok(DependencyMetadata::default())
    }
}

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

    #[test]
    fn test_extract_markdown_frontmatter() {
        let content = r#"---
dependencies:
  agents:
    - path: agents/helper.md
      version: v1.0.0
    - path: agents/reviewer.md
  snippets:
    - path: snippets/utils.md
---

# My Command

This is the command documentation."#;

        let path = Path::new("command.md");
        let metadata = MetadataExtractor::extract(path, content, None).unwrap();

        assert!(metadata.has_dependencies());
        let deps = metadata.dependencies.unwrap();
        assert_eq!(deps["agents"].len(), 2);
        assert_eq!(deps["snippets"].len(), 1);
        assert_eq!(deps["agents"][0].path, "agents/helper.md");
        assert_eq!(deps["agents"][0].version, Some("v1.0.0".to_string()));
    }

    #[test]
    fn test_extract_markdown_no_frontmatter() {
        let content = r#"# My Command

This is a command without frontmatter."#;

        let path = Path::new("command.md");
        let metadata = MetadataExtractor::extract(path, content, None).unwrap();

        assert!(!metadata.has_dependencies());
    }

    #[test]
    fn test_extract_json_dependencies() {
        let content = r#"{
  "events": ["UserPromptSubmit"],
  "type": "command",
  "command": ".claude/scripts/test.js",
  "dependencies": {
    "scripts": [
      { "path": "scripts/test-runner.sh", "version": "v1.0.0" },
      { "path": "scripts/validator.py" }
    ],
    "agents": [
      { "path": "agents/code-analyzer.md", "version": "~1.2.0" }
    ]
  }
}"#;

        let path = Path::new("hook.json");
        let metadata = MetadataExtractor::extract(path, content, None).unwrap();

        assert!(metadata.has_dependencies());
        let deps = metadata.dependencies.unwrap();
        assert_eq!(deps["scripts"].len(), 2);
        assert_eq!(deps["agents"].len(), 1);
        assert_eq!(deps["scripts"][0].path, "scripts/test-runner.sh");
        assert_eq!(deps["scripts"][0].version, Some("v1.0.0".to_string()));
    }

    #[test]
    fn test_extract_json_no_dependencies() {
        let content = r#"{
  "command": "npx",
  "args": ["-y", "@modelcontextprotocol/server-github"]
}"#;

        let path = Path::new("mcp.json");
        let metadata = MetadataExtractor::extract(path, content, None).unwrap();

        assert!(!metadata.has_dependencies());
    }

    #[test]
    fn test_extract_script_file() {
        let content = r#"#!/bin/bash
echo "This is a script file"
# Scripts don't support dependencies"#;

        let path = Path::new("script.sh");
        let metadata = MetadataExtractor::extract(path, content, None).unwrap();

        assert!(!metadata.has_dependencies());
    }

    #[test]
    fn test_extract_auto_markdown() {
        let content = r#"---
dependencies:
  agents:
    - path: agents/test.md
---

# Content"#;

        let metadata = MetadataExtractor::extract_auto(content).unwrap();
        assert!(metadata.has_dependencies());
        assert_eq!(metadata.dependency_count(), 1);
    }

    #[test]
    fn test_extract_auto_json() {
        let content = r#"{
  "dependencies": {
    "snippets": [
      { "path": "snippets/test.md" }
    ]
  }
}"#;

        let metadata = MetadataExtractor::extract_auto(content).unwrap();
        assert!(metadata.has_dependencies());
        assert_eq!(metadata.dependency_count(), 1);
    }

    #[test]
    fn test_windows_line_endings() {
        let content = "---\r\ndependencies:\r\n  agents:\r\n    - path: agents/test.md\r\n---\r\n\r\n# Content";

        let path = Path::new("command.md");
        let metadata = MetadataExtractor::extract(path, content, None).unwrap();

        assert!(metadata.has_dependencies());
        let deps = metadata.dependencies.unwrap();
        assert_eq!(deps["agents"].len(), 1);
        assert_eq!(deps["agents"][0].path, "agents/test.md");
    }

    #[test]
    fn test_empty_dependencies() {
        let content = r#"---
dependencies:
---

# Content"#;

        let path = Path::new("command.md");
        let metadata = MetadataExtractor::extract(path, content, None).unwrap();

        // Should parse successfully but have no dependencies
        assert!(!metadata.has_dependencies());
    }

    #[test]
    fn test_malformed_yaml() {
        let content = r#"---
dependencies:
  agents:
    - path: agents/test.md
    version: missing dash
---

# Content"#;

        let path = Path::new("command.md");
        let result = MetadataExtractor::extract(path, content, None);

        // Should succeed but return empty metadata (with warning logged)
        assert!(result.is_ok());
        let metadata = result.unwrap();
        assert!(metadata.dependencies.is_none());
    }

    #[test]
    fn test_extract_with_tool_field() {
        let content = r#"---
dependencies:
  agents:
    - path: agents/backend.md
      version: v1.0.0
      tool: opencode
    - path: agents/frontend.md
      tool: claude-code
---

# Command with multi-tool dependencies"#;

        let path = Path::new("command.md");
        let metadata = MetadataExtractor::extract(path, content, None).unwrap();

        assert!(metadata.has_dependencies());
        let deps = metadata.dependencies.unwrap();
        assert_eq!(deps["agents"].len(), 2);

        // Verify tool fields are preserved
        assert_eq!(deps["agents"][0].path, "agents/backend.md");
        assert_eq!(deps["agents"][0].tool, Some("opencode".to_string()));

        assert_eq!(deps["agents"][1].path, "agents/frontend.md");
        assert_eq!(deps["agents"][1].tool, Some("claude-code".to_string()));
    }

    #[test]
    fn test_extract_unknown_field_warning() {
        let content = r#"---
dependencies:
  agents:
    - path: agents/test.md
      version: v1.0.0
      invalid_field: should_warn
---

# Content"#;

        let path = Path::new("command.md");
        let result = MetadataExtractor::extract(path, content, None);

        // Should succeed but return empty metadata due to unknown field
        assert!(result.is_ok());
        let metadata = result.unwrap();
        // With deny_unknown_fields, the parsing fails and we get empty metadata
        assert!(!metadata.has_dependencies());
    }

    #[test]
    fn test_template_frontmatter_with_project_vars() {
        // Create a project config
        let mut config_map = toml::map::Map::new();
        config_map.insert("language".to_string(), toml::Value::String("rust".into()));
        config_map.insert("framework".to_string(), toml::Value::String("tokio".into()));
        let project_config = ProjectConfig::from(config_map);

        // Markdown with templated dependency path
        let content = r#"---
agpm:
  templating: true
dependencies:
  snippets:
    - path: standards/{{ agpm.project.language }}-guide.md
      version: v1.0.0
  commands:
    - path: configs/{{ agpm.project.framework }}-setup.md
---

# My Agent"#;

        let path = Path::new("agent.md");
        let metadata = MetadataExtractor::extract(path, content, Some(&project_config)).unwrap();

        assert!(metadata.has_dependencies());
        let deps = metadata.dependencies.unwrap();

        // Check that templates were resolved
        assert_eq!(deps["snippets"].len(), 1);
        assert_eq!(deps["snippets"][0].path, "standards/rust-guide.md");

        assert_eq!(deps["commands"].len(), 1);
        assert_eq!(deps["commands"][0].path, "configs/tokio-setup.md");
    }

    #[test]
    fn test_template_frontmatter_with_missing_vars() {
        // Create a project config with only one variable
        let mut config_map = toml::map::Map::new();
        config_map.insert("language".to_string(), toml::Value::String("rust".into()));
        let project_config = ProjectConfig::from(config_map);

        // Template references undefined variable (should error with helpful message)
        let content = r#"---
agpm:
  templating: true
dependencies:
  snippets:
    - path: standards/{{ agpm.project.language }}-{{ agpm.project.undefined }}-guide.md
---

# My Agent"#;

        let path = Path::new("agent.md");
        let result = MetadataExtractor::extract(path, content, Some(&project_config));

        // Should error on undefined variable
        assert!(result.is_err());
        let error_msg = format!("{}", result.unwrap_err());
        assert!(error_msg.contains("Failed to render frontmatter template"));
        assert!(error_msg.contains("default")); // Suggests using default filter
    }

    #[test]
    fn test_template_frontmatter_with_default_filter() {
        // Create a project config with only one variable
        let mut config_map = toml::map::Map::new();
        config_map.insert("language".to_string(), toml::Value::String("rust".into()));
        let project_config = ProjectConfig::from(config_map);

        // Use default filter for undefined variable (recommended pattern)
        let content = r#"---
agpm:
  templating: true
dependencies:
  snippets:
    - path: standards/{{ agpm.project.language }}-{{ agpm.project.style | default(value="standard") }}-guide.md
---

# My Agent"#;

        let path = Path::new("agent.md");
        let metadata = MetadataExtractor::extract(path, content, Some(&project_config)).unwrap();

        assert!(metadata.has_dependencies());
        let deps = metadata.dependencies.unwrap();

        // Default filter provides fallback value
        assert_eq!(deps["snippets"].len(), 1);
        assert_eq!(deps["snippets"][0].path, "standards/rust-standard-guide.md");
    }

    #[test]
    fn test_template_json_dependencies() {
        // Create a project config
        let mut config_map = toml::map::Map::new();
        config_map.insert("tool".to_string(), toml::Value::String("linter".into()));
        let project_config = ProjectConfig::from(config_map);

        // JSON with templated dependency path
        let content = r#"{
  "events": ["UserPromptSubmit"],
  "command": "node",
  "agpm": {
    "templating": true
  },
  "dependencies": {
    "scripts": [
      { "path": "scripts/{{ agpm.project.tool }}.js", "version": "v1.0.0" }
    ]
  }
}"#;

        let path = Path::new("hook.json");
        let metadata = MetadataExtractor::extract(path, content, Some(&project_config)).unwrap();

        assert!(metadata.has_dependencies());
        let deps = metadata.dependencies.unwrap();

        // Check that template was resolved
        assert_eq!(deps["scripts"].len(), 1);
        assert_eq!(deps["scripts"][0].path, "scripts/linter.js");
    }

    #[test]
    fn test_template_with_no_template_syntax() {
        // Create a project config
        let mut config_map = toml::map::Map::new();
        config_map.insert("language".to_string(), toml::Value::String("rust".into()));
        let project_config = ProjectConfig::from(config_map);

        // Content without template syntax - should work normally
        let content = r#"---
dependencies:
  snippets:
    - path: standards/plain-guide.md
---

# My Agent"#;

        let path = Path::new("agent.md");
        let metadata = MetadataExtractor::extract(path, content, Some(&project_config)).unwrap();

        assert!(metadata.has_dependencies());
        let deps = metadata.dependencies.unwrap();

        // Path should remain unchanged
        assert_eq!(deps["snippets"].len(), 1);
        assert_eq!(deps["snippets"][0].path, "standards/plain-guide.md");
    }

    #[test]
    fn test_template_opt_out_via_agpm_field() {
        // Create a project config
        let mut config_map = toml::map::Map::new();
        config_map.insert("language".to_string(), toml::Value::String("rust".into()));
        let project_config = ProjectConfig::from(config_map);

        // Content with template syntax BUT templating disabled via agpm.templating field
        let content = r#"---
agpm:
  templating: false
dependencies:
  snippets:
    - path: standards/{{ agpm.project.language }}-guide.md
---

# My Agent"#;

        let path = Path::new("agent.md");
        let metadata = MetadataExtractor::extract(path, content, Some(&project_config)).unwrap();

        assert!(metadata.has_dependencies());
        let deps = metadata.dependencies.unwrap();

        // Template syntax should be preserved (not rendered)
        assert_eq!(deps["snippets"].len(), 1);
        assert_eq!(deps["snippets"][0].path, "standards/{{ agpm.project.language }}-guide.md");
    }

    #[test]
    fn test_template_transitive_dep_path() {
        use std::path::PathBuf;

        // Test that dependency paths in frontmatter are templated correctly
        let content = r#"---
agpm:
  templating: true
dependencies:
  agents:
    - path: agents/{{ agpm.project.language }}-helper.md
      version: v1.0.0
---

# Main Agent
"#;

        let mut config_map = toml::map::Map::new();
        config_map.insert("language".to_string(), toml::Value::String("rust".to_string()));
        let config = ProjectConfig::from(config_map);

        let path = PathBuf::from("agents/main.md");
        let result = MetadataExtractor::extract(&path, content, Some(&config));

        assert!(result.is_ok(), "Should extract metadata: {:?}", result.err());
        let metadata = result.unwrap();

        // Should have dependencies
        assert!(metadata.dependencies.is_some(), "Should have dependencies");
        let deps = metadata.dependencies.unwrap();

        // Should have agents key
        assert!(deps.contains_key("agents"), "Should have agents dependencies");
        let agents = &deps["agents"];

        // Should have one agent dependency
        assert_eq!(agents.len(), 1, "Should have one agent dependency");

        // Path should be templated (not contain template syntax)
        let dep_path = &agents[0].path;
        assert_eq!(
            dep_path, "agents/rust-helper.md",
            "Path should be templated to rust-helper, got: {}",
            dep_path
        );
        assert!(!dep_path.contains("{{"), "Path should not contain template syntax");
        assert!(!dep_path.contains("}}"), "Path should not contain template syntax");
    }

    #[test]
    fn test_template_opt_out_json() {
        // Create a project config
        let mut config_map = toml::map::Map::new();
        config_map.insert("tool".to_string(), toml::Value::String("linter".into()));
        let project_config = ProjectConfig::from(config_map);

        // JSON with template syntax BUT templating disabled
        let content = r#"{
  "agpm": {
    "templating": false
  },
  "events": ["UserPromptSubmit"],
  "dependencies": {
    "scripts": [
      { "path": "scripts/{{ agpm.project.tool }}.js" }
    ]
  }
}"#;

        let path = Path::new("hook.json");
        let metadata = MetadataExtractor::extract(path, content, Some(&project_config)).unwrap();

        assert!(metadata.has_dependencies());
        let deps = metadata.dependencies.unwrap();

        // Template syntax should be preserved (not rendered)
        assert_eq!(deps["scripts"].len(), 1);
        assert_eq!(deps["scripts"][0].path, "scripts/{{ agpm.project.tool }}.js");
    }

    #[test]
    fn test_validate_tool_name_as_resource_type_yaml() {
        // YAML using tool name 'opencode' instead of resource type 'agents'
        let content = r#"---
dependencies:
  opencode:
    - path: agents/helper.md
---
# Command"#;

        let path = Path::new("command.md");
        let result = MetadataExtractor::extract(path, content, None);

        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("Invalid resource type 'opencode'"));
        assert!(err_msg.contains("tool name"));
        assert!(err_msg.contains("agents:"));
    }

    #[test]
    fn test_validate_tool_name_as_resource_type_json() {
        // JSON using tool name 'claude-code' instead of resource type 'snippets'
        let content = r#"{
  "dependencies": {
    "claude-code": [
      { "path": "snippets/helper.md" }
    ]
  }
}"#;

        let path = Path::new("hook.json");
        let result = MetadataExtractor::extract(path, content, None);

        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("Invalid resource type 'claude-code'"));
        assert!(err_msg.contains("tool name"));
    }

    #[test]
    fn test_validate_unknown_resource_type() {
        // Using a completely unknown resource type
        let content = r#"---
dependencies:
  foobar:
    - path: something/test.md
---
# Command"#;

        let path = Path::new("command.md");
        let result = MetadataExtractor::extract(path, content, None);

        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("Unknown resource type 'foobar'"));
        assert!(err_msg.contains("Valid resource types"));
    }

    #[test]
    fn test_validate_correct_resource_types() {
        // All valid resource types should pass
        let content = r#"---
dependencies:
  agents:
    - path: agents/helper.md
  snippets:
    - path: snippets/util.md
  commands:
    - path: commands/deploy.md
---
# Command"#;

        let path = Path::new("command.md");
        let result = MetadataExtractor::extract(path, content, None);

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