mars-agents 0.7.1-rc.1

Agent package manager for .agents/ directories
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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
use std::path::Path;

use crate::error::MarsError;
use crate::hash;
use crate::lock::{CANONICAL_TARGET_ROOT, LockFile, LockIndex, LockedItem};
use crate::sync::target::{TargetItem, TargetState};
use crate::types::ContentHash;

/// The diff between current disk state and desired target state.
#[derive(Debug, Clone)]
pub struct SyncDiff {
    pub items: Vec<DiffEntry>,
}

/// A single diff entry — one of six cases from the merge matrix.
#[derive(Debug, Clone)]
pub enum DiffEntry {
    /// New item not in lock or on disk.
    Add { target: TargetItem },
    /// Source changed, local unchanged → clean update.
    Update {
        target: TargetItem,
        locked: LockedItem,
    },
    /// Source unchanged, local unchanged → skip.
    Unchanged {
        target: TargetItem,
        locked: LockedItem,
    },
    /// Source changed AND local changed → needs merge.
    Conflict {
        target: TargetItem,
        locked: LockedItem,
        local_hash: ContentHash,
    },
    /// In lock but not in target → should be removed.
    Orphan { locked: LockedItem },
    /// Local modification, source unchanged → keep local.
    LocalModified {
        target: TargetItem,
        locked: LockedItem,
        local_hash: ContentHash,
    },
}

/// Compute the diff between current disk state + lock and target state.
///
/// Uses dual checksums from the lock file:
/// - `source_checksum`: what the source provided
/// - `installed_checksum`: what mars wrote to disk
///
/// Compares current disk hash against lock checksums to determine the diff entry variant.
pub fn compute(
    root: &Path,
    lock: &LockFile,
    target: &TargetState,
    force: bool,
) -> Result<SyncDiff, MarsError> {
    let mut items = Vec::new();
    let lock_index = LockIndex::new(lock);

    // Process each target item
    for (_dest_key, target_item) in &target.items {
        if let Some(locked_item) =
            lock_index.find_output(CANONICAL_TARGET_ROOT, &target_item.dest_path)
        {
            // Item exists in lock — compare checksums
            let source_changed = target_item.source_hash != locked_item.source_checksum
                || rewritten_installed_checksum(target_item)
                    .is_some_and(|checksum| checksum != locked_item.installed_checksum);

            // Check disk hash against the expected baseline.
            // In --force mode, baseline is source_checksum so conflicted files
            // are treated as local modifications and get overwritten.
            let expected_disk_checksum = if force {
                &locked_item.source_checksum
            } else {
                &locked_item.installed_checksum
            };

            let disk_path = target_item.dest_path.resolve(root);
            let hash_path = hash_path_for_kind(&disk_path, target_item.id.kind);
            let local_changed = if hash_path.exists() {
                let disk_hash = hash::compute_hash(&hash_path, target_item.id.kind)?;
                let disk_hash = ContentHash::from(disk_hash);
                if disk_hash != *expected_disk_checksum {
                    Some(disk_hash)
                } else {
                    None
                }
            } else {
                // File was deleted locally — treat as if local changed to "nothing"
                // In this case, we should reinstall it
                None
            };

            match (source_changed, &local_changed) {
                (false, None) => {
                    // Neither changed → skip
                    if hash_path.exists() {
                        items.push(DiffEntry::Unchanged {
                            target: target_item.clone(),
                            locked: locked_item.clone(),
                        });
                    } else {
                        // File was deleted but hashes match lock — reinstall
                        items.push(DiffEntry::Add {
                            target: target_item.clone(),
                        });
                    }
                }
                (true, None) => {
                    // Source changed, local unchanged → clean update
                    items.push(DiffEntry::Update {
                        target: target_item.clone(),
                        locked: locked_item.clone(),
                    });
                }
                (false, Some(local_hash)) => {
                    // Local changed, source unchanged → keep local
                    items.push(DiffEntry::LocalModified {
                        target: target_item.clone(),
                        locked: locked_item.clone(),
                        local_hash: local_hash.clone(),
                    });
                }
                (true, Some(local_hash)) => {
                    // Both changed → conflict
                    items.push(DiffEntry::Conflict {
                        target: target_item.clone(),
                        locked: locked_item.clone(),
                        local_hash: local_hash.clone(),
                    });
                }
            }
        } else {
            // Not in lock → new item
            items.push(DiffEntry::Add {
                target: target_item.clone(),
            });
        }
    }

    // Find orphans: items in lock but not in target
    for (dest_path, locked_item) in lock.canonical_flat_items() {
        if !target.items.contains_key(&dest_path) {
            items.push(DiffEntry::Orphan {
                locked: locked_item,
            });
        }
    }

    Ok(SyncDiff { items })
}

fn rewritten_installed_checksum(target_item: &TargetItem) -> Option<ContentHash> {
    target_item
        .rewritten_content
        .as_ref()
        .map(|content| ContentHash::from(hash::hash_bytes(content.as_bytes())))
}

fn hash_path_for_kind(path: &Path, kind: crate::lock::ItemKind) -> std::path::PathBuf {
    if kind == crate::lock::ItemKind::BootstrapDoc {
        path.parent()
            .map(Path::to_path_buf)
            .unwrap_or_else(|| path.to_path_buf())
    } else {
        path.to_path_buf()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hash;
    use crate::lock::{ItemId, ItemKind, LockedItemV2, OutputRecord};
    use crate::types::{ItemName, SourceName};
    use indexmap::IndexMap;
    use std::fs;
    use std::path::PathBuf;
    use tempfile::TempDir;

    /// Create a minimal target item for testing.
    fn make_target_item(
        name: &str,
        kind: ItemKind,
        source_hash: &str,
        source_path: PathBuf,
    ) -> TargetItem {
        let dest_path = match kind {
            ItemKind::Agent => PathBuf::from("agents").join(format!("{name}.md")),
            ItemKind::Skill => PathBuf::from("skills").join(name),
            ItemKind::Hook => PathBuf::from("hooks").join(name),
            ItemKind::McpServer => PathBuf::from("mcp").join(name),
            ItemKind::BootstrapDoc => PathBuf::from("bootstrap").join(name).join("BOOTSTRAP.md"),
        };
        TargetItem {
            id: ItemId {
                kind,
                name: ItemName::from(name),
            },
            source_name: SourceName::from("test-source"),
            origin: crate::types::SourceOrigin::Dependency(SourceName::from("test-source")),
            source_id: crate::types::SourceId::Path {
                canonical: source_path.clone(),
                subpath: None,
            },
            source_path,
            dest_path: dest_path.to_string_lossy().to_string().into(),
            source_hash: ContentHash::from(source_hash),
            is_flat_skill: false,
            rewritten_content: None,
        }
    }

    /// Build a v2 `(key, LockedItemV2)` pair for inserting into `LockFile.items`.
    fn make_v2_item(
        name: &str,
        kind: ItemKind,
        source_checksum: &str,
        installed_checksum: &str,
    ) -> (String, LockedItemV2) {
        let dest_path = match kind {
            ItemKind::Agent => format!("agents/{name}.md"),
            ItemKind::Skill => format!("skills/{name}"),
            ItemKind::Hook => format!("hooks/{name}"),
            ItemKind::McpServer => format!("mcp/{name}"),
            ItemKind::BootstrapDoc => format!("bootstrap/{name}/BOOTSTRAP.md"),
        };
        let key = format!("{kind}/{name}");
        let item = LockedItemV2 {
            source: SourceName::from("test-source"),
            kind,
            version: None,
            source_checksum: ContentHash::from(source_checksum),
            outputs: vec![OutputRecord {
                target_root: ".mars".to_string(),
                dest_path: dest_path.into(),
                installed_checksum: ContentHash::from(installed_checksum),
            }],
        };
        (key, item)
    }

    #[test]
    fn new_item_produces_add() {
        let root = TempDir::new().unwrap();
        let source_dir = TempDir::new().unwrap();
        let source_path = source_dir.path().join("agents/coder.md");
        fs::create_dir_all(source_dir.path().join("agents")).unwrap();
        fs::write(&source_path, "# new agent").unwrap();

        let hash = hash::hash_bytes(b"# new agent");

        let target_item = make_target_item("coder", ItemKind::Agent, &hash, source_path);
        let mut target_items = IndexMap::new();
        target_items.insert("agents/coder.md".into(), target_item);
        let target = TargetState {
            items: target_items,
        };

        let lock = LockFile::empty();
        let diff = compute(root.path(), &lock, &target, false).unwrap();

        assert_eq!(diff.items.len(), 1);
        assert!(matches!(&diff.items[0], DiffEntry::Add { .. }));
    }

    #[test]
    fn unchanged_item_produces_unchanged() {
        let root = TempDir::new().unwrap();
        let content = b"# existing agent";
        let hash = hash::hash_bytes(content);

        // Write file to disk
        let agents_dir = root.path().join("agents");
        fs::create_dir_all(&agents_dir).unwrap();
        fs::write(agents_dir.join("coder.md"), content).unwrap();

        let source_path = PathBuf::from("/tmp/source/agents/coder.md");

        let target_item = make_target_item("coder", ItemKind::Agent, &hash, source_path);
        let mut target_items = IndexMap::new();
        target_items.insert("agents/coder.md".into(), target_item);
        let target = TargetState {
            items: target_items,
        };

        let mut lock_items = IndexMap::new();
        let (k, v) = make_v2_item("coder", ItemKind::Agent, &hash, &hash);
        lock_items.insert(k, v);
        let lock = LockFile {
            version: 2,
            dependencies: IndexMap::new(),
            items: lock_items,
            config_entries: std::collections::BTreeMap::new(),
        };

        let diff = compute(root.path(), &lock, &target, false).unwrap();
        assert_eq!(diff.items.len(), 1);
        assert!(matches!(&diff.items[0], DiffEntry::Unchanged { .. }));
    }

    #[test]
    fn source_changed_local_unchanged_produces_update() {
        let root = TempDir::new().unwrap();
        let old_content = b"# old version";
        let old_hash = hash::hash_bytes(old_content);
        let new_hash = hash::hash_bytes(b"# new version");

        // Write old content to disk (matching lock's installed_checksum)
        let agents_dir = root.path().join("agents");
        fs::create_dir_all(&agents_dir).unwrap();
        fs::write(agents_dir.join("coder.md"), old_content).unwrap();

        let source_path = PathBuf::from("/tmp/source/agents/coder.md");

        // Target has new hash
        let target_item = make_target_item("coder", ItemKind::Agent, &new_hash, source_path);
        let mut target_items = IndexMap::new();
        target_items.insert("agents/coder.md".into(), target_item);
        let target = TargetState {
            items: target_items,
        };

        // Lock has old hash
        let mut lock_items = IndexMap::new();
        let (k, v) = make_v2_item("coder", ItemKind::Agent, &old_hash, &old_hash);
        lock_items.insert(k, v);
        let lock = LockFile {
            version: 2,
            dependencies: IndexMap::new(),
            items: lock_items,
            config_entries: std::collections::BTreeMap::new(),
        };

        let diff = compute(root.path(), &lock, &target, false).unwrap();
        assert_eq!(diff.items.len(), 1);
        assert!(matches!(&diff.items[0], DiffEntry::Update { .. }));
    }

    #[test]
    fn local_changed_source_unchanged_produces_local_modified() {
        let root = TempDir::new().unwrap();
        let original_content = b"# original";
        let original_hash = hash::hash_bytes(original_content);
        let local_content = b"# locally modified";

        // Write locally modified content to disk
        let agents_dir = root.path().join("agents");
        fs::create_dir_all(&agents_dir).unwrap();
        fs::write(agents_dir.join("coder.md"), local_content).unwrap();

        let source_path = PathBuf::from("/tmp/source/agents/coder.md");

        // Target has same source hash as lock (no upstream change)
        let target_item = make_target_item("coder", ItemKind::Agent, &original_hash, source_path);
        let mut target_items = IndexMap::new();
        target_items.insert("agents/coder.md".into(), target_item);
        let target = TargetState {
            items: target_items,
        };

        // Lock also has original hash
        let mut lock_items = IndexMap::new();
        let (k, v) = make_v2_item("coder", ItemKind::Agent, &original_hash, &original_hash);
        lock_items.insert(k, v);
        let lock = LockFile {
            version: 2,
            dependencies: IndexMap::new(),
            items: lock_items,
            config_entries: std::collections::BTreeMap::new(),
        };

        let diff = compute(root.path(), &lock, &target, false).unwrap();
        assert_eq!(diff.items.len(), 1);
        assert!(matches!(&diff.items[0], DiffEntry::LocalModified { .. }));
    }

    #[test]
    fn both_changed_produces_conflict() {
        let root = TempDir::new().unwrap();
        let original_hash = hash::hash_bytes(b"# original");
        let new_source_hash = hash::hash_bytes(b"# new upstream");
        let local_content = b"# locally modified";

        // Write locally modified content
        let agents_dir = root.path().join("agents");
        fs::create_dir_all(&agents_dir).unwrap();
        fs::write(agents_dir.join("coder.md"), local_content).unwrap();

        let source_path = PathBuf::from("/tmp/source/agents/coder.md");

        // Target has new source hash (upstream changed)
        let target_item = make_target_item("coder", ItemKind::Agent, &new_source_hash, source_path);
        let mut target_items = IndexMap::new();
        target_items.insert("agents/coder.md".into(), target_item);
        let target = TargetState {
            items: target_items,
        };

        // Lock has original hash
        let mut lock_items = IndexMap::new();
        let (k, v) = make_v2_item("coder", ItemKind::Agent, &original_hash, &original_hash);
        lock_items.insert(k, v);
        let lock = LockFile {
            version: 2,
            dependencies: IndexMap::new(),
            items: lock_items,
            config_entries: std::collections::BTreeMap::new(),
        };

        let diff = compute(root.path(), &lock, &target, false).unwrap();
        assert_eq!(diff.items.len(), 1);
        assert!(matches!(&diff.items[0], DiffEntry::Conflict { .. }));
    }

    #[test]
    fn orphan_detected() {
        let root = TempDir::new().unwrap();

        // Empty target — no items wanted
        let target = TargetState {
            items: IndexMap::new(),
        };

        // Lock has an item
        let mut lock_items = IndexMap::new();
        let (k, v) = make_v2_item("old-agent", ItemKind::Agent, "sha256:aaa", "sha256:aaa");
        lock_items.insert(k, v);
        let lock = LockFile {
            version: 2,
            dependencies: IndexMap::new(),
            items: lock_items,
            config_entries: std::collections::BTreeMap::new(),
        };

        let diff = compute(root.path(), &lock, &target, false).unwrap();
        assert_eq!(diff.items.len(), 1);
        assert!(matches!(&diff.items[0], DiffEntry::Orphan { .. }));
    }

    #[test]
    fn dual_checksum_prevents_false_conflict() {
        // When mars rewrites frontmatter, source_checksum != installed_checksum.
        // The disk should match installed_checksum (what mars wrote).
        // This should NOT be detected as a local modification.
        let root = TempDir::new().unwrap();

        let source_hash = hash::hash_bytes(b"# original source");
        let installed_content = b"# rewritten by mars";
        let installed_hash = hash::hash_bytes(installed_content);

        // Disk has the mars-rewritten content
        let agents_dir = root.path().join("agents");
        fs::create_dir_all(&agents_dir).unwrap();
        fs::write(agents_dir.join("coder.md"), installed_content).unwrap();

        let source_path = PathBuf::from("/tmp/source/agents/coder.md");

        // Target has same source hash as before (no upstream change)
        let target_item = make_target_item("coder", ItemKind::Agent, &source_hash, source_path);
        let mut target_items = IndexMap::new();
        target_items.insert("agents/coder.md".into(), target_item);
        let target = TargetState {
            items: target_items,
        };

        // Lock has different source_checksum and installed_checksum
        let mut lock_items = IndexMap::new();
        let (k, v) = make_v2_item("coder", ItemKind::Agent, &source_hash, &installed_hash);
        lock_items.insert(k, v);
        let lock = LockFile {
            version: 2,
            dependencies: IndexMap::new(),
            items: lock_items,
            config_entries: std::collections::BTreeMap::new(),
        };

        let diff = compute(root.path(), &lock, &target, false).unwrap();
        assert_eq!(diff.items.len(), 1);
        // Should be Unchanged because disk matches installed_checksum
        // and source_hash matches source_checksum
        assert!(
            matches!(&diff.items[0], DiffEntry::Unchanged { .. }),
            "expected Unchanged, got {:?}",
            diff.items[0]
        );
    }

    #[test]
    fn mixed_diff_entries() {
        let root = TempDir::new().unwrap();
        let agents_dir = root.path().join("agents");
        fs::create_dir_all(&agents_dir).unwrap();

        let hash_a = hash::hash_bytes(b"# unchanged");
        let hash_b_old = hash::hash_bytes(b"# old version");
        let hash_b_new = hash::hash_bytes(b"# new version");

        // Write unchanged file
        fs::write(agents_dir.join("stable.md"), b"# unchanged").unwrap();

        // Write file with old content (will be updated)
        fs::write(agents_dir.join("updating.md"), b"# old version").unwrap();

        let source_path_a = PathBuf::from("/tmp/source/agents/stable.md");
        let source_path_b = PathBuf::from("/tmp/source/agents/updating.md");
        let source_path_c = PathBuf::from("/tmp/source/agents/new.md");

        let mut target_items = IndexMap::new();
        target_items.insert(
            "agents/stable.md".into(),
            make_target_item("stable", ItemKind::Agent, &hash_a, source_path_a),
        );
        target_items.insert(
            "agents/updating.md".into(),
            make_target_item("updating", ItemKind::Agent, &hash_b_new, source_path_b),
        );
        target_items.insert(
            "agents/new.md".into(),
            make_target_item(
                "new",
                ItemKind::Agent,
                &hash::hash_bytes(b"# brand new"),
                source_path_c,
            ),
        );
        let target = TargetState {
            items: target_items,
        };

        let mut lock_items = IndexMap::new();
        let (k, v) = make_v2_item("stable", ItemKind::Agent, &hash_a, &hash_a);
        lock_items.insert(k, v);
        let (k, v) = make_v2_item("updating", ItemKind::Agent, &hash_b_old, &hash_b_old);
        lock_items.insert(k, v);
        let (k, v) = make_v2_item("orphan", ItemKind::Agent, "sha256:xxx", "sha256:xxx");
        lock_items.insert(k, v);
        let lock = LockFile {
            version: 2,
            dependencies: IndexMap::new(),
            items: lock_items,
            config_entries: std::collections::BTreeMap::new(),
        };

        let diff = compute(root.path(), &lock, &target, false).unwrap();
        assert_eq!(diff.items.len(), 4); // Unchanged + Update + Add + Orphan

        let unchanged_count = diff
            .items
            .iter()
            .filter(|d| matches!(d, DiffEntry::Unchanged { .. }))
            .count();
        let update_count = diff
            .items
            .iter()
            .filter(|d| matches!(d, DiffEntry::Update { .. }))
            .count();
        let add_count = diff
            .items
            .iter()
            .filter(|d| matches!(d, DiffEntry::Add { .. }))
            .count();
        let orphan_count = diff
            .items
            .iter()
            .filter(|d| matches!(d, DiffEntry::Orphan { .. }))
            .count();

        assert_eq!(unchanged_count, 1);
        assert_eq!(update_count, 1);
        assert_eq!(add_count, 1);
        assert_eq!(orphan_count, 1);
    }

    #[test]
    fn force_uses_source_checksum_for_local_change_detection() {
        let root = TempDir::new().unwrap();
        let upstream_content = b"# upstream";
        let conflicted_content = b"<<<<<<< local\n# local\n=======\n# upstream\n>>>>>>> upstream\n";

        let source_hash = hash::hash_bytes(upstream_content);
        let installed_hash = hash::hash_bytes(conflicted_content);

        // Disk matches prior conflicted content from last sync.
        let agents_dir = root.path().join("agents");
        fs::create_dir_all(&agents_dir).unwrap();
        fs::write(agents_dir.join("coder.md"), conflicted_content).unwrap();

        let mut target_items = IndexMap::new();
        target_items.insert(
            "agents/coder.md".into(),
            make_target_item(
                "coder",
                ItemKind::Agent,
                &source_hash,
                PathBuf::from("/tmp/source/agents/coder.md"),
            ),
        );
        let target = TargetState {
            items: target_items,
        };

        let mut lock_items = IndexMap::new();
        lock_items.insert(
            "agent/coder".to_string(),
            LockedItemV2 {
                source: "test-source".into(),
                kind: ItemKind::Agent,
                version: None,
                source_checksum: source_hash.clone().into(),
                outputs: vec![OutputRecord {
                    target_root: ".mars".to_string(),
                    dest_path: "agents/coder.md".into(),
                    installed_checksum: installed_hash.into(),
                }],
            },
        );
        let lock = LockFile {
            version: 2,
            dependencies: IndexMap::new(),
            items: lock_items,
            config_entries: std::collections::BTreeMap::new(),
        };

        let normal = compute(root.path(), &lock, &target, false).unwrap();
        assert!(matches!(&normal.items[0], DiffEntry::Unchanged { .. }));

        let forced = compute(root.path(), &lock, &target, true).unwrap();
        assert!(matches!(&forced.items[0], DiffEntry::LocalModified { .. }));
    }

    #[test]
    fn canonical_diff_ignores_non_canonical_output_checksum() {
        let root = TempDir::new().unwrap();
        let canonical_content = b"# canonical";
        let canonical_hash = hash::hash_bytes(canonical_content);
        let pi_hash = hash::hash_bytes(b"# pi rewrite");

        let agents_dir = root.path().join("agents");
        fs::create_dir_all(&agents_dir).unwrap();
        fs::write(agents_dir.join("coder.md"), canonical_content).unwrap();

        let mut target_items = IndexMap::new();
        target_items.insert(
            "agents/coder.md".into(),
            make_target_item(
                "coder",
                ItemKind::Agent,
                &canonical_hash,
                PathBuf::from("/tmp/source/agents/coder.md"),
            ),
        );
        let target = TargetState {
            items: target_items,
        };

        let mut lock_items = IndexMap::new();
        lock_items.insert(
            "agent/coder".to_string(),
            LockedItemV2 {
                source: SourceName::from("test-source"),
                kind: ItemKind::Agent,
                version: None,
                source_checksum: canonical_hash.clone().into(),
                outputs: vec![
                    OutputRecord {
                        target_root: ".mars".to_string(),
                        dest_path: "agents/coder.md".into(),
                        installed_checksum: canonical_hash.clone().into(),
                    },
                    OutputRecord {
                        target_root: ".pi".to_string(),
                        dest_path: "agents/coder.md".into(),
                        installed_checksum: pi_hash.into(),
                    },
                ],
            },
        );
        let lock = LockFile {
            version: 2,
            dependencies: IndexMap::new(),
            items: lock_items,
            config_entries: std::collections::BTreeMap::new(),
        };

        let diff = compute(root.path(), &lock, &target, false).unwrap();
        assert_eq!(diff.items.len(), 1);
        assert!(
            matches!(&diff.items[0], DiffEntry::Unchanged { .. }),
            "expected Unchanged, got {:?}",
            diff.items[0]
        );
    }

    #[test]
    fn rewritten_content_change_produces_update() {
        let root = TempDir::new().unwrap();

        let source_content = b"---\nskills:\n- planning\n---\n# Agent\n";
        let source_hash = hash::hash_bytes(source_content);
        let old_installed_content = b"---\nskills:\n- planning\n---\n# Agent\n";
        let old_installed_hash = hash::hash_bytes(old_installed_content);
        let rewritten_content = "---\nskills:\n- strategy\n---\n# Agent\n";
        let rewritten_hash = hash::hash_bytes(rewritten_content.as_bytes());

        let agents_dir = root.path().join("agents");
        fs::create_dir_all(&agents_dir).unwrap();
        fs::write(agents_dir.join("coder.md"), old_installed_content).unwrap();

        let mut target_items = IndexMap::new();
        target_items.insert(
            "agents/coder.md".into(),
            TargetItem {
                id: ItemId {
                    kind: ItemKind::Agent,
                    name: "coder".into(),
                },
                source_name: SourceName::from("test-source"),
                origin: crate::types::SourceOrigin::Dependency(SourceName::from("test-source")),
                source_id: crate::types::SourceId::Path {
                    canonical: PathBuf::from("/tmp/source/agents/coder.md"),
                    subpath: None,
                },
                source_path: PathBuf::from("/tmp/source/agents/coder.md"),
                dest_path: "agents/coder.md".into(),
                source_hash: source_hash.clone().into(),
                is_flat_skill: false,
                rewritten_content: Some(rewritten_content.to_string()),
            },
        );
        let target = TargetState {
            items: target_items,
        };

        let mut lock_items = IndexMap::new();
        lock_items.insert(
            "agent/coder".to_string(),
            LockedItemV2 {
                source: SourceName::from("test-source"),
                kind: ItemKind::Agent,
                version: None,
                source_checksum: source_hash.into(),
                outputs: vec![OutputRecord {
                    target_root: ".mars".to_string(),
                    dest_path: "agents/coder.md".into(),
                    installed_checksum: old_installed_hash.clone().into(),
                }],
            },
        );
        let lock = LockFile {
            version: 2,
            dependencies: IndexMap::new(),
            items: lock_items,
            config_entries: std::collections::BTreeMap::new(),
        };

        let diff = compute(root.path(), &lock, &target, false).unwrap();
        assert_eq!(diff.items.len(), 1);
        assert!(matches!(&diff.items[0], DiffEntry::Update { .. }));

        assert_ne!(rewritten_hash, old_installed_hash);
    }
}