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
//! Dependency processing and resolution for individual dependencies.
//!
//! This module contains the core logic for resolving individual dependencies
//! to locked resources, handling both local and Git-based dependencies.

use std::path::{Path, PathBuf};

use anyhow::Result;

use crate::core::ResourceType;
use crate::lockfile::LockedResource;
use crate::manifest::ResourceDependency;

use super::lockfile_builder;
use super::path_resolver as install_path_resolver;
use super::source_context::SourceContext;
use super::{DependencyResolver, ResolutionCore, generate_dependency_name};

impl DependencyResolver {
    /// Resolve a single dependency to a lockfile entry.
    ///
    /// Delegates to specialized resolvers based on dependency type.
    pub(super) async fn resolve_dependency(
        &self,
        name: &str,
        dep: &ResourceDependency,
        resource_type: ResourceType,
    ) -> Result<LockedResource> {
        tracing::debug!(
            "resolve_dependency: name={}, path={}, source={:?}, is_local={}",
            name,
            dep.get_path(),
            dep.get_source(),
            dep.is_local()
        );

        if dep.is_local() {
            self.resolve_local_dependency(name, dep, resource_type)
        } else {
            self.resolve_git_dependency(name, dep, resource_type).await
        }
    }

    /// Determine filename for a dependency.
    ///
    /// Returns custom filename if specified, otherwise extracts from path.
    pub(super) fn resolve_filename(dep: &ResourceDependency) -> String {
        dep.get_filename().map_or_else(
            || super::extract_meaningful_path(Path::new(dep.get_path())),
            |f| f.to_string(),
        )
    }

    /// Get tool/artifact type for a dependency.
    ///
    /// Returns explicit tool or default for resource type.
    pub(super) fn resolve_tool(
        &self,
        dep: &ResourceDependency,
        resource_type: ResourceType,
    ) -> String {
        dep.get_tool()
            .map(|s| s.to_string())
            .unwrap_or_else(|| self.core.manifest().get_default_tool(resource_type))
    }

    /// Determine manifest_alias for a dependency.
    ///
    /// Returns Some for direct/pattern dependencies, None for transitive.
    pub(super) fn resolve_manifest_alias(
        &self,
        name: &str,
        resource_type: ResourceType,
    ) -> Option<String> {
        let has_pattern_alias = self.get_pattern_alias_for_dependency(name, resource_type);
        let is_in_manifest = self
            .core
            .manifest()
            .get_dependencies(resource_type)
            .is_some_and(|deps| deps.contains_key(name));

        if let Some(pattern_alias) = has_pattern_alias {
            // Pattern-expanded dependency - use pattern name as manifest_alias
            Some(pattern_alias)
        } else if is_in_manifest {
            // Direct manifest dependency - use name as manifest_alias
            Some(name.to_string())
        } else {
            // Transitive dependency - no manifest_alias
            None
        }
    }

    /// Resolve local file system dependency to locked resource.
    pub(super) fn resolve_local_dependency(
        &self,
        name: &str,
        dep: &ResourceDependency,
        resource_type: ResourceType,
    ) -> Result<LockedResource> {
        use crate::utils::normalize_path_for_storage;

        let filename = Self::resolve_filename(dep);
        let artifact_type_string = self.resolve_tool(dep, resource_type);
        let artifact_type = artifact_type_string.as_str();

        let installed_at = install_path_resolver::resolve_install_path(
            self.core.manifest(),
            dep,
            artifact_type,
            resource_type,
            &filename,
        )?;

        let manifest_alias = self.resolve_manifest_alias(name, resource_type);

        tracing::debug!(
            "Local dependency: name={}, path={}, manifest_alias={:?}",
            name,
            dep.get_path(),
            manifest_alias
        );

        let applied_patches = lockfile_builder::get_patches_for_resource(
            self.core.manifest(),
            resource_type,
            name,
            manifest_alias.as_deref(),
        );

        // Generate canonical name for local dependencies
        // For transitive dependencies (manifest_alias=None), use the name as-is since it's
        // already the correct relative path computed by the transitive resolver
        // For direct dependencies (manifest_alias=Some), normalize the path
        let canonical_name = self.compute_local_canonical_name(name, dep, &manifest_alias)?;

        let variant_inputs = lockfile_builder::VariantInputs::new(
            lockfile_builder::build_merged_variant_inputs(self.core.manifest(), dep),
        );

        // Determine if this is a private dependency
        // Use the original manifest name (not canonical name) for the lookup
        let is_private = manifest_alias.as_ref().is_some_and(|alias| {
            self.core.manifest().is_private_dependency(&resource_type.to_string(), alias)
        });

        // Transform path for private dependencies
        let final_installed_at = if is_private {
            install_path_resolver::transform_path_for_private(&installed_at)
        } else {
            installed_at
        };

        Ok(LockedResource {
            name: canonical_name,
            source: None,
            url: None,
            path: normalize_path_for_storage(dep.get_path()),
            version: None,
            resolved_commit: None,
            checksum: String::new(),
            installed_at: final_installed_at,
            dependencies: self.get_dependencies_for(
                name,
                None,
                resource_type,
                Some(&artifact_type_string),
                variant_inputs.hash(),
            ),
            resource_type,
            tool: Some(artifact_type_string),
            manifest_alias,
            applied_patches,
            install: dep.get_install(),
            variant_inputs,
            context_checksum: None,
            is_private,
            approximate_token_count: None,
        })
    }

    /// Compute canonical name for local dependencies.
    ///
    /// Both direct and transitive dependencies use the same naming strategy:
    /// - Use the path relative to manifest directory (preserving ../ for external paths)
    /// - Strip file extension
    /// - Normalize path separators for cross-platform storage
    ///
    /// This ensures that when the same file is referenced as both a direct dependency
    /// (e.g., `../artifacts/commands/helper.md`) and a transitive dependency
    /// (e.g., `./helper.md` resolved to `../artifacts/commands/helper.md`),
    /// they produce the SAME canonical name for template lookups.
    pub(super) fn compute_local_canonical_name(
        &self,
        name: &str,
        dep: &ResourceDependency,
        manifest_alias: &Option<String>,
    ) -> Result<String> {
        if manifest_alias.is_none() {
            // Transitive dependency - name is already correct (e.g., "../snippets/agents/backend-engineer")
            Ok(name.to_string())
        } else {
            // Direct dependency - use the same approach as transitive deps:
            // Take the path relative to manifest (preserving ../ for external paths)
            // and normalize to canonical form.
            //
            // CRITICAL: Do NOT canonicalize to absolute path first, as this breaks
            // matching for paths outside the manifest directory (e.g., ../artifacts/...).
            // Instead, use the relative path directly which matches transitive resolver behavior.
            let path = dep.get_path();

            if let Some(manifest_dir) = self.core.manifest().manifest_dir.as_ref() {
                let source_context = SourceContext::local(manifest_dir);
                Ok(generate_dependency_name(path, &source_context))
            } else {
                // Fallback: strip extension and normalize
                let path_without_ext = Path::new(path).with_extension("");
                Ok(crate::utils::normalize_path_for_storage(&path_without_ext))
            }
        }
    }

    /// Resolve Git-based dependency to locked resource.
    pub(super) async fn resolve_git_dependency(
        &self,
        name: &str,
        dep: &ResourceDependency,
        resource_type: ResourceType,
    ) -> Result<LockedResource> {
        use crate::utils::normalize_path_for_storage;

        let source_name = dep
            .get_source()
            .ok_or_else(|| anyhow::anyhow!("Dependency '{}' has no source specified", name))?;

        // Generate canonical name using remote source context
        let source_context = SourceContext::remote(source_name);
        let canonical_name = generate_dependency_name(dep.get_path(), &source_context);

        let source_url = self
            .core
            .source_manager()
            .get_source_url(source_name)
            .ok_or_else(|| anyhow::anyhow!("Source '{}' not found", source_name))?;

        let version_key = dep.get_version().map_or_else(|| "HEAD".to_string(), |v| v.to_string());
        let group_key = format!("{}::{}", source_name, version_key);

        let prepared = self.version_service.get_prepared_version(&group_key).ok_or_else(|| {
            anyhow::anyhow!(
                "Prepared state missing for source '{}' @ '{}'",
                source_name,
                version_key
            )
        })?;

        let filename = Self::resolve_filename(dep);
        let artifact_type_string = self.resolve_tool(dep, resource_type);
        let artifact_type = artifact_type_string.as_str();

        let installed_at = install_path_resolver::resolve_install_path(
            self.core.manifest(),
            dep,
            artifact_type,
            resource_type,
            &filename,
        )?;

        let manifest_alias = self.resolve_manifest_alias(name, resource_type);

        let applied_patches = lockfile_builder::get_patches_for_resource(
            self.core.manifest(),
            resource_type,
            name,
            manifest_alias.as_deref(),
        );

        let variant_inputs = lockfile_builder::VariantInputs::new(
            lockfile_builder::build_merged_variant_inputs(self.core.manifest(), dep),
        );

        // Extract data from prepared before storing variant_inputs
        let resolved_version = prepared.resolved_version.clone();
        let resolved_commit = prepared.resolved_commit.clone();

        // Store variant_inputs in PreparedSourceVersion for backtracking
        // DashMap allows concurrent inserts, so we don't need mutable access
        let resource_id = format!("{}:{}", source_name, dep.get_path());
        prepared.resource_variants.insert(resource_id, Some(variant_inputs.json().clone()));

        // Determine if this is a private dependency
        let is_private = manifest_alias.as_ref().is_some_and(|alias| {
            self.core.manifest().is_private_dependency(&resource_type.to_string(), alias)
        });

        // Transform path for private dependencies
        let final_installed_at = if is_private {
            install_path_resolver::transform_path_for_private(&installed_at)
        } else {
            installed_at
        };

        Ok(LockedResource {
            name: canonical_name,
            source: Some(source_name.to_string()),
            url: Some(source_url.clone()),
            path: normalize_path_for_storage(dep.get_path()),
            version: resolved_version,
            resolved_commit: Some(resolved_commit),
            checksum: String::new(),
            installed_at: final_installed_at,
            dependencies: self.get_dependencies_for(
                name,
                Some(source_name),
                resource_type,
                Some(&artifact_type_string),
                variant_inputs.hash(),
            ),
            resource_type,
            tool: Some(artifact_type_string),
            manifest_alias,
            applied_patches,
            install: dep.get_install(),
            variant_inputs,
            context_checksum: None,
            is_private,
            approximate_token_count: None,
        })
    }

    /// Resolve pattern dependency to multiple locked resources.
    ///
    /// Delegates to local or Git pattern resolvers.
    pub(super) async fn resolve_pattern_dependency(
        &self,
        name: &str,
        dep: &ResourceDependency,
        resource_type: ResourceType,
    ) -> Result<Vec<LockedResource>> {
        if !dep.is_pattern() {
            return Err(anyhow::anyhow!(
                "Expected pattern dependency but no glob characters found in path"
            ));
        }

        if dep.is_local() {
            self.resolve_local_pattern(name, dep, resource_type)
        } else {
            self.resolve_git_pattern(name, dep, resource_type).await
        }
    }

    /// Resolve local pattern dependency to multiple locked resources.
    pub(super) fn resolve_local_pattern(
        &self,
        name: &str,
        dep: &ResourceDependency,
        resource_type: ResourceType,
    ) -> Result<Vec<LockedResource>> {
        use crate::pattern::PatternResolver;

        let pattern = dep.get_path();
        let (base_path, pattern_str) = install_path_resolver::parse_pattern_base_path(pattern);
        let pattern_resolver = PatternResolver::new();
        let matches = pattern_resolver.resolve(&pattern_str, &base_path)?;

        let artifact_type_string = self.resolve_tool(dep, resource_type);
        let artifact_type = artifact_type_string.as_str();

        // Compute variant inputs once for all matched files in the pattern
        let variant_inputs = lockfile_builder::VariantInputs::new(
            lockfile_builder::build_merged_variant_inputs(self.core.manifest(), dep),
        );

        // Determine if this pattern is a private dependency
        let is_private =
            self.core.manifest().is_private_dependency(&resource_type.to_string(), name);

        let mut resources = Vec::new();
        for matched_path in matches {
            let resource_name = crate::pattern::extract_resource_name(&matched_path);
            let full_relative_path =
                install_path_resolver::construct_full_relative_path(&base_path, &matched_path);
            let filename =
                install_path_resolver::extract_pattern_filename(&base_path, &matched_path);

            let installed_at = install_path_resolver::resolve_install_path(
                self.core.manifest(),
                dep,
                artifact_type,
                resource_type,
                &filename,
            )?;

            // Transform path for private dependencies
            let final_installed_at = if is_private {
                install_path_resolver::transform_path_for_private(&installed_at)
            } else {
                installed_at
            };

            resources.push(LockedResource {
                name: resource_name.clone(),
                source: None,
                url: None,
                path: full_relative_path,
                version: None,
                resolved_commit: None,
                checksum: String::new(),
                installed_at: final_installed_at,
                dependencies: vec![],
                resource_type,
                tool: Some(artifact_type_string.clone()),
                manifest_alias: Some(name.to_string()),
                applied_patches: lockfile_builder::get_patches_for_resource(
                    self.core.manifest(),
                    resource_type,
                    &resource_name, // Use canonical resource name
                    Some(name),     // Use manifest_alias for patch lookups
                ),
                install: dep.get_install(),
                variant_inputs: variant_inputs.clone(),
                context_checksum: None,
                is_private,
                approximate_token_count: None,
            });
        }

        Ok(resources)
    }

    /// Resolve Git-based pattern dependency to multiple locked resources.
    pub(super) async fn resolve_git_pattern(
        &self,
        name: &str,
        dep: &ResourceDependency,
        resource_type: ResourceType,
    ) -> Result<Vec<LockedResource>> {
        use crate::pattern::PatternResolver;
        use crate::utils::{compute_relative_install_path, normalize_path_for_storage};

        let pattern = dep.get_path();
        let pattern_name = name;

        let source_name = dep.get_source().ok_or_else(|| {
            anyhow::anyhow!("Pattern dependency '{}' has no source specified", name)
        })?;

        let source_url = self
            .core
            .source_manager()
            .get_source_url(source_name)
            .ok_or_else(|| anyhow::anyhow!("Source '{}' not found", source_name))?;

        let version_key = dep.get_version().map_or_else(|| "HEAD".to_string(), |v| v.to_string());
        let group_key = format!("{}::{}", source_name, version_key);

        let prepared = self.version_service.get_prepared_version(&group_key).ok_or_else(|| {
            anyhow::anyhow!(
                "Prepared state missing for source '{}' @ '{}'",
                source_name,
                version_key
            )
        })?;

        // Extract data from prepared before mutable borrow (needed for loop)
        let worktree_path = prepared.worktree_path.clone();
        let resolved_version = prepared.resolved_version.clone();
        let resolved_commit = prepared.resolved_commit.clone();

        let repo_path = Path::new(&worktree_path);
        let pattern_resolver = PatternResolver::new();
        let matches = pattern_resolver.resolve(pattern, repo_path)?;

        let artifact_type_string = self.resolve_tool(dep, resource_type);
        let artifact_type = artifact_type_string.as_str();

        // Compute variant inputs once for all matched files in the pattern
        let variant_inputs = lockfile_builder::VariantInputs::new(
            lockfile_builder::build_merged_variant_inputs(self.core.manifest(), dep),
        );

        // Determine if this pattern is a private dependency
        let is_private =
            self.core.manifest().is_private_dependency(&resource_type.to_string(), pattern_name);

        let mut resources = Vec::new();
        for matched_path in matches {
            let resource_name = crate::pattern::extract_resource_name(&matched_path);

            // Compute installation path
            let installed_at = match resource_type {
                ResourceType::Hook | ResourceType::McpServer => {
                    install_path_resolver::resolve_merge_target_path(
                        self.core.manifest(),
                        artifact_type,
                        resource_type,
                    )
                }
                _ => {
                    let artifact_path = self
                        .core
                        .manifest()
                        .get_artifact_resource_path(artifact_type, resource_type)
                        .ok_or_else(|| {
                            anyhow::anyhow!(
                                "Resource type '{}' is not supported by tool '{}'",
                                resource_type,
                                artifact_type
                            )
                        })?;

                    let dep_flatten = dep.get_flatten();
                    let tool_flatten = self
                        .core
                        .manifest()
                        .get_tool_config(artifact_type)
                        .and_then(|config| config.resources.get(resource_type.to_plural()))
                        .and_then(|resource_config| resource_config.flatten);

                    let flatten = dep_flatten.or(tool_flatten).unwrap_or(false);

                    let base_target = if let Some(custom_target) = dep.get_target() {
                        // Strip leading path separators (both Unix and Windows) to ensure relative path
                        PathBuf::from(artifact_path.display().to_string())
                            .join(custom_target.trim_start_matches(['/', '\\']))
                    } else {
                        artifact_path.to_path_buf()
                    };

                    let filename = repo_path.join(&matched_path).to_string_lossy().to_string();
                    let relative_path =
                        compute_relative_install_path(&base_target, Path::new(&filename), flatten);
                    // Convert directly to Unix format for lockfile storage (forward slashes only)
                    normalize_path_for_storage(base_target.join(relative_path))
                }
            };

            // Store variant_inputs in PreparedSourceVersion for backtracking
            // DashMap allows concurrent inserts, so we access through regular get()
            let resource_id = format!("{}:{}", source_name, matched_path.to_string_lossy());
            if let Some(prepared_ref) = self.version_service.get_prepared_version(&group_key) {
                prepared_ref
                    .resource_variants
                    .insert(resource_id, Some(variant_inputs.json().clone()));
            }

            // Transform path for private dependencies
            let final_installed_at = if is_private {
                install_path_resolver::transform_path_for_private(&installed_at)
            } else {
                installed_at
            };

            resources.push(LockedResource {
                name: resource_name.clone(),
                source: Some(source_name.to_string()),
                url: Some(source_url.clone()),
                path: normalize_path_for_storage(matched_path.to_string_lossy().to_string()),
                version: resolved_version.clone(),
                resolved_commit: Some(resolved_commit.clone()),
                checksum: String::new(),
                installed_at: final_installed_at,
                dependencies: vec![],
                resource_type,
                tool: Some(artifact_type_string.clone()),
                manifest_alias: Some(pattern_name.to_string()),
                applied_patches: lockfile_builder::get_patches_for_resource(
                    self.core.manifest(),
                    resource_type,
                    &resource_name,     // Use canonical resource name
                    Some(pattern_name), // Use manifest_alias for patch lookups
                ),
                install: dep.get_install(),
                variant_inputs: variant_inputs.clone(),
                context_checksum: None,
                is_private,
                approximate_token_count: None,
            });
        }

        Ok(resources)
    }
}

/// Helpers for dependency resolution context.
impl ResolutionCore {
    /// Get the manifest directory for resolving relative paths.
    pub fn manifest_dir(&self) -> Option<&std::path::Path> {
        self.manifest().manifest_dir.as_deref()
    }
}