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
//! Core types and utilities for dependency resolution.
//!
//! This module provides shared types, context structures, and helper functions
//! used throughout the resolver. It consolidates:
//! - Resolution context and core shared state
//! - Context structures for different resolution phases
//! - Pure helper functions for dependency manipulation

use std::collections::HashMap;
use std::sync::Arc;

use dashmap::DashMap;

use crate::cache::Cache;
use crate::core::ResourceType;
use crate::core::operation_context::OperationContext;
use crate::lockfile::lockfile_dependency_ref::LockfileDependencyRef;
use crate::manifest::{Manifest, ResourceDependency};
use crate::source::SourceManager;
use crate::version::conflict::ConflictDetector;

// ============================================================================
// Resolution Mode Types
// ============================================================================

/// Determines which resolution strategy to use for a dependency
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResolutionMode {
    /// Semantic versioning with constraints and tags
    Version,
    /// Direct git reference (branch or rev)
    GitRef,
}

impl ResolutionMode {
    /// Determine resolution mode from a dependency specification
    pub fn from_dependency(dep: &crate::manifest::ResourceDependency) -> Self {
        use crate::manifest::ResourceDependency;

        match dep {
            ResourceDependency::Simple(_) => Self::Version, // Default to version
            ResourceDependency::Detailed(d) => {
                if d.branch.is_some() || d.rev.is_some() {
                    Self::GitRef
                } else {
                    Self::Version
                }
            }
        }
    }
}

// ============================================================================
// Core Resolution Context
// ============================================================================

/// Core shared context for dependency resolution.
///
/// This struct holds immutable state that is shared across all
/// resolution services. It does not change during resolution.
pub struct ResolutionCore {
    /// The project manifest with dependencies and configuration
    pub manifest: Manifest,

    /// The cache for worktrees and Git operations
    pub cache: Cache,

    /// The source manager for resolving source URLs
    pub source_manager: SourceManager,

    /// Optional operation context for warnings and progress tracking
    pub operation_context: Option<Arc<OperationContext>>,
}

impl ResolutionCore {
    /// Create a new resolution core.
    pub fn new(
        manifest: Manifest,
        cache: Cache,
        source_manager: SourceManager,
        operation_context: Option<Arc<OperationContext>>,
    ) -> Self {
        Self {
            manifest,
            cache,
            source_manager,
            operation_context,
        }
    }

    /// Get a reference to the manifest.
    pub fn manifest(&self) -> &Manifest {
        &self.manifest
    }

    /// Get a reference to the cache.
    pub fn cache(&self) -> &Cache {
        &self.cache
    }

    /// Get a reference to the source manager.
    pub fn source_manager(&self) -> &SourceManager {
        &self.source_manager
    }

    /// Get a reference to the operation context if present.
    pub fn operation_context(&self) -> Option<&Arc<OperationContext>> {
        self.operation_context.as_ref()
    }
}

// ============================================================================
// Resolution Context Types
// ============================================================================

/// Type alias for dependency keys used in resolution maps.
///
/// Format: (ResourceType, dependency_name, source, tool, variant_inputs_hash)
///
/// The variant_inputs_hash ensures that dependencies with different template variables
/// are treated as distinct entries, preventing incorrect deduplication when multiple
/// parent resources need the same dependency with different variant inputs.
pub type DependencyKey = (ResourceType, String, Option<String>, Option<String>, String);

/// Base resolution context with immutable shared state.
///
/// This context is passed to most resolution operations and provides access
/// to the manifest, cache, source manager, and operation context.
///
/// Implements `Copy` because all fields are references (`&'a T`), making
/// it cheap to pass by value and enabling ergonomic usage in closures
/// and parallel processing contexts.
#[derive(Copy, Clone)]
pub struct ResolutionContext<'a> {
    /// The project manifest with dependencies and configuration
    pub manifest: &'a Manifest,

    /// The cache for worktrees and Git operations
    pub cache: &'a Cache,

    /// The source manager for resolving source URLs
    pub source_manager: &'a SourceManager,

    /// Optional operation context for warnings and progress tracking
    pub operation_context: Option<&'a Arc<OperationContext>>,
}

/// Context for transitive dependency resolution.
///
/// Extends the base resolution context with concurrent state needed for
/// parallel transitive dependency traversal and conflict detection.
pub struct TransitiveContext<'a> {
    /// Base immutable context
    pub base: ResolutionContext<'a>,

    /// Map tracking which dependencies are required by which resources (concurrent)
    pub dependency_map: &'a Arc<DashMap<DependencyKey, Vec<String>>>,

    /// Map tracking custom names for transitive dependencies (concurrent, for template variables)
    pub transitive_custom_names: &'a Arc<DashMap<DependencyKey, String>>,

    /// Conflict detector for version resolution
    pub conflict_detector: &'a mut ConflictDetector,

    /// Index of manifest overrides for deduplication with transitive deps
    pub manifest_overrides: &'a ManifestOverrideIndex,
}

/// Context for pattern expansion operations.
///
/// Extends the base resolution context with pattern alias tracking.
pub struct PatternContext<'a> {
    /// Base immutable context
    pub base: ResolutionContext<'a>,

    /// Map tracking pattern alias relationships (concrete_name -> pattern_name) (concurrent)
    pub pattern_alias_map: &'a Arc<DashMap<(ResourceType, String), String>>,
}

// ============================================================================
// Manifest Override Types
// ============================================================================

/// Stores override information from manifest dependencies.
///
/// When a resource appears both as a direct dependency in the manifest and as
/// a transitive dependency of another resource, this structure stores the
/// customizations from the manifest version to ensure they take precedence.
#[derive(Debug, Clone)]
pub struct ManifestOverride {
    /// Custom filename specified in manifest
    pub filename: Option<String>,

    /// Custom target path specified in manifest
    pub target: Option<String>,

    /// Install flag override
    pub install: Option<bool>,

    /// Manifest alias (for reference)
    pub manifest_alias: Option<String>,

    /// Original template variables from manifest
    pub template_vars: Option<serde_json::Value>,
}

/// Key for override index lookup.
///
/// This key uniquely identifies a resource variant for the purpose of
/// detecting when a transitive dependency should be overridden by a
/// direct manifest dependency.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct OverrideKey {
    /// The type of resource (Agent, Snippet, etc.)
    pub resource_type: ResourceType,

    /// Normalized path (without leading ./ and without extension)
    pub normalized_path: String,

    /// Source repository name (None for local dependencies)
    pub source: Option<String>,

    /// Target tool name
    pub tool: String,

    /// Variant inputs hash (computed from template_vars)
    pub variant_hash: String,
}

/// Override index mapping resource identities to their manifest customizations.
///
/// This index is built once during resolution from the manifest dependencies
/// and used to apply overrides to transitive dependencies that match.
pub type ManifestOverrideIndex = HashMap<OverrideKey, ManifestOverride>;

// ============================================================================
// Conflict Detection Types
// ============================================================================

/// Value type for resolved dependencies tracked for conflict detection.
///
/// Contains the resolution metadata needed to detect and resolve version conflicts
/// between different dependencies that resolve to the same resource.
#[derive(Debug, Clone)]
pub struct ResolvedDependencyInfo {
    /// The version constraint that was specified (e.g., "^1.0.0", "main", "abc123")
    pub version_constraint: String,

    /// The resolved commit SHA for this dependency
    pub resolved_sha: String,

    /// The version constraint of the parent dependency (if any)
    pub parent_version: Option<String>,

    /// The resolved SHA of the parent dependency (if any)
    pub parent_sha: Option<String>,

    /// The resolution mode used (Version or GitRef)
    pub resolution_mode: ResolutionMode,
}

/// Key type for resolved dependencies tracked for conflict detection.
///
/// Uniquely identifies a resolved dependency instance for conflict tracking.
pub type ConflictDetectionKey = (crate::lockfile::ResourceId, String, String);

/// Concurrent map type for tracking resolved dependencies during conflict detection.
///
/// This type is used throughout the resolver to track dependency resolution
/// metadata for detecting version conflicts between different dependency requirements.
pub type ResolvedDependenciesMap = Arc<DashMap<ConflictDetectionKey, ResolvedDependencyInfo>>;

// ============================================================================
// Manifest Override Helper Functions

/// Apply manifest overrides to a resource dependency.
///
/// This helper function centralizes the logic for applying manifest customizations
/// to transitive dependencies, ensuring consistent behavior across the codebase.
///
/// # Arguments
///
/// * `dep` - The resource dependency to modify (will be updated in-place)
/// * `override_info` - The override information from the manifest
/// * `normalized_path` - The normalized path for logging
///
/// # Effects
///
/// Modifies the dependency in-place with the following overrides:
/// - `filename` - Custom filename
/// - `target` - Custom target path
/// - `install` - Install flag override
/// - `template_vars` - Template variables (replaces transitive version)
///
/// # Logging
///
/// Logs debug information about applied overrides and warnings for non-detailed dependencies.
pub fn apply_manifest_override(
    dep: &mut ResourceDependency,
    override_info: &ManifestOverride,
    normalized_path: &str,
) {
    tracing::debug!(
        "Applying manifest override to transitive dependency: {} (normalized: {})",
        dep.get_path(),
        normalized_path
    );

    // Apply overrides to make transitive dep match manifest version
    if let ResourceDependency::Detailed(detailed) = dep {
        // Get the path before we start modifying the dependency
        let path = detailed.path.clone();

        if let Some(filename) = &override_info.filename {
            detailed.filename = Some(filename.clone());
        }

        if let Some(target) = &override_info.target {
            detailed.target = Some(target.clone());
        }

        if let Some(install) = override_info.install {
            detailed.install = Some(install);
        }

        // Replace template vars with manifest version for consistent rendering
        if let Some(template_vars) = &override_info.template_vars {
            detailed.template_vars = Some(template_vars.clone());
        }

        tracing::debug!(
            "Applied manifest overrides to '{}': filename={:?}, target={:?}, install={:?}, template_vars={}",
            path,
            detailed.filename,
            detailed.target,
            detailed.install,
            detailed.template_vars.is_some()
        );
    } else {
        tracing::warn!(
            "Cannot apply manifest override to non-detailed dependency: {}",
            dep.get_path()
        );
    }
}

// ============================================================================
// Dependency Helper Functions
// ============================================================================

/// Builds a resource identifier in the format `source:path`.
///
/// Resource identifiers are used for conflict detection and version resolution
/// to uniquely identify resources across different sources.
///
/// # Arguments
///
/// * `dep` - The resource dependency specification
///
/// # Returns
///
/// A string in the format `"source:path"`, or `"unknown:path"` for dependencies
/// without a source (e.g., local dependencies).
pub fn build_resource_id(dep: &ResourceDependency) -> String {
    let source = dep.get_source().unwrap_or("unknown");
    let path = dep.get_path();
    format!("{source}:{path}")
}

/// Normalizes a path by stripping leading `./` prefix.
///
/// This is a simple normalization that makes paths consistent for comparison
/// and lookup operations.
///
/// # Arguments
///
/// * `path` - The path string to normalize
///
/// # Returns
///
/// A normalized path string without leading `./`
///
/// # Examples
///
/// ```
/// use agpm_cli::resolver::types::normalize_lookup_path;
///
/// assert_eq!(normalize_lookup_path("./agents/helper.md"), "agents/helper");
/// assert_eq!(normalize_lookup_path("agents/helper.md"), "agents/helper");
/// assert_eq!(normalize_lookup_path("./foo"), "foo");
/// ```
pub fn normalize_lookup_path(path: &str) -> String {
    use std::path::{Component, Path};

    let path_obj = Path::new(path);

    // Build normalized path by iterating through components
    let mut components = Vec::new();
    for component in path_obj.components() {
        match component {
            Component::CurDir => continue, // Skip "."
            Component::Normal(os_str) => {
                components.push(os_str.to_string_lossy().to_string());
            }
            _ => {}
        }
    }

    // If we have components, strip extension from last one
    if let Some(last) = components.last_mut() {
        // Strip .md extension if present
        if let Some(stem) = Path::new(last.as_str()).file_stem() {
            *last = stem.to_string_lossy().to_string();
        }
    }

    if components.is_empty() {
        path.to_string()
    } else {
        components.join("/")
    }
}

/// Extracts the filename from a path.
///
/// Returns the last component of a slash-separated path.
///
/// # Arguments
///
/// * `path` - The path string (may contain forward slashes)
///
/// # Returns
///
/// The filename if the path contains at least one component, `None` otherwise.
///
/// # Examples
///
/// ```
/// use agpm_cli::resolver::types::extract_filename_from_path;
///
/// assert_eq!(extract_filename_from_path("agents/helper.md"), Some("helper.md".to_string()));
/// assert_eq!(extract_filename_from_path("foo/bar/baz.txt"), Some("baz.txt".to_string()));
/// assert_eq!(extract_filename_from_path("single.md"), Some("single.md".to_string()));
/// assert_eq!(extract_filename_from_path(""), None);
/// ```
pub fn extract_filename_from_path(path: &str) -> Option<String> {
    std::path::Path::new(path).file_name().and_then(|n| n.to_str()).map(String::from)
}

/// Strips resource type directory prefix from a path.
///
/// This mimics the logic in `generate_dependency_name` to allow dependency
/// lookups to work with dependency names from the dependency map.
///
/// For paths like `agents/helpers/foo.md`, this returns `helpers/foo.md`.
/// For paths without a recognized resource type directory, returns `None`.
///
/// # Arguments
///
/// * `path` - The path string with forward slashes
///
/// # Returns
///
/// The path with the resource type directory prefix stripped, or `None` if
/// no resource type directory is found.
///
/// # Recognized Resource Type Directories
///
/// - agents
/// - snippets
/// - commands
/// - scripts
/// - hooks
/// - mcp-servers
///
/// # Examples
///
/// ```
/// use agpm_cli::resolver::types::strip_resource_type_directory;
///
/// assert_eq!(
///     strip_resource_type_directory("agents/helpers/foo.md"),
///     Some("helpers/foo.md".to_string())
/// );
/// assert_eq!(
///     strip_resource_type_directory("snippets/rust/best-practices.md"),
///     Some("rust/best-practices.md".to_string())
/// );
/// assert_eq!(
///     strip_resource_type_directory("commands/deploy.md"),
///     Some("deploy.md".to_string())
/// );
/// assert_eq!(
///     strip_resource_type_directory("foo/bar.md"),
///     None
/// );
/// assert_eq!(
///     strip_resource_type_directory("agents"),
///     None  // No components after the resource type dir
/// );
/// ```
pub fn strip_resource_type_directory(path: &str) -> Option<String> {
    use std::path::{Component, Path};

    let resource_type_dirs = ["agents", "snippets", "commands", "scripts", "hooks", "mcp-servers"];

    // Use Path::components() to handle both forward and back slashes
    let components: Vec<_> = Path::new(path)
        .components()
        .filter_map(|c| match c {
            Component::Normal(s) => s.to_str(),
            _ => None,
        })
        .collect();

    if components.len() > 1 {
        // Find the index of the first resource type directory
        if let Some(idx) = components.iter().position(|c| resource_type_dirs.contains(c)) {
            // Skip everything up to and including the resource type directory
            if idx + 1 < components.len() {
                // Always return with forward slashes for storage format
                return Some(components[idx + 1..].join("/"));
            }
        }
    }
    None
}

/// Formats a dependency reference with version suffix.
///
/// Creates a string in the format `"resource_type/name@version"` for use in
/// lockfile dependency lists.
///
/// # Arguments
///
/// * `resource_type` - The type of resource (Agent, Snippet, etc.)
/// * `name` - The resource name
/// * `version` - The version string (can be a semver tag, commit SHA, or "HEAD")
///
/// # Returns
///
/// A formatted dependency string with version.
///
/// # Examples
///
/// ```
/// use agpm_cli::core::ResourceType;
/// use agpm_cli::resolver::types::format_dependency_with_version;
///
/// let formatted = format_dependency_with_version(
///     ResourceType::Agent,
///     "helper",
///     "v1.0.0"
/// );
/// assert_eq!(formatted, "agent:helper@v1.0.0");
///
/// let formatted = format_dependency_with_version(
///     ResourceType::Snippet,
///     "utils",
///     "abc123"
/// );
/// assert_eq!(formatted, "snippet:utils@abc123");
/// ```
pub fn format_dependency_with_version(
    resource_type: ResourceType,
    name: &str,
    version: &str,
) -> String {
    LockfileDependencyRef::local(resource_type, name.to_string(), Some(version.to_string()))
        .to_string()
}

/// Formats a dependency reference without version suffix.
///
/// Creates a string in the format `"resource_type/name"` for use in
/// dependency tracking before version resolution.
///
/// # Arguments
///
/// * `resource_type` - The type of resource (Agent, Snippet, etc.)
/// * `name` - The resource name
///
/// # Returns
///
/// A formatted dependency string without version.
///
/// # Examples
///
/// ```
/// use agpm_cli::core::ResourceType;
/// use agpm_cli::resolver::types::format_dependency_without_version;
///
/// let formatted = format_dependency_without_version(ResourceType::Agent, "helper");
/// assert_eq!(formatted, "agent:helper");
///
/// let formatted = format_dependency_without_version(ResourceType::Command, "deploy");
/// assert_eq!(formatted, "command:deploy");
/// ```
pub fn format_dependency_without_version(resource_type: ResourceType, name: &str) -> String {
    LockfileDependencyRef::local(resource_type, name.to_string(), None).to_string()
}

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

    #[test]
    fn test_normalize_lookup_path() {
        // Extensions are stripped for consistent lookup
        assert_eq!(normalize_lookup_path("./agents/helper.md"), "agents/helper");
        assert_eq!(normalize_lookup_path("agents/helper.md"), "agents/helper");
        assert_eq!(normalize_lookup_path("snippets/helpers/foo.md"), "snippets/helpers/foo");
        assert_eq!(normalize_lookup_path("./foo.md"), "foo");
        assert_eq!(normalize_lookup_path("./foo"), "foo");
        assert_eq!(normalize_lookup_path("foo"), "foo");
    }

    #[test]
    fn test_extract_filename_from_path() {
        assert_eq!(extract_filename_from_path("agents/helper.md"), Some("helper.md".to_string()));
        assert_eq!(extract_filename_from_path("foo/bar/baz.txt"), Some("baz.txt".to_string()));
        assert_eq!(extract_filename_from_path("single.md"), Some("single.md".to_string()));
        assert_eq!(extract_filename_from_path(""), None);
        // Path::file_name() normalizes trailing slashes
        assert_eq!(extract_filename_from_path("trailing/"), Some("trailing".to_string()));
    }

    #[test]
    fn test_strip_resource_type_directory() {
        assert_eq!(
            strip_resource_type_directory("agents/helpers/foo.md"),
            Some("helpers/foo.md".to_string())
        );
        assert_eq!(
            strip_resource_type_directory("snippets/rust/best-practices.md"),
            Some("rust/best-practices.md".to_string())
        );
        assert_eq!(
            strip_resource_type_directory("commands/deploy.md"),
            Some("deploy.md".to_string())
        );
        assert_eq!(strip_resource_type_directory("foo/bar.md"), None);
        assert_eq!(strip_resource_type_directory("agents"), None);
        assert_eq!(
            strip_resource_type_directory("mcp-servers/filesystem.json"),
            Some("filesystem.json".to_string())
        );
    }

    #[test]
    fn test_format_dependency_with_version() {
        assert_eq!(
            format_dependency_with_version(ResourceType::Agent, "helper", "v1.0.0"),
            "agent:helper@v1.0.0"
        );
        assert_eq!(
            format_dependency_with_version(ResourceType::Snippet, "utils", "abc123"),
            "snippet:utils@abc123"
        );
    }

    #[test]
    fn test_format_dependency_without_version() {
        assert_eq!(
            format_dependency_without_version(ResourceType::Agent, "helper"),
            "agent:helper"
        );
        assert_eq!(
            format_dependency_without_version(ResourceType::Command, "deploy"),
            "command:deploy"
        );
    }

    #[test]
    fn test_build_resource_id() {
        let dep = ResourceDependency::Detailed(Box::new(DetailedDependency {
            source: Some("test-source".to_string()),
            path: "agents/helper.md".to_string(),
            version: Some("v1.0.0".to_string()),
            branch: None,
            rev: None,
            command: None,
            args: None,
            target: None,
            filename: None,
            dependencies: None,
            tool: None,
            flatten: None,
            install: None,
            template_vars: Some(serde_json::Value::Object(serde_json::Map::new())),
        }));
        let resource_id = build_resource_id(&dep);
        assert!(resource_id.contains("agents/helper.md"));
    }
}