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
//! Tests for lockfile migration from old format to new dual checksum format

use crate::common::TestProject;
use anyhow::Result;
use tokio::fs;

/// Normalize lockfile content by replacing timestamps with a fixed value
/// to enable deterministic comparisons across test runs.
fn normalize_timestamps(lockfile: &str) -> String {
    // Replace fetched_at timestamps with a fixed value
    let re = regex::Regex::new(r#"fetched_at = "[^"]+""#).unwrap();
    re.replace_all(lockfile, r#"fetched_at = "NORMALIZED""#).to_string()
}

/// Test that old lockfile format is detected and fails with helpful error
#[tokio::test]
async fn test_old_lockfile_detection() -> Result<()> {
    agpm_cli::test_utils::init_test_logging(None);

    let project = TestProject::new().await?;
    let test_repo = project.create_source_repo("test-repo").await?;

    // Create a simple resource
    test_repo
        .add_resource(
            "agents",
            "simple",
            r#"---
title: Simple Agent
---
# Simple Agent

I am a simple agent.
"#,
        )
        .await?;

    test_repo.commit_all("Initial version")?;
    test_repo.tag_version("v1.0.0")?;

    let repo_url = test_repo.bare_file_url(project.sources_path()).await?;

    let manifest = format!(
        r#"[sources]
test-repo = "{}"

[agents]
simple = {{ source = "test-repo", path = "agents/simple.md", version = "v1.0.0" }}
"#,
        repo_url
    );

    project.write_manifest(&manifest).await?;

    // Create old format lockfile (without context_checksum)
    let _old_lockfile_content = format!(
        r#"# AGPM Lockfile
# This file is automatically generated. Do not edit.
# Run 'agpm install' to regenerate.

format_version = "1"

[[agents]]
name = "simple"
source = "test-repo"
path = "agents/simple.md"
version = "v1.0.0"
resolved_commit = "{}"
checksum = "sha256:placeholder"
installed_at = ".claude/agents/agpm/simple.md"
dependencies = []
resource_type = "Agent"
tool = "claude-code"
template_vars = "{{}}"  # Old field name (now variant_inputs)
"#,
        // We'll need to get the actual resolved commit after initial install
        "placeholder_commit"
    );

    // First, do a real install to get the actual commit
    let output = project.run_agpm(&["install"])?;
    assert!(output.success, "Initial install should succeed");

    // Read the generated lockfile to get the real commit
    let real_lockfile_content = project.read_lockfile().await?;
    let lines: Vec<&str> = real_lockfile_content.lines().collect();
    let mut resolved_commit = "unknown";

    for line in lines {
        if line.trim().starts_with("resolved_commit") {
            if let Some(commit) = line.split('=').nth(1) {
                resolved_commit = commit.trim().trim_matches('"');
            }
            break;
        }
    }

    // Now create the old format lockfile with real commit
    let old_lockfile_content = format!(
        r#"# AGPM Lockfile
# This file is automatically generated. Do not edit.
# Run 'agpm install' to regenerate.

format_version = "1"

[[agents]]
name = "simple"
source = "test-repo"
path = "agents/simple.md"
version = "v1.0.0"
resolved_commit = "{}"
checksum = "sha256:placeholder"
installed_at = ".claude/agents/agpm/simple.md"
dependencies = []
resource_type = "Agent"
tool = "claude-code"
template_vars = "{{}}"  # Old field name (now variant_inputs)
"#,
        resolved_commit
    );

    // Write old format lockfile
    let lockfile_path = project.project_path().join("agpm.lock");
    fs::write(&lockfile_path, old_lockfile_content).await?;

    // Try to run install - should fail with migration error
    let output = project.run_agpm(&["install"])?;
    assert!(!output.success, "Install should fail with old lockfile format");

    // Check for helpful error message
    let error_output = format!("{}\n{}", output.stdout, output.stderr);
    assert!(
        error_output.contains("context_checksum")
            || error_output.contains("regenerate")
            || error_output.contains("migrate")
            || error_output.contains("upgrade"),
        "Should contain helpful migration message. Output: {}",
        error_output
    );

    Ok(())
}

/// Test that old template_vars field is properly handled
#[tokio::test]
async fn test_old_template_vars_handling() -> Result<()> {
    agpm_cli::test_utils::init_test_logging(None);

    let project = TestProject::new().await?;
    let test_repo = project.create_source_repo("test-repo").await?;

    // Create a templated resource
    test_repo
        .add_resource(
            "agents",
            "templated",
            r#"---
title: "{{ project.name }}"
agpm:
  templating: true
---
# {{ project.name }}

This is a templated agent.
"#,
        )
        .await?;

    test_repo.commit_all("Initial version")?;
    test_repo.tag_version("v1.0.0")?;

    let repo_url = test_repo.bare_file_url(project.sources_path()).await?;

    // Create manifest with template_vars (old field name usage)
    let manifest = format!(
        r#"[sources]
test-repo = "{}"

[agents]
templated = {{ source = "test-repo", path = "agents/templated.md", version = "v1.0.0", template_vars = {{ project = {{ name = "TestProject" }} }} }}
"#,
        repo_url
    );

    project.write_manifest(&manifest).await?;

    // Install should work with template_vars (still supported for compatibility)
    let output = project.run_agpm(&["install"])?;
    assert!(output.success, "Install should succeed with template_vars. Stderr: {}", output.stderr);

    // Verify resource is installed
    let agent_path = project.project_path().join(".claude/agents/agpm/templated.md");
    assert!(agent_path.exists(), "Templated agent should be installed");

    // Verify lockfile contains both context_checksum and template_vars (for backward compatibility)
    let lockfile = project.load_lockfile()?;
    let has_context_checksum = lockfile.agents.iter().any(|a| a.context_checksum.is_some());
    assert!(has_context_checksum, "Lockfile should contain context_checksum");
    let has_template_vars = lockfile.agents.iter().any(|a| {
        // Check if variant_inputs is not an empty object
        a.variant_inputs.json().as_object().is_some_and(|obj| !obj.is_empty())
    });
    assert!(has_template_vars, "Lockfile should contain template_vars for backward compatibility");

    // Verify content was rendered correctly
    let content = fs::read_to_string(&agent_path).await?;
    assert!(content.contains("TestProject"), "Content should be rendered with template variables");

    Ok(())
}

/// Test migration from install=false to content-only handling
#[tokio::test]
async fn test_install_false_migration() -> Result<()> {
    agpm_cli::test_utils::init_test_logging(None);

    let project = TestProject::new().await?;
    let test_repo = project.create_source_repo("test-repo").await?;

    // Create two resources
    test_repo
        .add_resource(
            "snippets",
            "installable",
            r#"---
title: Installable Snippet
---
# Installable Snippet

This gets installed.
"#,
        )
        .await?;

    test_repo
        .add_resource(
            "snippets",
            "content-only",
            r#"---
title: Content Only Snippet
dependencies:
  snippets:
    - path: snippets/dependency.md
      version: "v1.0.0"
agpm:
  templating: true
---
# Content Only Snippet

This is content-only.
"#,
        )
        .await?;

    test_repo
        .add_resource(
            "snippets",
            "dependency",
            r#"---
title: Dependency Snippet
---
# Dependency Snippet

I am a dependency.
"#,
        )
        .await?;

    test_repo.commit_all("Initial version")?;
    test_repo.tag_version("v1.0.0")?;

    let repo_url = test_repo.bare_file_url(project.sources_path()).await?;

    // Initial manifest: both installed
    let manifest1 = format!(
        r#"[sources]
test-repo = "{}"

[snippets]
installable = {{ source = "test-repo", path = "snippets/installable.md", version = "v1.0.0" }}
content_only = {{ source = "test-repo", path = "snippets/content-only.md", version = "v1.0.0", template_vars = {{}} }}
"#,
        repo_url
    );

    project.write_manifest(&manifest1).await?;

    // Initial install
    let output1 = project.run_agpm(&["install"])?;
    assert!(output1.success, "Initial install should succeed");

    // Verify both files exist
    let installable_path = project.project_path().join(".agpm/snippets/installable.md");
    let content_only_path = project.project_path().join(".agpm/snippets/content-only.md");
    let dependency_path = project.project_path().join(".agpm/snippets/dependency.md");

    assert!(installable_path.exists(), "Installable snippet should be installed");
    assert!(content_only_path.exists(), "Content-only snippet should be installed initially");
    assert!(dependency_path.exists(), "Dependency should be installed");

    // Update manifest: make content-only snippet really content-only
    let manifest2 = format!(
        r#"[sources]
test-repo = "{}"

[snippets]
installable = {{ source = "test-repo", path = "snippets/installable.md", version = "v1.0.0" }}
content_only = {{ source = "test-repo", path = "snippets/content-only.md", version = "v1.0.0", install = false, template_vars = {{}} }}
"#,
        repo_url
    );

    project.write_manifest(&manifest2).await?;

    // Update install
    let output2 = project.run_agpm(&["install"])?;
    assert!(output2.success, "Update should succeed");

    // Verify cleanup occurred
    assert!(
        output2.stdout.contains("Cleaned up") || output2.stdout.contains("moved or removed"),
        "Should report cleanup. Output: {}",
        output2.stdout
    );

    // Content-only file should be removed, but dependency should remain (transitive)
    assert!(installable_path.exists(), "Installable snippet should still exist");
    assert!(!content_only_path.exists(), "Content-only snippet should be removed");
    assert!(
        dependency_path.exists(),
        "Dependency should still exist (may be content-only transitive dependency)"
    );

    Ok(())
}

/// Test that variant_inputs field works with new system
#[tokio::test]
async fn test_variant_inputs_compatibility() -> Result<()> {
    agpm_cli::test_utils::init_test_logging(None);

    let project = TestProject::new().await?;
    let test_repo = project.create_source_repo("test-repo").await?;

    // Create a resource that uses template variables
    test_repo
        .add_resource(
            "commands",
            "variant-command",
            r#"---
title: "Variant Command"
api_url: "{{ config.api_url }}"
timeout: {{ config.timeout }}
agpm:
  templating: true
---
# Variant Command

API: {{ config.api_url }}
Timeout: {{ config.timeout }}s
Features: {{ features | join(sep=", ") }}
"#,
        )
        .await?;

    test_repo.commit_all("Initial version")?;
    test_repo.tag_version("v1.0.0")?;

    let repo_url = test_repo.bare_file_url(project.sources_path()).await?;

    // Test with both template_vars and variant_inputs (should work)
    let manifest = format!(
        r#"[sources]
test-repo = "{}"

[commands]
variant = {{ source = "test-repo", path = "commands/variant-command.md", version = "v1.0.0", template_vars = {{ config = {{ api_url = "https://api.example.com", timeout = 30 }}, features = ["auth", "logging"] }} }}
"#,
        repo_url
    );

    project.write_manifest(&manifest).await?;

    // Install
    let output = project.run_agpm(&["install"])?;
    assert!(
        output.success,
        "Install should succeed with template_vars alias. Stderr: {}",
        output.stderr
    );

    // Verify resource is installed (uses canonical name from path, not manifest alias)
    let command_path = project.project_path().join(".claude/commands/agpm/variant-command.md");
    assert!(command_path.exists(), "Variant command should be installed");

    // Verify content was rendered correctly
    let content = fs::read_to_string(&command_path).await?;
    assert!(content.contains("https://api.example.com"), "API URL should be rendered");
    assert!(content.contains("30s"), "Timeout should be rendered");
    assert!(content.contains("auth, logging"), "Features should be rendered");

    // Verify lockfile contains both fields for compatibility
    let lockfile = project.load_lockfile()?;
    let has_context_checksum = lockfile.commands.iter().any(|c| c.context_checksum.is_some());
    assert!(has_context_checksum, "Lockfile should contain context_checksum");
    let has_template_vars = lockfile.commands.iter().any(|c| {
        // Check if variant_inputs is not an empty object
        c.variant_inputs.json().as_object().is_some_and(|obj| !obj.is_empty())
    });
    assert!(has_template_vars, "Lockfile should contain template_vars (backward compatibility)");

    Ok(())
}

/// Test multiple runs with same input produce same results after migration
#[tokio::test]
async fn test_post_migration_consistency() -> Result<()> {
    agpm_cli::test_utils::init_test_logging(None);

    let project = TestProject::new().await?;
    let test_repo = project.create_source_repo("test-repo").await?;

    // Create a mix of resources
    test_repo
        .add_resource(
            "agents",
            "plain",
            r#"---
title: Plain Agent
---
# Plain Agent

No templating.
"#,
        )
        .await?;

    test_repo
        .add_resource(
            "agents",
            "templated",
            r#"---
title: "{{ config.name }}"
agpm:
  templating: true
---
# {{ config.name }}

Templated agent.
"#,
        )
        .await?;

    test_repo.commit_all("Initial version")?;
    test_repo.tag_version("v1.0.0")?;

    let repo_url = test_repo.bare_file_url(project.sources_path()).await?;

    let manifest = format!(
        r#"[sources]
test-repo = "{}"

[agents]
plain = {{ source = "test-repo", path = "agents/plain.md", version = "v1.0.0" }}
templated = {{ source = "test-repo", path = "agents/templated.md", version = "v1.0.0", template_vars = {{ config = {{ name = "MigratedAgent" }} }} }}
"#,
        repo_url
    );

    project.write_manifest(&manifest).await?;

    // Run install multiple times and verify consistency
    let mut lockfiles = Vec::new();

    for run in 1..=3 {
        // Clean lockfile
        let lockfile_path = project.project_path().join("agpm.lock");
        if lockfile_path.exists() {
            fs::remove_file(&lockfile_path).await?;
        }

        // Install
        let output = project.run_agpm(&["install"])?;
        assert!(output.success, "Run {} should succeed", run);

        // Read lockfile
        let lockfile_content = project.read_lockfile().await?;
        lockfiles.push(lockfile_content);

        // Verify resources are installed
        let plain_path = project.project_path().join(".claude/agents/agpm/plain.md");
        let templated_path = project.project_path().join(".claude/agents/agpm/templated.md");

        assert!(plain_path.exists(), "Plain agent should exist in run {}", run);
        assert!(templated_path.exists(), "Templated agent should exist in run {}", run);
    }

    // All lockfiles should be identical (post-migration consistency)
    // Normalize timestamps before comparison
    let normalized_lockfiles: Vec<_> = lockfiles.iter().map(|l| normalize_timestamps(l)).collect();

    for i in 1..normalized_lockfiles.len() {
        assert_eq!(
            normalized_lockfiles[0],
            normalized_lockfiles[i],
            "Lockfiles should be consistent post-migration. Run 1 vs Run {}:\n\nRun 1:\n{}\n\nRun {}:\n{}",
            i + 1,
            normalized_lockfiles[0],
            i + 1,
            normalized_lockfiles[i]
        );
    }

    // Verify context checksum is present for templated resource but not for plain
    let first_lockfile = toml::from_str::<agpm_cli::lockfile::LockFile>(&lockfiles[0])?;

    let context_checksums: Vec<_> =
        first_lockfile.agents.iter().filter_map(|a| a.context_checksum.as_ref()).collect();

    assert!(!context_checksums.is_empty(), "Lockfile should contain context checksum");

    // Should have exactly one context checksum (only for templated resource)
    assert_eq!(
        context_checksums.len(),
        1,
        "Should have exactly one context checksum (for templated resource), found {}",
        context_checksums.len()
    );

    Ok(())
}