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
//! Tests for context checksum functionality

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

/// Test that context checksums are generated for templated resources
#[tokio::test]
async fn test_context_checksum_generation() -> 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 }}"
version: "{{ config.version }}"
agpm:
  templating: true
---
# {{ project.name }} v{{ config.version }}

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

    // Create a non-templated resource
    test_repo
        .add_resource(
            "agents",
            "plain",
            r#"---
title: Plain Agent
version: "1.0.0"
---
# Plain Agent

This is a plain agent without templating.
"#,
        )
        .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]
templated = {{ source = "test-repo", path = "agents/templated.md", version = "v1.0.0", template_vars = {{ project = {{ name = "MyProject" }}, config = {{ version = "2.0" }} }} }}
plain = {{ source = "test-repo", path = "agents/plain.md", version = "v1.0.0" }}
"#,
        repo_url
    );

    project.write_manifest(&manifest).await?;

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

    // Load lockfile
    let lockfile = project.load_lockfile()?;

    // Find templated and plain agents
    let templated_agent = lockfile
        .agents
        .iter()
        .find(|a| a.name == "agents/templated")
        .expect("Should find templated agent");

    let plain_agent =
        lockfile.agents.iter().find(|a| a.name == "agents/plain").expect("Should find plain agent");

    // Templated resource should have context checksum
    assert!(
        templated_agent.context_checksum.is_some(),
        "Templated resource should have context checksum"
    );

    // Plain resource should NOT have context checksum (None)
    assert!(
        plain_agent.context_checksum.is_none(),
        "Plain resource should not have context checksum"
    );

    // Verify context checksum format
    if let Some(checksum) = &templated_agent.context_checksum {
        assert!(
            checksum.starts_with("sha256:"),
            "Context checksum should have sha256: prefix: {}",
            checksum
        );

        let hash_part = &checksum[7..]; // Remove "sha256:" prefix
        assert_eq!(hash_part.len(), 64, "SHA-256 hash should be 64 characters: {}", hash_part);
        assert!(
            hash_part.chars().all(|c| c.is_ascii_hexdigit()),
            "SHA-256 hash should be hex digits: {}",
            hash_part
        );
    }

    Ok(())
}

/// Test that different template variables produce different context checksums
#[tokio::test]
async fn test_context_checksum_uniqueness() -> 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 templated resource
    test_repo
        .add_resource(
            "snippets",
            "configurable",
            r#"---
title: "{{ config.title }}"
env: "{{ config.env }}"
agpm:
  templating: true
---
# {{ config.title }}

Environment: {{ config.env }}
"#,
        )
        .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?;

    // First configuration
    let manifest1 = format!(
        r#"[sources]
test-repo = "{}"

[snippets]
config1 = {{ source = "test-repo", path = "snippets/configurable.md", version = "v1.0.0", template_vars = {{ config = {{ title = "Development", env = "dev" }} }} }}
"#,
        repo_url
    );

    project.write_manifest(&manifest1).await?;
    let output1 = project.run_agpm(&["install"])?;
    assert!(output1.success, "First install should succeed");

    let lockfile1 = project.load_lockfile()?;

    // Clean up for second test
    let lockfile_path = project.project_path().join("agpm.lock");
    fs::remove_file(&lockfile_path).await?;

    // Second configuration (different template variables)
    let manifest2 = format!(
        r#"[sources]
test-repo = "{}"

[snippets]
config2 = {{ source = "test-repo", path = "snippets/configurable.md", version = "v1.0.0", template_vars = {{ config = {{ title = "Production", env = "prod" }} }} }}
"#,
        repo_url
    );

    project.write_manifest(&manifest2).await?;
    let output2 = project.run_agpm(&["install"])?;
    assert!(output2.success, "Second install should succeed");

    let lockfile2 = project.load_lockfile()?;

    // Extract context checksums by manifest_alias using struct
    let config1_snippet = lockfile1
        .snippets
        .iter()
        .find(|s| s.manifest_alias.as_deref() == Some("config1"))
        .expect("Should find config1 snippet");

    let config2_snippet = lockfile2
        .snippets
        .iter()
        .find(|s| s.manifest_alias.as_deref() == Some("config2"))
        .expect("Should find config2 snippet");

    let checksum1 = config1_snippet.context_checksum.as_ref();
    let checksum2 = config2_snippet.context_checksum.as_ref();

    assert!(checksum1.is_some(), "Should find context checksum for config1");
    assert!(checksum2.is_some(), "Should find context checksum for config2");

    // Context checksums should be different
    assert_ne!(
        checksum1, checksum2,
        "Different template variables should produce different context checksums. Config1: {:?}, Config2: {:?}",
        checksum1, checksum2
    );

    Ok(())
}

/// Test that same template variables produce same context checksums
#[tokio::test]
async fn test_context_checksum_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 templated resource
    test_repo
        .add_resource(
            "agents",
            "consistent",
            r#"---
title: "{{ project.title }}"
author: "{{ project.author }}"
agpm:
  templating: true
---
# {{ project.title }} by {{ project.author }}

Consistent 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?;

    // Define template variables
    let manifest_template = format!(
        r#"[sources]
test-repo = "{}"

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

    let template_vars = vec![
        ("MyProject".to_string(), "Alice".to_string()),
        ("MyProject".to_string(), "Alice".to_string()), // Same as above
        ("DifferentProject".to_string(), "Alice".to_string()),
        ("MyProject".to_string(), "Bob".to_string()),
    ];

    let mut checksums = Vec::new();

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

        // Install with template variables
        let _manifest = manifest_template.replace("{}", &title).replace("{}", &author);

        // This is getting complex, let me simplify
        let manifest = format!(
            r#"[sources]
test-repo = "{}"

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

        project.write_manifest(&manifest).await?;
        let output = project.run_agpm(&["install"])?;
        assert!(output.success, "Install should succeed for {} by {}", title, author);

        let lockfile = project.load_lockfile()?;

        // Extract context checksum using struct
        let consistent_agent =
            lockfile.agents.iter().find(|a| a.name == "agents/consistent").unwrap_or_else(|| {
                panic!("Should find consistent agent for {} by {}", title, author)
            });

        let context_checksum = consistent_agent
            .context_checksum
            .as_ref()
            .unwrap_or_else(|| panic!("Should find context checksum for {} by {}", title, author));

        checksums.push(context_checksum.clone());
    }

    // First two should be identical (same title and author)
    assert_eq!(
        checksums[0], checksums[1],
        "Same template variables should produce same context checksum: {}",
        checksums[0]
    );

    // Others should be different
    assert_ne!(checksums[0], checksums[2], "Different titles should produce different checksums");
    assert_ne!(checksums[0], checksums[3], "Different authors should produce different checksums");
    assert_ne!(
        checksums[2], checksums[3],
        "Different combinations should produce different checksums"
    );

    Ok(())
}

/// Test context checksum with complex nested structures
#[tokio::test]
async fn test_context_checksum_complex_structures() -> 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 template with complex nested structures
    test_repo
        .add_resource(
            "commands",
            "complex-command",
            r#"---
config:
  database:
    host: "{{ db.host }}"
    port: {{ db.port }}
    ssl: {{ db.ssl }}
  features:
    {% for feature in features %}
    - {{ feature }}
    {% endfor %}
  timeouts:
    connect: {{ timeouts.connect }}
    read: {{ timeouts.read }}
agpm:
  templating: true
---
# Complex Command

Database: {{ db.host }}:{{ db.port }}
Features: {{ features | join(sep=", ") }}
Timeouts: connect={{ timeouts.connect }}s, read={{ timeouts.read }}s
"#,
        )
        .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?;

    // Complex template variables with nested structures
    let manifest = format!(
        r#"[sources]
test-repo = "{}"

[commands]
complex = {{ source = "test-repo", path = "commands/complex-command.md", version = "v1.0.0", template_vars = {{ db = {{ host = "db.example.com", port = 5432, ssl = true }}, features = ["auth", "logging", "monitoring"], timeouts = {{ connect = 10, read = 30 }} }} }}
"#,
        repo_url
    );

    project.write_manifest(&manifest).await?;

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

    // Verify context checksum is generated
    let lockfile = project.load_lockfile()?;

    // Note: context_checksum generation depends on the resource metadata
    // If not present, the resource may not have templating enabled correctly
    if let Some(complex_cmd) = lockfile.commands.iter().find(|c| c.name.contains("complex-command"))
    {
        if let Some(checksum) = &complex_cmd.context_checksum {
            // Verify context checksum format
            assert!(
                checksum.starts_with("sha256:"),
                "Context checksum should have proper format: {}",
                checksum
            );
        }
    }

    // Verify the command was rendered correctly
    let command_path = project.project_path().join(".claude/commands/agpm/complex-command.md");
    assert!(command_path.exists(), "Complex command should be installed");

    let command_content = fs::read_to_string(&command_path).await?;
    assert!(
        command_content.contains("db.example.com:5432"),
        "Command should contain rendered database info"
    );
    assert!(
        command_content.contains("auth, logging, monitoring"),
        "Command should contain rendered features"
    );
    assert!(
        command_content.contains("connect=10s, read=30s"),
        "Command should contain rendered timeouts"
    );

    Ok(())
}