dalo 0.7.2

Git-backed skill management for AI 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
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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
//! Status model and renderable command output.

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

use serde::Serialize;

use crate::adopt::{
    AdoptReport, KeepReport, RemoveOwnedReport, ResolveListReport, TargetScanWarning,
    UnmanagedSkill,
};
use crate::approval::ApprovalReport;
use crate::catalog::{CatalogDrift, CatalogInspectReport, CatalogSelectReport};
use crate::doctor::{DoctorReport, DoctorSeverity};
use crate::error::DaloResult;
use crate::instructions::{
    self, DiscoveredPack, InstructionBlockDrift, InstructionPackReport, TopicOverlap,
};
use crate::inventory::InventoryWarning;
use crate::lockfile::{self, LockDrift, LockDriftCode};
use crate::materialize::SyncReport;
use crate::resolver::{self, Resolution};
use crate::source::{
    SourceAddReport, SourceConfig, SourceKind, SourceListReport, SourcePriorityReport,
    SourceRemoveReport,
};
use crate::store::{self, ApprovalsFile, InitReport, StorePaths};
use crate::target::{TargetDetectReport, TargetLinkReport, TargetUnlinkReport};
use crate::term;

/// Full status report.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct StatusReport {
    /// Store root.
    pub store: PathBuf,
    /// Source scan summaries.
    pub sources: Vec<SourceStatus>,
    /// Configured materialization targets.
    pub targets: Vec<TargetStatus>,
    /// Inventory warnings.
    pub inventory_warnings: Vec<InventoryWarning>,
    /// Resolution output.
    pub resolution: Resolution,
    /// Previous-lock comparison against the live resolution.
    pub lock: LockStatus,
    /// Unmanaged skills found in linked targets.
    pub unmanaged_skills: Vec<UnmanagedSkill>,
    /// Non-fatal target directory scan warnings.
    pub target_warnings: Vec<TargetScanWarning>,
    /// Discovered instruction packs (available and enabled).
    pub instruction_packs: Vec<DiscoveredPack>,
    /// Declared-topic overlaps among active instruction packs (advisory).
    pub instruction_pack_overlaps: Vec<TopicOverlap>,
    /// Active instruction blocks that are missing, malformed, or stale.
    pub instruction_block_drifts: Vec<InstructionBlockDrift>,
}

/// User lock status derived during `status`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct LockStatus {
    /// User lock path.
    pub path: PathBuf,
    /// Persisted schema version.
    pub schema_version: u32,
    /// Drift between the previous lock and the live resolution.
    pub drift: Vec<LockDrift>,
}

/// One source status entry.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SourceStatus {
    /// Source ID.
    pub id: String,
    /// Source kind.
    pub kind: SourceKind,
    /// Source path.
    pub path: PathBuf,
    /// Priority.
    pub priority: i32,
    /// Whether the source is enabled.
    pub enabled: bool,
    /// Whether the source path exists.
    pub exists: bool,
    /// Number of scanned skills.
    pub skill_count: usize,
    /// Optional non-fatal scan error.
    pub error: Option<String>,
}

/// One configured target shown by `status`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct TargetStatus {
    /// Logical target ID.
    pub id: String,
    /// Target directory.
    pub path: PathBuf,
    /// Whether the target is enabled for materialization.
    pub linked: bool,
    /// Whether the target directory exists.
    pub exists: bool,
}

/// Build the current status report.
#[must_use = "the status report should be rendered or inspected"]
pub fn build_status_report(store_root: &Path) -> DaloResult<StatusReport> {
    let paths = StorePaths::new(store_root.to_path_buf());
    let config = store::read_config(&paths)?;
    let approvals = store::read_approvals(&paths)?;
    let previous_lock = store::read_user_lock(&paths)?;
    let state = store::read_state(&paths)?;

    // The shared pipeline scans every enabled source once and resolves it; we
    // reuse its per-source scan outcomes here for the status detail instead of
    // re-scanning. Disabled sources are not scanned, so we render them directly.
    let live = resolver::resolve_from_config(&config, approvals.approvals);
    let scan_by_id = live
        .scans
        .iter()
        .map(|scan| (scan.source.id.as_str(), scan))
        .collect::<std::collections::BTreeMap<_, _>>();

    let mut sources = Vec::new();
    let mut inventory_warnings = Vec::new();

    for source in &config.sources {
        let status = if let Some(scan) = scan_by_id.get(source.id.as_str()) {
            if let Some(inventory) = &scan.inventory {
                inventory_warnings.extend(inventory.warnings.iter().cloned());
            }
            SourceStatus {
                id: source.id.clone(),
                kind: source.kind,
                path: source.path.clone(),
                priority: source.priority,
                enabled: true,
                exists: source.path.exists(),
                skill_count: scan.inventory.as_ref().map_or(0, |inv| inv.skills.len()),
                error: scan.error.clone(),
            }
        } else {
            SourceStatus {
                id: source.id.clone(),
                kind: source.kind,
                path: source.path.clone(),
                priority: source.priority,
                enabled: false,
                exists: source.path.exists(),
                skill_count: 0,
                error: None,
            }
        };
        sources.push(status);
    }

    sources.sort_by(|left, right| {
        left.priority
            .cmp(&right.priority)
            .then_with(|| left.id.cmp(&right.id))
    });
    inventory_warnings.sort_by(|left, right| left.path.cmp(&right.path));

    let mut targets = state
        .targets
        .iter()
        .map(|target| TargetStatus {
            id: target.id.clone(),
            path: target.path.clone(),
            linked: target.enabled,
            exists: target.path.exists(),
        })
        .collect::<Vec<_>>();
    targets.sort_by(|left, right| left.id.cmp(&right.id));

    let resolution = live.resolution;
    let live_lock = lockfile::build_user_lock(&config.sources, &resolution, None);
    let mut drift = lockfile::compare_user_lock(&previous_lock, &live_lock);
    suppress_initial_local_source_drift(&previous_lock, &mut drift);
    let lock = LockStatus {
        path: paths.lock_file.clone(),
        schema_version: previous_lock.schema_version,
        drift,
    };
    let unmanaged_scan = crate::adopt::discover_unmanaged_skill_scan(&paths)?;

    let instruction_packs = instructions::discover_packs(
        &paths,
        &config.sources,
        &previous_lock.active_instruction_packs,
    );
    let active_packs = instruction_packs
        .iter()
        .filter(|pack| pack.enabled)
        .cloned()
        .collect::<Vec<_>>();
    let instruction_pack_overlaps = instructions::topic_overlaps(&active_packs);
    let instruction_block_drifts = instructions::instruction_block_drifts(
        &paths,
        &config.sources,
        &previous_lock.active_instruction_packs,
    );

    Ok(StatusReport {
        store: store_root.to_path_buf(),
        sources,
        targets,
        inventory_warnings,
        resolution,
        lock,
        unmanaged_skills: unmanaged_scan.unmanaged_skills,
        target_warnings: unmanaged_scan.warnings,
        instruction_packs,
        instruction_pack_overlaps,
        instruction_block_drifts,
    })
}

fn suppress_initial_local_source_drift(
    previous_lock: &lockfile::UserLock,
    drift: &mut Vec<LockDrift>,
) {
    if previous_lock.sources.is_empty()
        && previous_lock.active_skills.is_empty()
        && previous_lock.pending_approval_skills.is_empty()
        && previous_lock.unlinked_skills.is_empty()
        && previous_lock.target_materializations.is_empty()
    {
        drift.retain(|entry| {
            !(entry.code == LockDriftCode::SourceAdded && entry.subject == "local")
        });
    }
}

/// Print a human-readable init report.
pub fn print_init_report(report: &InitReport) {
    println!("dalo store: {}", report.store.display());

    for operation in &report.operations {
        println!(
            "{:<8} {:<12} {}",
            operation.status.as_str(),
            operation.action.as_str(),
            operation.path.display()
        );
    }
    println!();

    if !report.validation_warnings.is_empty() {
        println!("Store needs attention:");
        for warning in &report.validation_warnings {
            println!("  warning {}: {}", warning.path.display(), warning.message);
        }
        println!("Fix the files above before using dalo.");
        return;
    }

    println!("Store ready.");
    println!("Next steps:");
    println!("  1. dalo target link <codex|claude|openclaw|hermes>");
    println!("  2. dalo source add <id> <git-url>");
    println!("  3. dalo sync");
}

/// Print local approval records.
pub fn print_approval_list(report: &ApprovalsFile) {
    if report.approvals.is_empty() {
        println!("no approvals recorded");
        return;
    }
    for approval in &report.approvals {
        println!("{} {}", approval.scope, approval.value);
    }
}

/// Print one approval mutation result.
pub fn print_approval_report(report: &ApprovalReport) {
    let verb = if report.dry_run && report.action != "unchanged" {
        "planned"
    } else {
        report.action.as_str()
    };
    println!("{verb} {} {}", report.scope, report.value);
}

/// Print a human-readable status report.
pub fn print_status_report(report: &StatusReport) {
    println!("dalo store: {}", report.store.display());
    println!("sources:");
    if report.sources.is_empty() {
        println!("  none");
    } else {
        for source in &report.sources {
            let state = if source.enabled {
                "enabled"
            } else {
                "disabled"
            };
            let error = source
                .error
                .as_ref()
                .map_or(String::new(), |error| format!(" ({error})"));
            println!(
                "  {:<12} {:<5} priority={:<4} skills={:<3} {}{}",
                source.id, source.kind, source.priority, source.skill_count, state, error
            );
        }
    }

    println!("targets:");
    if report.targets.is_empty() {
        println!("  none linked (run: dalo target link <codex|claude|openclaw|hermes>)");
    } else {
        for target in &report.targets {
            let state = if !target.linked {
                "unlinked"
            } else if target.exists {
                "linked"
            } else {
                "missing"
            };
            println!("  {:<12} {:<7} {}", target.id, state, target.path.display());
        }
    }

    println!("active skills:");
    if report.resolution.active_skills.is_empty() {
        println!("  none");
    } else {
        for skill in &report.resolution.active_skills {
            let marker = if skill.local_override {
                " local_override"
            } else {
                ""
            };
            println!("  {} -> {}{}", skill.slot_name, skill.source_ref, marker);
        }
    }

    if !report.resolution.pending_approval_skills.is_empty() {
        println!("pending approval:");
        for skill in &report.resolution.pending_approval_skills {
            println!(
                "  {} -> {} (run: dalo approve skill {})",
                skill.slot_name, skill.source_ref, skill.source_ref
            );
        }
    }

    if !report.resolution.unlinked_skills.is_empty() {
        println!("unlinked skills:");
        for skill in &report.resolution.unlinked_skills {
            println!(
                "  {} -> {} reason=shadowed by={}",
                skill.skill.slot_name, skill.skill.source_ref, skill.shadowed_by
            );
        }
    }

    if !report.resolution.blocked_skills.is_empty() {
        println!("blocked skills (required closure not linkable):");
        for blocked in &report.resolution.blocked_skills {
            println!(
                "  {} -> {} requires=`{}` reason={}",
                blocked.skill.slot_name,
                blocked.skill.source_ref,
                blocked.requirement,
                resolver::closure_block_reason_name(blocked.reason)
            );
        }
    }

    if !report.resolution.diagnostics.is_empty() {
        println!("resolution diagnostics:");
        for diagnostic in &report.resolution.diagnostics {
            println!(
                "  {}: {}",
                resolver::diagnostic_code_name(diagnostic.code),
                diagnostic.message
            );
        }
    }

    if !report.lock.drift.is_empty() {
        println!("lock drift:");
        for drift in &report.lock.drift {
            println!("  {} {}: {}", drift.code, drift.subject, drift.message);
        }
    }

    if !report.unmanaged_skills.is_empty() {
        println!("unmanaged skills:");
        for skill in &report.unmanaged_skills {
            let marker = if skill.protected { " protected" } else { "" };
            println!("  {} -> {}{}", skill.id, skill.path.display(), marker);
        }
    }

    if !report.inventory_warnings.is_empty() {
        println!("inventory warnings:");
        for warning in &report.inventory_warnings {
            println!(
                "  {} {}: {}",
                warning.code,
                warning.path.display(),
                warning.message
            );
        }
    }

    if !report.target_warnings.is_empty() {
        println!("target warnings:");
        for warning in &report.target_warnings {
            println!(
                "  {} {}: {}",
                warning.code.as_str(),
                warning.path.display(),
                warning.message
            );
        }
    }

    if !report.instruction_packs.is_empty() {
        println!("instruction packs:");
        for pack in &report.instruction_packs {
            let state = if pack.enabled { "enabled" } else { "available" };
            println!("  {} ({state})", pack.pack_ref());
        }
    }

    if !report.instruction_pack_overlaps.is_empty() {
        println!("instruction pack topic overlaps:");
        for overlap in &report.instruction_pack_overlaps {
            println!(
                "  {} <-> {} share: {}",
                overlap.packs[0],
                overlap.packs[1],
                overlap.topics.join(", ")
            );
        }
    }

    if !report.instruction_block_drifts.is_empty() {
        println!("instruction block drift:");
        for drift in &report.instruction_block_drifts {
            println!(
                "  {}:{} {} at {} ({})",
                drift.source_id,
                drift.pack_id,
                instruction_block_drift_kind_label(drift.kind),
                drift.target.display(),
                drift.message
            );
        }
    }
}

/// Print a human-readable sync report.
pub fn print_sync_report(report: &SyncReport) {
    println!("dalo store: {}", report.store.display());
    if report.operations.is_empty() {
        if report.linked_targets == 0 && !report.resolution.active_skills.is_empty() {
            println!(
                "nothing materialized: {} skills resolved but no targets are linked; run `dalo target link <codex|claude|openclaw|hermes>`",
                report.resolution.active_skills.len()
            );
        } else if report.resolution.pending_approval_skills.is_empty()
            && report.resolution.blocked_skills.is_empty()
            && !report
                .resolution
                .diagnostics
                .iter()
                .any(|diagnostic| diagnostic.code.requires_review())
            && report.degraded_sources.is_empty()
        {
            println!("nothing to sync: 0 skills materialized; store is up to date");
        } else {
            println!("nothing materialized: resolution is incomplete");
        }
    } else {
        for operation in &report.operations {
            let desired = operation
                .desired_path
                .as_ref()
                .map_or(String::new(), |path| format!(" -> {}", path.display()));
            let reason = operation
                .reason
                .as_ref()
                .map_or(String::new(), |reason| format!(" ({reason})"));
            println!(
                "{:<8} {:<10} {}{}{}",
                operation.status.as_str(),
                operation.kind.as_str(),
                operation.link_path.display(),
                desired,
                reason
            );
        }
    }
    let prefix = if report.operations.is_empty() {
        "  "
    } else {
        ""
    };
    for skill in &report.resolution.pending_approval_skills {
        println!(
            "{prefix}pending approval: {} (run: dalo approve skill {})",
            skill.source_ref, skill.source_ref
        );
    }
    for blocked in &report.resolution.blocked_skills {
        println!(
            "{prefix}blocked: {} requires {}",
            blocked.skill.source_ref, blocked.requirement
        );
    }
    for source in &report.degraded_sources {
        println!("{prefix}degraded source: {} ({})", source.id, source.reason);
    }
    for diagnostic in &report.resolution.diagnostics {
        println!(
            "{prefix}diagnostic: {}: {}",
            resolver::diagnostic_code_name(diagnostic.code),
            diagnostic.message
        );
    }
}

/// Print a human-readable source add report.
pub fn print_source_add_report(report: &SourceAddReport) {
    let verb = if report.dry_run { "would add" } else { "added" };
    println!(
        "{verb} source {} -> {}",
        report.source.id,
        report.source.path.display()
    );
}

/// Print a source removal report.
pub fn print_source_remove_report(report: &SourceRemoveReport) {
    let verb = if report.dry_run {
        "would remove"
    } else {
        "removed"
    };
    println!("{verb} source {}", report.source_id);
    if report.kept_checkout {
        println!(
            "  checkout: retained {} (move or remove it before re-adding source `{}`)",
            report.checkout_path.display(),
            report.source_id
        );
    } else if report.cleanup_warnings.is_empty() {
        println!("  checkout: removed {}", report.checkout_path.display());
    } else {
        println!(
            "  checkout: cleanup incomplete {}",
            report.checkout_path.display()
        );
    }
    println!("  approvals removed: {}", report.removed_approvals);
    println!("  catalog lock removed: {}", report.removed_catalog_lock);
    if !report.deactivated_skills.is_empty() {
        println!("  deactivated skills:");
        for skill in &report.deactivated_skills {
            println!("    {skill}");
        }
    }
    if !report.reconciled_links.is_empty() {
        println!("  reconciled links:");
        for link in &report.reconciled_links {
            println!("    {:<11} {}", link.kind.as_str(), link.path.display());
        }
    }
    for warning in &report.cleanup_warnings {
        println!("  warning: {warning}");
    }
    println!("  affected artifacts:");
    for path in &report.affected_paths {
        println!("    {}", path.display());
    }
}

/// Print a human-readable source list report.
pub fn print_source_list_report(report: &SourceListReport) {
    if report.sources.is_empty() {
        println!("no sources configured");
        return;
    }
    for source in &report.sources {
        println!(
            "{:<12} {:<5} priority={:<4} enabled={} {}",
            source.id,
            source.kind,
            source.priority,
            source.enabled,
            source.path.display()
        );
    }
}

/// Print a human-readable source priority report.
pub fn print_source_priority_report(report: &SourcePriorityReport) {
    let verb = if report.dry_run {
        "would update"
    } else {
        "updated"
    };
    println!(
        "{verb} source {} priority={}",
        report.source.id, report.source.priority
    );
}

/// Print a human-readable catalog add report.
pub fn print_catalog_add_report(source: &SourceConfig, dry_run: bool) {
    let verb = if dry_run { "would add" } else { "added" };
    println!(
        "{verb} catalog source {} -> {}",
        source.id,
        source.path.display()
    );
}

/// Print a human-readable catalog inspect report.
pub fn print_catalog_inspect_report(report: &CatalogInspectReport) {
    println!(
        "catalog {}: {} available skill(s)",
        report.source_id,
        report.candidates.len()
    );
    for candidate in &report.candidates {
        let marker = if candidate.selected { "*" } else { " " };
        let id = candidate.id.as_deref().unwrap_or("-");
        println!(
            "  {marker} {:<24} id={:<24} {}",
            candidate.slot_name, id, candidate.path
        );
    }
}

/// Print a human-readable catalog select report.
pub fn print_catalog_select_report(report: &CatalogSelectReport) {
    let verb = if report.dry_run {
        "would select"
    } else {
        "selected"
    };
    if report.selected.is_empty() {
        println!("catalog {}: no skills selected", report.source_id);
    } else {
        println!(
            "catalog {}: {verb} {}",
            report.source_id,
            report.selected.join(", ")
        );
    }
}

/// Print a human-readable instruction pack mutation report.
pub fn print_instruction_pack_report(report: &InstructionPackReport) {
    let action = if report.dry_run && report.action != "unchanged" {
        format!("would {}", report.action.trim_end_matches('d'))
    } else {
        report.action.clone()
    };
    println!(
        "{} pack {} -> {}",
        action,
        report.pack_id,
        report.target.display()
    );
}

/// Print a human-readable catalog drift report.
pub fn print_catalog_drift_report(report: &CatalogDrift) {
    if report.outcomes.is_empty() {
        println!(
            "catalog {}: up to date (pinned {})",
            report.source_id,
            short_commit(&report.pinned_commit)
        );
        return;
    }
    println!(
        "catalog {}: {} drift outcome(s) (pinned {} -> upstream {})",
        report.source_id,
        report.outcomes.len(),
        short_commit(&report.pinned_commit),
        short_commit(&report.upstream_commit)
    );
    for outcome in &report.outcomes {
        println!("  [{}] {}", outcome.code.as_str(), outcome.message);
    }
}

fn short_commit(commit: &str) -> &str {
    commit.get(..12).unwrap_or(commit)
}

/// Print a human-readable adopt report.
pub fn print_adopt_report(report: &AdoptReport) {
    println!(
        "{} {} -> {}",
        report.copy.as_str(),
        report.source_path.display(),
        report.local_path.display()
    );
    println!("replacement: {}", report.replacement.as_str());
    if let Some(next_step) = report.next_step.as_deref() {
        println!("note: {next_step}");
    }
}

/// Print a human-readable resolve list report.
pub fn print_resolve_list_report(report: &ResolveListReport) {
    if report.unmanaged_skills.is_empty()
        && report.owned_skills.is_empty()
        && report.target_warnings.is_empty()
    {
        println!("no blockers, unmanaged skills, or owned symlinks found");
        return;
    }

    if !report.unmanaged_skills.is_empty() {
        println!("unmanaged skills:");
        for skill in &report.unmanaged_skills {
            let marker = if skill.protected { " protected" } else { "" };
            println!("  {} -> {}{}", skill.id, skill.path.display(), marker);
        }
    }

    if !report.owned_skills.is_empty() {
        println!("owned symlinks:");
        for skill in &report.owned_skills {
            println!(
                "  {} -> {} ({})",
                skill.id,
                skill.link_path.display(),
                skill.store_path.display()
            );
        }
    }

    if !report.target_warnings.is_empty() {
        println!("target warnings:");
        for warning in &report.target_warnings {
            println!(
                "  {} {}: {}",
                warning.code.as_str(),
                warning.path.display(),
                warning.message
            );
        }
    }
}

/// Print a human-readable keep report.
pub fn print_keep_report(report: &KeepReport) {
    let status = if report.existing {
        "existing"
    } else if report.dry_run {
        "planned"
    } else {
        "protected"
    };
    println!("{status} {}", report.skill.path.display());
    if let Some(warning) = report.warning.as_deref() {
        println!("warning: {warning}");
    }
}

/// Print a human-readable remove-owned report.
pub fn print_remove_owned_report(report: &RemoveOwnedReport) {
    println!("{} {}", report.status.as_str(), report.link_path.display());
}

/// Print a human-readable doctor report.
pub fn print_doctor_report(report: &DoctorReport) {
    println!("dalo store: {}", report.store.display());
    println!(
        "summary: errors={} warnings={} info={} ok={}",
        report.summary.errors, report.summary.warnings, report.summary.info, report.summary.ok
    );
    for finding in &report.findings {
        let next = finding
            .next_command
            .as_ref()
            .map_or(String::new(), |command| format!(" next={command}"));
        let severity = doctor_severity_label(finding.severity);
        let severity_padding = " ".repeat(7usize.saturating_sub(severity.len()));
        println!(
            "{}{} {}: {}{}",
            term::doctor_severity(severity),
            severity_padding,
            finding.code,
            finding.message,
            next
        );
    }
}

fn doctor_severity_label(severity: DoctorSeverity) -> &'static str {
    match severity {
        DoctorSeverity::Error => "error",
        DoctorSeverity::Warning => "warning",
        DoctorSeverity::Info => "info",
        DoctorSeverity::Ok => "ok",
    }
}

fn instruction_block_drift_kind_label(
    kind: instructions::InstructionBlockDriftKind,
) -> &'static str {
    match kind {
        instructions::InstructionBlockDriftKind::Missing => "missing",
        instructions::InstructionBlockDriftKind::Malformed => "malformed",
        instructions::InstructionBlockDriftKind::Stale => "stale",
        instructions::InstructionBlockDriftKind::SourceMissing => "source_missing",
    }
}

/// Print a human-readable target detection report.
pub fn print_target_detect_report(report: &TargetDetectReport) {
    for target in &report.targets {
        let path = target
            .path
            .as_ref()
            .map_or_else(|| "-".to_owned(), |path| path.display().to_string());
        println!(
            "{:<9} {:<12} exists={:<5} linked={:<5} {}",
            target.id,
            target.support.as_str(),
            target.exists,
            target.linked,
            path
        );
    }
}

/// Print a human-readable target link report.
pub fn print_target_link_report(report: &TargetLinkReport) {
    println!(
        "{} target {} -> {}",
        report.status.as_str(),
        report.target_id,
        report.path.display()
    );
    println!("canonical: {}", report.canonical_path.display());
}

/// Print a human-readable target unlink report.
pub fn print_target_unlink_report(report: &TargetUnlinkReport) {
    println!("{} target {}", report.status.as_str(), report.target_id);
    if report.status == crate::target::TargetUnlinkStatus::Unlinked {
        println!("note: owned symlinks remain; run `dalo sync` to remove them");
    }
}

#[cfg(test)]
mod tests {
    use std::fs;

    use super::*;

    #[test]
    fn build_status_report_should_resolve_local_skill() {
        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        let store_root = temp_dir.path().join("store");
        store::init_store(store_root.clone(), false).expect("init should succeed");
        let skill_dir = store_root.join("local/skills/review");
        fs::create_dir_all(&skill_dir).expect("skill dir should be created");
        fs::write(skill_dir.join("SKILL.md"), "# Review\n").expect("skill should be written");

        let report = build_status_report(&store_root).expect("status should build");

        assert_eq!(
            report.resolution.active_skills[0].source_ref,
            "local:review"
        );
    }

    #[test]
    fn build_status_report_should_report_missing_instruction_block() {
        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        let (store_root, target) = setup_enabled_instruction_pack(temp_dir.path(), "Body v1\n");
        fs::write(&target, "user-owned content\n").expect("target should be rewritten");

        let report = build_status_report(&store_root).expect("status should build");

        assert_eq!(report.instruction_block_drifts.len(), 1);
        assert_eq!(
            report.instruction_block_drifts[0].kind,
            instructions::InstructionBlockDriftKind::Missing
        );
    }

    #[test]
    fn build_status_report_should_report_stale_instruction_block() {
        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        let (store_root, _target) = setup_enabled_instruction_pack(temp_dir.path(), "Body v1\n");
        fs::write(
            store_root.join("local/instructions/house-style.md"),
            "Body v2\n",
        )
        .expect("pack should be updated");

        let report = build_status_report(&store_root).expect("status should build");

        assert_eq!(report.instruction_block_drifts.len(), 1);
        assert_eq!(
            report.instruction_block_drifts[0].kind,
            instructions::InstructionBlockDriftKind::Stale
        );
    }

    fn setup_enabled_instruction_pack(root: &Path, body: &str) -> (PathBuf, PathBuf) {
        let store_root = root.join("store");
        let target = root.join("AGENTS.md");
        store::init_store(store_root.clone(), false).expect("init should succeed");
        let paths = StorePaths::new(store_root.clone());
        fs::write(paths.local_instructions_dir.join("house-style.md"), body)
            .expect("pack should be written");
        fs::write(&target, "user-owned content\n").expect("target should be seeded");
        instructions::enable_pack(&paths, "house-style", &target, false)
            .expect("pack should be enabled");
        (store_root, target)
    }
}