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
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
//! Diagnostics for store, target, Git, and lockfile health.

use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::thread;
use std::time::{Duration, Instant};

use serde::Serialize;

use crate::adopt;
use crate::config::UserConfig;
use crate::error::shell_quote_path;
use crate::git;
use crate::instructions;
use crate::resolver;
use crate::source::SourceKind;
use crate::store::{self, ApprovalsFile, OwnedSkillState, StateFile, StorePaths};

const COMMAND_CHECK_TIMEOUT: Duration = Duration::from_secs(5);
const COMMAND_CHECK_POLL_INTERVAL: Duration = Duration::from_millis(50);

/// Doctor report.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DoctorReport {
    /// Store root.
    pub store: PathBuf,
    /// Diagnostic findings.
    pub findings: Vec<DoctorFinding>,
    /// Summary counts by severity.
    pub summary: DoctorSummary,
}

/// Count of findings by severity.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
pub struct DoctorSummary {
    /// Error count.
    pub errors: usize,
    /// Warning count.
    pub warnings: usize,
    /// Info count.
    pub info: usize,
    /// OK count.
    pub ok: usize,
}

/// One diagnostic finding.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DoctorFinding {
    /// Severity.
    pub severity: DoctorSeverity,
    /// Machine-readable code.
    pub code: DoctorCode,
    /// Human-readable message.
    pub message: String,
    /// Suggested next command.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_command: Option<String>,
}

/// Diagnostic severity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DoctorSeverity {
    /// Blocks normal operation.
    Error,
    /// May block a subset of workflows or deserves attention.
    Warning,
    /// Useful context.
    Info,
    /// Check passed.
    Ok,
}

/// Diagnostic code.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DoctorCode {
    /// Store root exists.
    StoreExists,
    /// Store root is missing.
    StoreMissing,
    /// Expected store layout exists.
    StoreLayoutOk,
    /// Expected store path is missing.
    StoreLayoutMissing,
    /// Config parses.
    ConfigOk,
    /// Config cannot be parsed.
    ConfigInvalid,
    /// State parses.
    StateOk,
    /// State cannot be parsed.
    StateInvalid,
    /// Lock parses.
    LockOk,
    /// Lock cannot be parsed.
    LockInvalid,
    /// Approvals file parses.
    ApprovalsOk,
    /// Approvals file cannot be parsed.
    ApprovalsInvalid,
    /// Git executable is available.
    GitAvailable,
    /// Git executable is missing.
    GitMissing,
    /// GitHub CLI is available.
    GhAvailable,
    /// GitHub CLI is missing.
    GhMissing,
    /// GitHub CLI is authenticated.
    GhAuthenticated,
    /// GitHub CLI is not authenticated.
    GhUnauthenticated,
    /// Local source has a Git repository.
    LocalGitOk,
    /// Local source Git repository is missing.
    LocalGitMissing,
    /// Configured target exists.
    TargetExists,
    /// Configured target is missing.
    TargetMissing,
    /// Multiple logical targets share a directory.
    DuplicateTargetDirectory,
    /// Owned symlink is valid.
    OwnedSymlinkOk,
    /// Owned symlink is missing.
    MissingOwnedSymlink,
    /// Owned symlink points to a missing store path.
    BrokenOwnedSymlink,
    /// Recorded owned slot is a real entry.
    OwnedPathRealEntry,
    /// Recorded owned symlink points outside the store.
    ForeignOwnedSymlink,
    /// Unmanaged target skill blocks the same managed slot.
    UnmanagedSameNameBlocker,
    /// A linked target directory could not be scanned for unmanaged skills.
    UnreadableTargetDirectory,
    /// Source is clean.
    SourceClean,
    /// Source has local changes.
    DirtySource,
    /// Store contains checkout or staging content not owned by config.
    SourceStoreDebris,
    /// A skill is pending approval.
    PendingApproval,
    /// A skill is blocked because its required closure is not linkable.
    RequiredClosureBlocked,
    /// Two active instruction packs declare overlapping topics.
    InstructionPackTopicOverlap,
    /// An active instruction pack's rendered block is missing, malformed, or stale.
    InstructionBlockDrift,
    /// Target path looks cloud-synced.
    CloudSyncedTarget,
}

/// Run read-only diagnostics.
pub fn run_doctor(store_root: &Path) -> DoctorReport {
    let paths = StorePaths::new(store_root.to_path_buf());
    let mut findings = Vec::new();

    check_commands(&mut findings);
    check_store_layout(&paths, &mut findings);

    let config = read_config(&paths, &mut findings);
    let state = read_state(&paths, &mut findings);
    let lock_ok = read_lock(&paths, &mut findings);
    let approvals = read_approvals(&paths, &mut findings);

    if paths.local_dir.join(".git").is_dir() {
        findings.push(ok(
            DoctorCode::LocalGitOk,
            "local source Git repository exists",
        ));
    } else if paths.root.exists() {
        findings.push(finding_error(
            DoctorCode::LocalGitMissing,
            "local source Git repository is missing",
            Some("dalo init".to_owned()),
        ));
    }

    if let Some(state) = state.as_ref() {
        check_targets(state, &mut findings);
        check_owned_symlinks(&paths, state, &mut findings);
    }

    if let Some(config) = config.as_ref() {
        check_sources(config, &mut findings);
        check_source_store_debris(&paths, config, &mut findings);
    }

    if let (Some(config), Some(_), true) = (config.as_ref(), state.as_ref(), lock_ok) {
        check_resolution(&paths, config, approvals.as_ref(), &mut findings);
    }

    findings.sort_by(|left, right| {
        severity_name(left.severity)
            .cmp(severity_name(right.severity))
            .then_with(|| code_name(left.code).cmp(code_name(right.code)))
            .then_with(|| left.message.cmp(&right.message))
    });
    let summary = summarize(&findings);

    DoctorReport {
        store: store_root.to_path_buf(),
        findings,
        summary,
    }
}

fn check_commands(findings: &mut Vec<DoctorFinding>) {
    if command_succeeds("git", &["--version"]) {
        findings.push(ok(DoctorCode::GitAvailable, "git is available"));
    } else {
        findings.push(finding_error(
            DoctorCode::GitMissing,
            "git is not available on PATH",
            None,
        ));
    }

    if command_succeeds("gh", &["--version"]) {
        findings.push(ok(DoctorCode::GhAvailable, "gh is available"));
        if command_succeeds("gh", &["auth", "status"]) {
            findings.push(ok(DoctorCode::GhAuthenticated, "gh is authenticated"));
        } else {
            findings.push(finding_warning(
                DoctorCode::GhUnauthenticated,
                "gh is not authenticated; PR flows will not work",
                Some("gh auth login".to_owned()),
            ));
        }
    } else {
        findings.push(finding_warning(
            DoctorCode::GhMissing,
            "gh is not available; normal sync works, but PR flows will not",
            None,
        ));
    }
}

fn check_store_layout(paths: &StorePaths, findings: &mut Vec<DoctorFinding>) {
    if paths.root.is_dir() {
        findings.push(ok(DoctorCode::StoreExists, "store root exists"));
    } else {
        findings.push(finding_error(
            DoctorCode::StoreMissing,
            format!("store root `{}` does not exist", paths.root.display()),
            Some("dalo init".to_owned()),
        ));
        return;
    }

    for path in [
        &paths.config_file,
        &paths.lock_file,
        &paths.state_file,
        &paths.approvals_file,
        &paths.local_dir,
        &paths.local_skills_dir,
        &paths.sources_dir,
    ] {
        if path.exists() {
            findings.push(ok(
                DoctorCode::StoreLayoutOk,
                format!("expected store path exists: `{}`", path.display()),
            ));
        } else {
            findings.push(finding_error(
                DoctorCode::StoreLayoutMissing,
                format!("expected store path is missing: `{}`", path.display()),
                Some("dalo init".to_owned()),
            ));
        }
    }
}

fn read_config(paths: &StorePaths, findings: &mut Vec<DoctorFinding>) -> Option<UserConfig> {
    match store::read_config(paths) {
        Ok(config) => {
            findings.push(ok(DoctorCode::ConfigOk, "config parses"));
            Some(config)
        }
        Err(error) => {
            findings.push(finding_error(
                DoctorCode::ConfigInvalid,
                format!("config could not be read: {error}"),
                Some(format!("$EDITOR {}", shell_quote_path(&paths.config_file))),
            ));
            None
        }
    }
}

fn read_state(paths: &StorePaths, findings: &mut Vec<DoctorFinding>) -> Option<StateFile> {
    match store::read_state(paths) {
        Ok(state) => {
            findings.push(ok(DoctorCode::StateOk, "state parses"));
            Some(state)
        }
        Err(error) => {
            findings.push(finding_error(
                DoctorCode::StateInvalid,
                format!("state could not be read: {error}"),
                Some("dalo init".to_owned()),
            ));
            None
        }
    }
}

fn read_lock(paths: &StorePaths, findings: &mut Vec<DoctorFinding>) -> bool {
    match store::read_user_lock(paths) {
        Ok(_) => {
            findings.push(ok(DoctorCode::LockOk, "user lock parses"));
            true
        }
        Err(error) => {
            findings.push(finding_error(
                DoctorCode::LockInvalid,
                format!("user lock could not be read: {error}"),
                Some("dalo sync".to_owned()),
            ));
            false
        }
    }
}

fn read_approvals(paths: &StorePaths, findings: &mut Vec<DoctorFinding>) -> Option<ApprovalsFile> {
    match store::read_approvals(paths) {
        Ok(approvals) => {
            findings.push(ok(DoctorCode::ApprovalsOk, "approvals parse"));
            Some(approvals)
        }
        Err(error) => {
            findings.push(finding_error(
                DoctorCode::ApprovalsInvalid,
                format!("approvals could not be read: {error}"),
                Some("inspect or restore approvals.toml".to_owned()),
            ));
            None
        }
    }
}

fn check_targets(state: &StateFile, findings: &mut Vec<DoctorFinding>) {
    for target in state.targets.iter().filter(|target| target.enabled) {
        if target.path.is_dir() {
            findings.push(ok(
                DoctorCode::TargetExists,
                format!(
                    "target `{}` exists at `{}`",
                    target.id,
                    target.path.display()
                ),
            ));
        } else {
            findings.push(finding_warning(
                DoctorCode::TargetMissing,
                format!(
                    "target `{}` is configured but `{}` is missing",
                    target.id,
                    target.path.display()
                ),
                Some(format!("dalo target link {}", target.id)),
            ));
        }

        if looks_cloud_synced(&target.path) {
            findings.push(finding_warning(
                DoctorCode::CloudSyncedTarget,
                format!(
                    "target `{}` appears to be inside a cloud-synced folder: `{}`",
                    target.id,
                    target.path.display()
                ),
                None,
            ));
        }
    }

    for dir in &state.materialization_dirs {
        if dir.logical_targets.len() > 1 {
            findings.push(info(
                DoctorCode::DuplicateTargetDirectory,
                format!(
                    "targets share `{}`: {}",
                    dir.path.display(),
                    dir.logical_targets.join(", ")
                ),
            ));
        }
    }
}

fn check_owned_symlinks(paths: &StorePaths, state: &StateFile, findings: &mut Vec<DoctorFinding>) {
    for owned in &state.owned_skills {
        match fs::symlink_metadata(&owned.link_path) {
            Ok(metadata) if metadata.file_type().is_symlink() => {
                match fs::read_link(&owned.link_path) {
                    Ok(target)
                        if !store::path_is_same_or_descendant(
                            &store::resolve_link_target(&owned.link_path, &target),
                            &paths.root,
                        ) =>
                    {
                        findings.push(finding_error(
                            DoctorCode::ForeignOwnedSymlink,
                            format!(
                                "owned symlink `{}` points outside the store to `{}`",
                                owned.link_path.display(),
                                target.display()
                            ),
                            Some(format!(
                                "dalo resolve remove-owned {}",
                                owned_selector(owned)
                            )),
                        ));
                    }
                    Ok(target)
                        if !store::resolve_link_target(&owned.link_path, &target).exists() =>
                    {
                        findings.push(finding_error(
                            DoctorCode::BrokenOwnedSymlink,
                            format!(
                                "owned symlink `{}` points to missing `{}`",
                                owned.link_path.display(),
                                target.display()
                            ),
                            Some(format!(
                                "dalo resolve remove-owned {}",
                                owned_selector(owned)
                            )),
                        ));
                    }
                    Ok(_) => findings.push(ok(
                        DoctorCode::OwnedSymlinkOk,
                        format!("owned symlink `{}` is valid", owned.link_path.display()),
                    )),
                    Err(error) => findings.push(finding_error(
                        DoctorCode::BrokenOwnedSymlink,
                        format!(
                            "owned symlink `{}` could not be read: {error}",
                            owned.link_path.display()
                        ),
                        Some(format!(
                            "dalo resolve remove-owned {}",
                            owned_selector(owned)
                        )),
                    )),
                }
            }
            Ok(_) => findings.push(finding_error(
                DoctorCode::OwnedPathRealEntry,
                format!(
                    "recorded owned path `{}` is a real entry, not a symlink",
                    owned.link_path.display()
                ),
                Some(format!(
                    "dalo resolve remove-owned {}",
                    owned_selector(owned)
                )),
            )),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                findings.push(finding_warning(
                    DoctorCode::MissingOwnedSymlink,
                    format!(
                        "recorded owned symlink `{}` is missing",
                        owned.link_path.display()
                    ),
                    Some(format!(
                        "dalo resolve remove-owned {}",
                        owned_selector(owned)
                    )),
                ));
            }
            Err(error) => findings.push(finding_error(
                DoctorCode::BrokenOwnedSymlink,
                format!(
                    "recorded owned symlink `{}` could not be inspected: {error}",
                    owned.link_path.display()
                ),
                Some(format!(
                    "dalo resolve remove-owned {}",
                    owned_selector(owned)
                )),
            )),
        }
    }
}

fn owned_selector(owned: &OwnedSkillState) -> String {
    format!("{}:{}", owned.target_id, owned.slot_name)
}

fn check_sources(config: &UserConfig, findings: &mut Vec<DoctorFinding>) {
    for source in config.sources.iter().filter(|source| source.enabled) {
        match git::is_dirty(&source.path) {
            Ok(true) => {
                let severity = if source.kind == SourceKind::Team {
                    DoctorSeverity::Error
                } else {
                    DoctorSeverity::Warning
                };
                findings.push(DoctorFinding {
                    severity,
                    code: DoctorCode::DirtySource,
                    message: if source.kind == SourceKind::Local {
                        format!(
                            "source `{}` at `{}` has local changes; adopted skills must be committed before syncing",
                            source.id,
                            source.path.display()
                        )
                    } else {
                        format!(
                            "source `{}` at `{}` has local changes; resolve or commit them before syncing",
                            source.id,
                            source.path.display()
                        )
                    },
                    next_command: Some(format!(
                        "git -C {} status",
                        shell_quote_path(&source.path)
                    )),
                });
            }
            Ok(false) => findings.push(ok(
                DoctorCode::SourceClean,
                format!("source `{}` is clean", source.id),
            )),
            Err(error) => findings.push(finding_warning(
                DoctorCode::DirtySource,
                format!(
                    "source `{}` dirty state could not be checked: {error}",
                    source.id
                ),
                None,
            )),
        }
    }
}

fn check_source_store_debris(
    paths: &StorePaths,
    config: &UserConfig,
    findings: &mut Vec<DoctorFinding>,
) {
    let configured = config
        .sources
        .iter()
        .filter(|source| source.kind != SourceKind::Local)
        .map(|source| source.id.as_str())
        .collect::<BTreeSet<_>>();
    let Ok(source_dirs) = fs::read_dir(&paths.sources_dir) else {
        return;
    };

    for entry in source_dirs.flatten() {
        let source_id = entry.file_name().to_string_lossy().into_owned();
        let path = entry.path();
        if !configured.contains(source_id.as_str()) {
            findings.push(finding_warning(
                DoctorCode::SourceStoreDebris,
                format!("unconfigured source content exists at `{}`", path.display()),
                Some(format!("inspect or remove {}", path.display())),
            ));
            continue;
        }

        let Ok(children) = fs::read_dir(&path) else {
            continue;
        };
        for child in children.flatten() {
            let name = child.file_name();
            let name = name.to_string_lossy();
            if name.starts_with(".checkout-tmp-") || name == "checkout.dalo-removing" {
                findings.push(finding_warning(
                    DoctorCode::SourceStoreDebris,
                    format!(
                        "interrupted source-operation debris exists at `{}`",
                        child.path().display()
                    ),
                    Some(format!("inspect or remove {}", child.path().display())),
                ));
            }
        }
    }
}

fn check_resolution(
    paths: &StorePaths,
    config: &UserConfig,
    approvals: Option<&ApprovalsFile>,
    findings: &mut Vec<DoctorFinding>,
) {
    let approval_records = approvals
        .map(|approvals| approvals.approvals.clone())
        .unwrap_or_default();
    let resolution = resolver::resolve_from_config(config, approval_records).resolution;

    if approvals.is_some() {
        for diagnostic in &resolution.diagnostics {
            if diagnostic.code == resolver::ResolutionDiagnosticCode::LegacyBareApproval {
                findings.push(finding_warning(
                    DoctorCode::PendingApproval,
                    diagnostic.message.clone(),
                    Some("dalo status".to_owned()),
                ));
            }
        }
        for skill in &resolution.pending_approval_skills {
            findings.push(finding_warning(
                DoctorCode::PendingApproval,
                format!("skill `{}` is pending approval", skill.source_ref),
                Some(format!("dalo approve skill {}", skill.source_ref)),
            ));
        }
    }

    for blocked in &resolution.blocked_skills {
        findings.push(finding_warning(
            DoctorCode::RequiredClosureBlocked,
            format!(
                "skill `{}` is blocked: requirement `{}` is {}",
                blocked.skill.source_ref,
                blocked.requirement,
                resolver::closure_block_reason_name(blocked.reason)
            ),
            Some("dalo status".to_owned()),
        ));
    }

    let lock = store::read_user_lock(paths).unwrap_or_default();
    let discovered =
        instructions::discover_packs(paths, &config.sources, &lock.active_instruction_packs);
    let active_packs = discovered
        .into_iter()
        .filter(|pack| pack.enabled)
        .collect::<Vec<_>>();
    for overlap in instructions::topic_overlaps(&active_packs) {
        findings.push(finding_warning(
            DoctorCode::InstructionPackTopicOverlap,
            format!(
                "instruction packs `{}` and `{}` overlap on topics: {}",
                overlap.packs[0],
                overlap.packs[1],
                overlap.topics.join(", ")
            ),
            Some("dalo status".to_owned()),
        ));
    }
    for drift in instructions::instruction_block_drifts(
        paths,
        &config.sources,
        &lock.active_instruction_packs,
    ) {
        findings.push(finding_warning(
            DoctorCode::InstructionBlockDrift,
            format!(
                "instruction pack `{}:{}` is {} at `{}`: {}",
                drift.source_id,
                drift.pack_id,
                instruction_block_drift_kind_name(drift.kind),
                drift.target.display(),
                drift.message
            ),
            Some(format!(
                "dalo instructions enable {} {}",
                drift.pack_id,
                drift.target.display()
            )),
        ));
    }

    let active_slots = resolution
        .active_skills
        .iter()
        .map(|skill| (skill.slot_name.as_str(), skill.source_ref.as_str()))
        .collect::<BTreeMap<_, _>>();
    if let Ok(unmanaged_scan) = adopt::discover_unmanaged_skill_scan(paths) {
        for warning in unmanaged_scan.warnings {
            findings.push(finding_warning(
                DoctorCode::UnreadableTargetDirectory,
                format!(
                    "target path `{}` could not be scanned: {}",
                    warning.path.display(),
                    warning.message
                ),
                None,
            ));
        }
        for unmanaged in unmanaged_scan.unmanaged_skills {
            if let Some(source_ref) = active_slots.get(unmanaged.slot_name.as_str()) {
                findings.push(finding_error(
                    DoctorCode::UnmanagedSameNameBlocker,
                    format!(
                        "unmanaged skill `{}` blocks managed `{}`",
                        unmanaged.path.display(),
                        source_ref
                    ),
                    Some(format!("dalo adopt {}", unmanaged.id)),
                ));
            }
        }
    }
}

fn command_succeeds(program: &str, args: &[&str]) -> bool {
    command_succeeds_with_timeout(program, args, COMMAND_CHECK_TIMEOUT)
}

fn command_succeeds_with_timeout(program: &str, args: &[&str], timeout: Duration) -> bool {
    let Ok(mut child) = Command::new(program)
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
    else {
        return false;
    };
    let start = Instant::now();

    loop {
        match child.try_wait() {
            Ok(Some(status)) => return status.success(),
            Ok(None) => {}
            Err(_) => return false,
        }

        let elapsed = start.elapsed();
        if elapsed >= timeout {
            let _ = child.kill();
            let _ = child.wait();
            return false;
        }

        thread::sleep(COMMAND_CHECK_POLL_INTERVAL.min(timeout - elapsed));
    }
}

fn looks_cloud_synced(path: &Path) -> bool {
    let value = path.to_string_lossy();
    ["Dropbox", "Google Drive", "iCloud Drive", "OneDrive"]
        .iter()
        .any(|marker| value.contains(marker))
}

fn summarize(findings: &[DoctorFinding]) -> DoctorSummary {
    let mut summary = DoctorSummary::default();
    for finding in findings {
        match finding.severity {
            DoctorSeverity::Error => summary.errors += 1,
            DoctorSeverity::Warning => summary.warnings += 1,
            DoctorSeverity::Info => summary.info += 1,
            DoctorSeverity::Ok => summary.ok += 1,
        }
    }
    summary
}

fn ok(code: DoctorCode, message: impl Into<String>) -> DoctorFinding {
    DoctorFinding {
        severity: DoctorSeverity::Ok,
        code,
        message: message.into(),
        next_command: None,
    }
}

fn info(code: DoctorCode, message: impl Into<String>) -> DoctorFinding {
    DoctorFinding {
        severity: DoctorSeverity::Info,
        code,
        message: message.into(),
        next_command: None,
    }
}

fn finding_warning(
    code: DoctorCode,
    message: impl Into<String>,
    next_command: Option<String>,
) -> DoctorFinding {
    DoctorFinding {
        severity: DoctorSeverity::Warning,
        code,
        message: message.into(),
        next_command,
    }
}

fn finding_error(
    code: DoctorCode,
    message: impl Into<String>,
    next_command: Option<String>,
) -> DoctorFinding {
    DoctorFinding {
        severity: DoctorSeverity::Error,
        code,
        message: message.into(),
        next_command,
    }
}

fn severity_name(severity: DoctorSeverity) -> &'static str {
    match severity {
        DoctorSeverity::Error => "0_error",
        DoctorSeverity::Warning => "1_warning",
        DoctorSeverity::Info => "2_info",
        DoctorSeverity::Ok => "3_ok",
    }
}

fn code_name(code: DoctorCode) -> &'static str {
    match code {
        DoctorCode::StoreExists => "store_exists",
        DoctorCode::StoreMissing => "store_missing",
        DoctorCode::StoreLayoutOk => "store_layout_ok",
        DoctorCode::StoreLayoutMissing => "store_layout_missing",
        DoctorCode::ConfigOk => "config_ok",
        DoctorCode::ConfigInvalid => "config_invalid",
        DoctorCode::StateOk => "state_ok",
        DoctorCode::StateInvalid => "state_invalid",
        DoctorCode::LockOk => "lock_ok",
        DoctorCode::LockInvalid => "lock_invalid",
        DoctorCode::ApprovalsOk => "approvals_ok",
        DoctorCode::ApprovalsInvalid => "approvals_invalid",
        DoctorCode::GitAvailable => "git_available",
        DoctorCode::GitMissing => "git_missing",
        DoctorCode::GhAvailable => "gh_available",
        DoctorCode::GhMissing => "gh_missing",
        DoctorCode::GhAuthenticated => "gh_authenticated",
        DoctorCode::GhUnauthenticated => "gh_unauthenticated",
        DoctorCode::LocalGitOk => "local_git_ok",
        DoctorCode::LocalGitMissing => "local_git_missing",
        DoctorCode::TargetExists => "target_exists",
        DoctorCode::TargetMissing => "target_missing",
        DoctorCode::DuplicateTargetDirectory => "duplicate_target_directory",
        DoctorCode::OwnedSymlinkOk => "owned_symlink_ok",
        DoctorCode::MissingOwnedSymlink => "missing_owned_symlink",
        DoctorCode::BrokenOwnedSymlink => "broken_owned_symlink",
        DoctorCode::OwnedPathRealEntry => "owned_path_real_entry",
        DoctorCode::ForeignOwnedSymlink => "foreign_owned_symlink",
        DoctorCode::UnmanagedSameNameBlocker => "unmanaged_same_name_blocker",
        DoctorCode::UnreadableTargetDirectory => "unreadable_target_directory",
        DoctorCode::SourceClean => "source_clean",
        DoctorCode::DirtySource => "dirty_source",
        DoctorCode::SourceStoreDebris => "source_store_debris",
        DoctorCode::PendingApproval => "pending_approval",
        DoctorCode::RequiredClosureBlocked => "required_closure_blocked",
        DoctorCode::InstructionPackTopicOverlap => "instruction_pack_topic_overlap",
        DoctorCode::InstructionBlockDrift => "instruction_block_drift",
        DoctorCode::CloudSyncedTarget => "cloud_synced_target",
    }
}

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

impl std::fmt::Display for DoctorCode {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(code_name(*self))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::store::{MaterializationDirState, OwnedSkillState, TargetState};
    use std::os::unix::fs::PermissionsExt;

    #[test]
    fn run_doctor_should_report_missing_store_without_creating_it() {
        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        let store = temp_dir.path().join("missing-store");

        let report = run_doctor(&store);

        assert!(
            report
                .findings
                .iter()
                .any(|finding| finding.code == DoctorCode::StoreMissing)
        );
        assert!(!store.exists());
    }

    #[test]
    fn run_doctor_should_point_invalid_config_to_the_editor() {
        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        let store = temp_dir.path().join("store with $(shell)");
        store::init_store(store.clone(), false).expect("init should succeed");
        let config_file = store.join("config.toml");
        fs::write(&config_file, "version = ").expect("config should be corrupted");

        let report = run_doctor(&store);
        let finding = report
            .findings
            .iter()
            .find(|finding| finding.code == DoctorCode::ConfigInvalid)
            .expect("invalid config should be reported");

        assert!(finding.message.contains("line 1"));
        assert_eq!(
            finding.next_command.as_deref(),
            Some(format!("$EDITOR '{}'", config_file.display()).as_str())
        );
    }

    #[test]
    fn run_doctor_should_report_broken_owned_symlink() {
        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        let store = temp_dir.path().join("store");
        let target = temp_dir.path().join("target");
        store::init_store(store.clone(), false).expect("init should succeed");
        fs::create_dir_all(&target).expect("target should be created");
        let link = target.join("review");
        std::os::unix::fs::symlink(store.join("local/skills/missing"), &link)
            .expect("broken symlink should be created");
        write_state(&store, &target, &link, &store.join("local/skills/missing"));

        let report = run_doctor(&store);

        assert!(
            report
                .findings
                .iter()
                .any(|finding| finding.code == DoctorCode::BrokenOwnedSymlink)
        );
    }

    #[test]
    fn run_doctor_should_accept_owned_symlink_to_store_equivalent_path() {
        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        let store = temp_dir.path().join("store");
        let store_alias = temp_dir.path().join("store-alias");
        let target = temp_dir.path().join("target");
        store::init_store(store.clone(), false).expect("init should succeed");
        fs::create_dir_all(&target).expect("target should be created");
        let store_skill = store.join("local/skills/review");
        fs::create_dir_all(&store_skill).expect("skill should be created");
        std::os::unix::fs::symlink(&store, &store_alias).expect("store alias should be created");
        let link = target.join("review");
        std::os::unix::fs::symlink(store_alias.join("local/skills/review"), &link)
            .expect("owned symlink should be created");
        write_state(&store, &target, &link, &store_skill);

        let report = run_doctor(&store);

        assert!(
            !report
                .findings
                .iter()
                .any(|finding| finding.code == DoctorCode::ForeignOwnedSymlink)
        );
        assert!(
            report
                .findings
                .iter()
                .any(|finding| finding.code == DoctorCode::OwnedSymlinkOk)
        );
    }

    #[test]
    fn command_succeeds_with_timeout_should_stop_hung_command() {
        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        let command = temp_dir.path().join("hang");
        fs::write(&command, "#!/bin/sh\nwhile :; do :; done\n").expect("script should be written");
        let mut permissions = fs::metadata(&command)
            .expect("script metadata should be readable")
            .permissions();
        permissions.set_mode(0o755);
        fs::set_permissions(&command, permissions).expect("script should be executable");

        assert!(!command_succeeds_with_timeout(
            command.to_str().expect("script path should be utf-8"),
            &[],
            Duration::from_millis(10),
        ));
    }

    #[test]
    fn run_doctor_should_report_missing_instruction_block() {
        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        let (store, 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 = run_doctor(&store);

        assert!(report.findings.iter().any(|finding| {
            finding.code == DoctorCode::InstructionBlockDrift
                && finding.message.contains("missing")
                && finding
                    .next_command
                    .as_deref()
                    .is_some_and(|command| command.contains("dalo instructions enable house-style"))
        }));
    }

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

        let report = run_doctor(&store);

        assert!(report.findings.iter().any(|finding| {
            finding.code == DoctorCode::InstructionBlockDrift && finding.message.contains("stale")
        }));
    }

    #[test]
    fn run_doctor_should_report_invalid_approvals_without_pending_warnings() {
        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        let store = temp_dir.path().join("store");
        let team_repo = temp_dir.path().join("team-repo");
        store::init_store(store.clone(), false).expect("init should succeed");
        create_git_skill_repo(&team_repo);
        write_config_with_team_source(&store, &team_repo, false);
        fs::write(
            StorePaths::new(store.clone()).approvals_file,
            "schema_version = ",
        )
        .expect("approvals should be corrupted");

        let report = run_doctor(&store);

        assert!(report.findings.iter().any(|finding| {
            finding.code == DoctorCode::ApprovalsInvalid
                && finding.severity == DoctorSeverity::Error
                && finding.next_command.as_deref() == Some("inspect or restore approvals.toml")
        }));
        assert!(
            !report
                .findings
                .iter()
                .any(|finding| finding.code == DoctorCode::PendingApproval)
        );
    }

    #[test]
    fn check_sources_should_rate_dirty_team_source_as_error() {
        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        let store = temp_dir.path().join("store");
        store::init_store(store.clone(), false).expect("init should succeed");
        let team_repo = temp_dir.path().join("team repo $(shell)");
        create_dirty_git_repo(&team_repo);
        write_config_with_dirty_sources(&store, &team_repo, None);

        let report = run_doctor(&store);

        assert!(report.findings.iter().any(|finding| {
            finding.code == DoctorCode::DirtySource
                && finding.severity == DoctorSeverity::Error
                && finding.message.contains("`team`")
                && finding.next_command.as_deref()
                    == Some(format!("git -C '{}' status", team_repo.display()).as_str())
        }));
    }

    #[test]
    fn check_sources_should_rate_dirty_local_source_as_warning() {
        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        let store = temp_dir.path().join("store");
        store::init_store(store.clone(), false).expect("init should succeed");
        let team_repo = temp_dir.path().join("team-repo");
        let local_repo = temp_dir.path().join("local repo; echo unsafe");
        create_dirty_git_repo(&team_repo);
        create_dirty_git_repo(&local_repo);
        write_config_with_dirty_sources(&store, &team_repo, Some(&local_repo));

        let report = run_doctor(&store);

        assert!(report.findings.iter().any(|finding| {
            finding.code == DoctorCode::DirtySource
                && finding.severity == DoctorSeverity::Warning
                && finding.message.contains("`workspace`")
                && finding.message.contains("adopted skills must be committed")
                && finding.next_command.as_deref()
                    == Some(format!("git -C '{}' status", local_repo.display()).as_str())
        }));
    }

    #[test]
    fn doctor_should_report_unconfigured_source_operation_debris() {
        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        let store = temp_dir.path().join("store");
        store::init_store(store.clone(), false).expect("init should succeed");
        let debris = store.join("sources/orphan/checkout.dalo-removing");
        fs::create_dir_all(&debris).expect("source debris should be created");

        let report = run_doctor(&store);

        assert!(report.findings.iter().any(|finding| {
            finding.code == DoctorCode::SourceStoreDebris
                && finding.severity == DoctorSeverity::Warning
                && finding
                    .message
                    .contains(debris.parent().unwrap().to_string_lossy().as_ref())
        }));
    }

    fn setup_enabled_instruction_pack(root: &Path, body: &str) -> (PathBuf, PathBuf) {
        let store = root.join("store");
        let target = root.join("AGENTS.md");
        store::init_store(store.clone(), false).expect("init should succeed");
        let paths = StorePaths::new(store.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");
        crate::instructions::enable_pack(&paths, "house-style", &target, false)
            .expect("pack should be enabled");
        (store, target)
    }

    fn create_dirty_git_repo(repo: &Path) {
        fs::create_dir_all(repo).expect("repo dir should be created");
        run_git(repo, &["init", "-q"]);
        fs::write(repo.join("README.md"), "tracked\n").expect("tracked file should be written");
        run_git(repo, &["add", "."]);
        run_git(
            repo,
            &[
                "-c",
                "commit.gpgsign=false",
                "-c",
                "user.email=test@example.com",
                "-c",
                "user.name=Test User",
                "commit",
                "-m",
                "initial",
                "-q",
            ],
        );
        fs::write(repo.join("README.md"), "dirty\n").expect("repo should be dirtied");
    }

    fn create_git_skill_repo(repo: &Path) {
        fs::create_dir_all(repo.join("skills/review")).expect("repo skill dir should be created");
        fs::write(repo.join("skills/review/SKILL.md"), "# Review\n")
            .expect("skill should be written");
        run_git(repo, &["init", "-q"]);
        run_git(repo, &["add", "."]);
        run_git(
            repo,
            &[
                "-c",
                "commit.gpgsign=false",
                "-c",
                "user.email=test@example.com",
                "-c",
                "user.name=Test User",
                "commit",
                "-m",
                "initial",
                "-q",
            ],
        );
    }

    fn write_config_with_team_source(store: &Path, team_repo: &Path, trusted: bool) {
        use crate::config::{Settings, UserConfig};
        use crate::source::{SourceConfig, SourceKind};

        let paths = StorePaths::new(store.to_path_buf());
        let config = UserConfig {
            version: crate::config::CONFIG_VERSION,
            settings: Settings {
                autosync: false,
                sync_interval: None,
            },
            sources: vec![SourceConfig {
                id: "team".to_owned(),
                kind: SourceKind::Team,
                path: team_repo.to_path_buf(),
                priority: 10,
                enabled: true,
                trusted,
                url: None,
                branch: None,
                update_policy: None,
                selection: Vec::new(),
            }],
        };
        store::write_config(&paths, &config).expect("config should be written");
    }

    fn write_config_with_dirty_sources(store: &Path, team_repo: &Path, local_repo: Option<&Path>) {
        use crate::config::{Settings, UserConfig};
        use crate::source::{SourceConfig, SourceKind};

        let paths = StorePaths::new(store.to_path_buf());
        let mut sources = vec![SourceConfig {
            id: "team".to_owned(),
            kind: SourceKind::Team,
            path: team_repo.to_path_buf(),
            priority: 10,
            enabled: true,
            trusted: true,
            url: None,
            branch: None,
            update_policy: None,
            selection: Vec::new(),
        }];
        if let Some(local_repo) = local_repo {
            sources.push(SourceConfig {
                id: "workspace".to_owned(),
                kind: SourceKind::Local,
                path: local_repo.to_path_buf(),
                priority: 0,
                enabled: true,
                trusted: true,
                url: None,
                branch: None,
                update_policy: None,
                selection: Vec::new(),
            });
        }
        let config = UserConfig {
            version: crate::config::CONFIG_VERSION,
            settings: Settings {
                autosync: false,
                sync_interval: None,
            },
            sources,
        };
        store::write_config(&paths, &config).expect("config should be written");
    }

    fn run_git(repo: &Path, args: &[&str]) {
        let status = Command::new("git")
            .args(args)
            .current_dir(repo)
            .status()
            .expect("git should run");
        assert!(status.success());
    }

    fn write_state(store: &Path, target: &Path, link: &Path, store_path: &Path) {
        let paths = StorePaths::new(store.to_path_buf());
        let mut state = store::read_state(&paths).expect("state should be readable");
        state.targets = vec![TargetState {
            id: "generic".to_owned(),
            path: target.to_path_buf(),
            canonical_path: target.to_path_buf(),
            enabled: true,
        }];
        state.materialization_dirs = vec![MaterializationDirState {
            path: target.to_path_buf(),
            logical_targets: vec!["generic".to_owned()],
        }];
        state.owned_skills = vec![OwnedSkillState {
            target_id: "generic".to_owned(),
            slot_name: "review".to_owned(),
            link_path: link.to_path_buf(),
            store_path: store_path.to_path_buf(),
        }];
        store::write_state(&paths, &state).expect("state should be written");
    }
}