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
//! Checksum computation and verification for lockfile integrity.
//!
//! This module provides SHA-256 checksum operations for verifying file integrity,
//! detecting corruption, and ensuring reproducible installations.
use anyhow::{Context, Result};
use std::fs;
use std::path::Path;
use super::{LockFile, ResourceId};
impl LockFile {
/// Compute SHA-256 checksum for file integrity verification.
///
/// Detects corruption, tampering, or changes after installation.
///
/// # Arguments
///
/// * `path` - Path to the file to checksum
///
/// # Returns
///
/// * `Ok(String)` - Checksum in format "`sha256:hexadecimal_hash`"
/// * `Err(anyhow::Error)` - File read error with detailed context
///
/// # Checksum Format
///
/// The returned checksum follows the format:
/// - **Algorithm prefix**: "sha256:"
/// - **Hash encoding**: Lowercase hexadecimal
/// - **Length**: 71 characters total (7 for prefix + 64 hex digits)
///
/// # Examples
///
/// ```rust,no_run
/// use std::path::Path;
/// use agpm_cli::lockfile::LockFile;
///
/// # fn example() -> anyhow::Result<()> {
/// let checksum = LockFile::compute_checksum(Path::new("example.md"))?;
/// println!("File checksum: {}", checksum);
/// // Output: "sha256:a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3"
/// # Ok(())
/// # }
/// ```
///
/// # Error Handling
///
/// Provides detailed error context for common issues:
/// - **File not found**: Suggests checking the path
/// - **Permission denied**: Suggests checking file permissions
/// - **IO errors**: Suggests checking disk health or file locks
///
/// # Security Considerations
///
/// - Uses SHA-256, a cryptographically secure hash function
/// - Suitable for integrity verification and tamper detection
/// - Consistent across platforms (Windows, macOS, Linux)
/// - Not affected by line ending differences (hashes actual bytes)
///
/// # Performance
///
/// The method reads the entire file into memory before hashing.
/// For very large files (>100MB), consider streaming implementations
/// in future versions.
pub fn compute_checksum(path: &Path) -> Result<String> {
use sha2::{Digest, Sha256};
let content = fs::read(path).with_context(|| {
format!(
"Cannot read file for checksum calculation: {}\n\n\
This error occurs when verifying file integrity.\n\
Check that the file exists and is readable.",
path.display()
)
})?;
let mut hasher = Sha256::new();
hasher.update(&content);
let result = hasher.finalize();
Ok(format!("sha256:{}", hex::encode(result)))
}
/// Verify file matches expected checksum.
///
/// Computes current checksum and compares with expected value.
///
/// # Arguments
///
/// * `path` - Path to the file to verify
/// * `expected` - Expected checksum in "sha256:hex" format
///
/// # Returns
///
/// * `Ok(true)` - File checksum matches expected value
/// * `Ok(false)` - File checksum does not match (corruption detected)
/// * `Err(anyhow::Error)` - File read error or checksum calculation failed
///
/// # Examples
///
/// ```rust,no_run
/// use std::path::Path;
/// use agpm_cli::lockfile::LockFile;
///
/// # fn example() -> anyhow::Result<()> {
/// let expected = "sha256:a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3";
/// let is_valid = LockFile::verify_checksum(Path::new("example.md"), expected)?;
///
/// if is_valid {
/// println!("File integrity verified");
/// } else {
/// println!("WARNING: File has been modified or corrupted!");
/// }
/// # Ok(())
/// # }
/// ```
///
/// # Use Cases
///
/// - **Installation verification**: Ensure copied files are intact
/// - **Periodic validation**: Detect file corruption over time
/// - **Security checks**: Detect unauthorized modifications
/// - **Troubleshooting**: Diagnose installation issues
///
/// # Performance
///
/// This method internally calls [`compute_checksum`](Self::compute_checksum),
/// so it has the same performance characteristics. For bulk verification
/// operations, consider caching computed checksums.
///
/// # Security
///
/// The comparison is performed using standard string equality, which is
/// not timing-attack resistant. Since checksums are not secrets, this
/// is acceptable for integrity verification purposes.
pub fn verify_checksum(path: &Path, expected: &str) -> Result<bool> {
let actual = Self::compute_checksum(path)?;
Ok(actual == expected)
}
/// Update checksum for resource identified by ResourceId.
///
/// Used after installation to record actual file checksum. ResourceId ensures unique
/// identification via name, source, tool, and template_vars.
///
/// # Arguments
///
/// * `id` - The unique identifier for the resource
/// * `checksum` - The new SHA-256 checksum in "sha256:hex" format
///
/// # Returns
///
/// Returns `true` if the resource was found and updated, `false` otherwise.
///
/// # Examples
///
/// ```rust,no_run
/// # use agpm_cli::lockfile::{LockFile, LockedResourceBuilder, ResourceId};
/// # use agpm_cli::core::ResourceType;
/// # use agpm_cli::utils::compute_variant_inputs_hash;
/// # let mut lockfile = LockFile::default();
/// # // First add a resource to update
/// # let resource = LockedResourceBuilder::new(
/// # "my-agent".to_string(),
/// # "my-agent.md".to_string(),
/// # "".to_string(),
/// # "agents/my-agent.md".to_string(),
/// # ResourceType::Agent,
/// # )
/// # .tool(Some("claude-code".to_string()))
/// # .build();
/// # lockfile.add_typed_resource("my-agent".to_string(), resource, ResourceType::Agent);
/// let variant_hash = compute_variant_inputs_hash(&serde_json::json!({})).unwrap_or_default();
/// let id = ResourceId::new("my-agent", None::<String>, Some("claude-code"), ResourceType::Agent, variant_hash);
/// let updated = lockfile.update_resource_checksum(&id, "sha256:abcdef123456...");
/// assert!(updated);
/// ```
pub fn update_resource_checksum(&mut self, id: &ResourceId, checksum: &str) -> bool {
// Try each resource type until we find a match by comparing ResourceIds
for resource in &mut self.agents {
if resource.id() == *id {
resource.checksum = checksum.to_string();
return true;
}
}
for resource in &mut self.snippets {
if resource.id() == *id {
resource.checksum = checksum.to_string();
return true;
}
}
for resource in &mut self.commands {
if resource.id() == *id {
resource.checksum = checksum.to_string();
return true;
}
}
for resource in &mut self.scripts {
if resource.id() == *id {
resource.checksum = checksum.to_string();
return true;
}
}
for resource in &mut self.hooks {
if resource.id() == *id {
resource.checksum = checksum.to_string();
return true;
}
}
for resource in &mut self.mcp_servers {
if resource.id() == *id {
resource.checksum = checksum.to_string();
return true;
}
}
false
}
/// Update context checksum for resource by ResourceId.
///
/// Stores the SHA-256 checksum of template rendering inputs (context) in the lockfile.
/// This is different from the file checksum which covers the final rendered content.
///
/// # Arguments
///
/// * `id` - The ResourceId identifying the resource to update
/// * `context_checksum` - The SHA-256 checksum of template context, or None for non-templated resources
///
/// # Returns
///
/// Returns `true` if the resource was found and updated, `false` otherwise.
///
/// # Examples
///
/// ```rust,ignore
/// let mut lockfile = LockFile::new();
/// let id = ResourceId::new("my-agent", None::<String>, Some("claude-code"), ResourceType::Agent, serde_json::json!({}));
/// let updated = lockfile.update_resource_context_checksum(&id, Some("sha256:context123456..."));
/// assert!(updated);
/// ```
pub fn update_resource_context_checksum(
&mut self,
id: &ResourceId,
context_checksum: &str,
) -> bool {
// Try each resource type until we find a match by comparing ResourceIds
for resource in &mut self.agents {
if resource.id() == *id {
resource.context_checksum = Some(context_checksum.to_string());
return true;
}
}
for resource in &mut self.snippets {
if resource.id() == *id {
resource.context_checksum = Some(context_checksum.to_string());
return true;
}
}
for resource in &mut self.commands {
if resource.id() == *id {
resource.context_checksum = Some(context_checksum.to_string());
return true;
}
}
for resource in &mut self.scripts {
if resource.id() == *id {
resource.context_checksum = Some(context_checksum.to_string());
return true;
}
}
for resource in &mut self.hooks {
if resource.id() == *id {
resource.context_checksum = Some(context_checksum.to_string());
return true;
}
}
for resource in &mut self.mcp_servers {
if resource.id() == *id {
resource.context_checksum = Some(context_checksum.to_string());
return true;
}
}
false
}
/// Update applied patches for resource by name.
///
/// Stores project patches in main lockfile; private patches go to agpm.private.lock.
/// Takes `AppliedPatches` from installer.
///
/// # Arguments
///
/// * `name` - The name of the resource to update
/// * `applied_patches` - The patches that were applied (from `AppliedPatches` struct)
///
/// # Returns
///
/// Returns `true` if the resource was found and updated, `false` otherwise.
///
/// # Examples
///
/// ```no_run
/// # use agpm_cli::lockfile::LockFile;
/// # use agpm_cli::manifest::patches::AppliedPatches;
/// # use std::collections::HashMap;
/// # let mut lockfile = LockFile::new();
/// let mut applied = AppliedPatches::new();
/// applied.project.insert("model".to_string(), toml::Value::String("haiku".into()));
///
/// let updated = lockfile.update_resource_applied_patches("my-agent", &applied);
/// assert!(updated);
/// ```
pub fn update_resource_applied_patches(
&mut self,
name: &str,
applied_patches: &crate::manifest::patches::AppliedPatches,
) -> bool {
// Store ONLY project patches in the main lockfile (agpm.lock)
// Private patches are stored separately in agpm.private.lock
// This ensures the main lockfile is deterministic and safe to commit
let project_patches = applied_patches.project.clone();
// Try each resource type until we find a match
for resource in &mut self.agents {
if resource.name == name {
resource.applied_patches = project_patches;
return true;
}
}
for resource in &mut self.snippets {
if resource.name == name {
resource.applied_patches = project_patches;
return true;
}
}
for resource in &mut self.commands {
if resource.name == name {
resource.applied_patches = project_patches;
return true;
}
}
for resource in &mut self.scripts {
if resource.name == name {
resource.applied_patches = project_patches;
return true;
}
}
for resource in &mut self.hooks {
if resource.name == name {
resource.applied_patches = project_patches;
return true;
}
}
for resource in &mut self.mcp_servers {
if resource.name == name {
resource.applied_patches = project_patches;
return true;
}
}
false
}
}