ccd-cli 1.0.0-beta.1

Bootstrap and validate Continuous Context Development repositories
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
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
use std::fs;
use std::path::Path;
use std::process::ExitCode;

use anyhow::Result;
use serde::Serialize;

use super::{check, host, sync};
use crate::handoff::{self, BranchMode};
use crate::memory::{entries as memory_entries, provider as memory_provider};
use crate::output::CommandReport;
use crate::paths::state::StateLayout;
use crate::paths::substrate::SubstrateKind;
use crate::profile;
use crate::repo::marker as repo_marker;
use crate::repo::registry as repo_registry;
use crate::repo::truth as project_truth;
use crate::state::config_migration;
use crate::state::consistency;
use crate::state::pod_identity;
use crate::state::runtime as runtime_state;
use crate::state::session as session_state;
use crate::state::validation_profile::{
    self, HandoffDoctorValidationProfile, ValidationProfile, ValidationSeverity,
};

const AGENTS_PLACEHOLDERS: &[&str] = &[
    "[One paragraph: what this project is, what it does, and who it is for.]",
    "[List the invariants where a violation cascades.]",
];

const MEMORY_PLACEHOLDERS: &[&str] = &[
    "[project name]",
    "[Facts that stay true across sessions.]",
    "[Start empty. Add an item when a pattern repeats or a rule changes.]",
    "[Optional: commands that repeatedly save time or prevent known failures.]",
];

/// Phrases (lowercase) that indicate a session log rather than a factual state snapshot.
const SESSION_LOG_PHRASES: &[&str] = &[
    "i then",
    "i tried",
    "i decided",
    "i ran",
    "i fixed",
    "i added",
    "next i ",
    "after that",
    "we then",
    "we decided",
];

const OPTIONAL_PROJECT_TRUTH: &[&str] = &["MEMORY.md", "_MANIFEST.md"];

#[derive(Serialize, Clone)]
pub struct DoctorCheck {
    check: String,
    file: String,
    status: &'static str,
    severity: &'static str,
    message: String,
}

#[derive(Serialize)]
pub struct DoctorReport {
    command: &'static str,
    ok: bool,
    repo_root: String,
    failures: usize,
    warnings: usize,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    host_integrations: Vec<host::HostIntegrationStatus>,
    checks: Vec<DoctorCheck>,
}

impl DoctorReport {
    /// Remove checks below the given status threshold.
    ///
    /// Only the `checks` vec is filtered. `ok`, `failures`, and `warnings`
    /// are left untouched so that `exit_code()` still reflects the
    /// unfiltered health of the repo.
    pub fn filter_by_status(&mut self, min_status: &str) {
        let min_rank = status_rank(min_status);
        self.checks
            .retain(|check| status_rank(check.status) >= min_rank);
    }
}

fn status_rank(status: &str) -> u8 {
    match status {
        "fail" => 2,
        "warn" => 1,
        _ => 0,
    }
}

impl CommandReport for DoctorReport {
    fn exit_code(&self) -> ExitCode {
        if self.failures > 0 {
            ExitCode::from(1)
        } else {
            ExitCode::SUCCESS
        }
    }

    fn render_text(&self) {
        for check in &self.checks {
            let label = match check.status {
                "pass" => "PASS",
                "warn" => "WARN",
                "fail" => "FAIL",
                _ => "INFO",
            };
            println!("[{label}] {}", check.message);
        }

        println!(
            "Doctor summary: {} failure(s), {} warning(s).",
            self.failures, self.warnings
        );
    }
}

#[derive(Clone, Copy)]
pub struct RunOptions {
    pub include_repo_native_checks: bool,
}

impl Default for RunOptions {
    fn default() -> Self {
        Self {
            include_repo_native_checks: true,
        }
    }
}

pub fn run(
    repo_root: &Path,
    explicit_profile: Option<&str>,
    options: RunOptions,
) -> Result<DoctorReport> {
    let mut checks = Vec::new();
    let mut host_integrations = Vec::new();
    let sync_profile = sync::SyncProfile::default();

    let InspectedCoreFile {
        checks: agent_checks,
        contents: agents_contents,
    } = inspect_core_file(
        &repo_root.join("AGENTS.md"),
        "AGENTS.md",
        AGENTS_PLACEHOLDERS,
        Some((sync_profile.soft_line_limit, sync_profile.hard_line_limit)),
    )?;
    checks.extend(agent_checks);

    for file in OPTIONAL_PROJECT_TRUTH {
        let path = repo_root.join(file);
        if !path.exists() {
            continue;
        }

        let (placeholders, budget) = known_file_rules(file, &sync_profile);
        checks.extend(inspect_core_file(&path, file, placeholders, budget)?.checks);
    }

    let layout = match profile::resolve(explicit_profile)
        .and_then(|profile| StateLayout::resolve(repo_root, profile))
    {
        Ok(layout) => Some(layout),
        Err(error) => {
            checks.push(fail_check(
                "clone_state",
                ".git/ccd",
                format!("failed to resolve workspace-state paths: {error:#}"),
            ));
            None
        }
    };

    let marker = match repo_marker::load(repo_root) {
        Ok(Some(marker)) => {
            checks.push(pass_check(
                "repo_marker",
                repo_marker::MARKER_FILE,
                format!(
                    "{} contains project ID `{}`",
                    repo_marker::MARKER_FILE,
                    marker.locality_id
                ),
            ));
            Some(marker)
        }
        Ok(None) => {
            checks.push(fail_check(
                "repo_marker",
                repo_marker::MARKER_FILE,
                format!(
                    "{} is missing; bootstrap this workspace with `ccd attach` or `ccd link`",
                    repo_marker::MARKER_FILE
                ),
            ));
            None
        }
        Err(error) => {
            checks.push(fail_check(
                "repo_marker",
                repo_marker::MARKER_FILE,
                format!("failed to parse {}: {error:#}", repo_marker::MARKER_FILE),
            ));
            None
        }
    };

    if let Some(layout) = &layout {
        checks.extend(validate_profile_kernel(layout)?);
    }

    if let (Some(layout), Some(marker)) = (layout.as_ref(), marker.as_ref()) {
        // Lazy migration: consolidate legacy config files into config.toml.
        let mut migrated_from = Vec::new();
        if let Ok(config_migration::MigrationReport::Migrated { from }) =
            config_migration::migrate_repo_overlay_if_needed(layout, &marker.locality_id)
        {
            migrated_from.extend(from);
        }
        if !migrated_from.is_empty() {
            checks.push(DoctorCheck {
                check: "config_migration".to_owned(),
                file: layout
                    .repo_overlay_config_path(&marker.locality_id)
                    .map(|p| p.display().to_string())
                    .unwrap_or_default(),
                status: "migrated",
                severity: "info",
                message: format!(
                    "migrated {} legacy config file(s) to repo overlay config.toml",
                    migrated_from.len()
                ),
            });
        }

        checks.extend(validate_linked_repo(
            repo_root,
            layout,
            &marker.locality_id,
        )?);
        let validation_profile =
            load_repo_validation_profile(layout, &marker.locality_id, &mut checks)?;
        checks.extend(validate_clone_state_with_profile(
            repo_root,
            layout,
            &marker.locality_id,
            &validation_profile,
        )?);
        match memory_provider::inspect_provider(repo_root, layout, &marker.locality_id, true) {
            Ok(inspection) => {
                if inspection.issues.is_empty() {
                    let config_path = layout.profile_config_path().display().to_string();
                    let provider = &inspection.view.effective_recall_provider;
                    let message = if inspection.view.configured_recall_provider.is_some() {
                        format!(
                            "memory recall provider `{}` is healthy with capabilities [{}]; startup recall policy is `{}`",
                            provider.name,
                            provider.capabilities.join(", "),
                            inspection.view.start_recall_policy.mode
                        )
                    } else {
                        format!(
                            "memory recall uses built-in `{}` fallback; startup recall policy is `{}`",
                            provider.name,
                            inspection.view.start_recall_policy.mode
                        )
                    };
                    checks.push(pass_check("memory_provider", &config_path, message));
                } else {
                    for issue in inspection.issues {
                        checks.push(fail_check(issue.check, &issue.file, issue.message));
                    }
                }
            }
            Err(error) => checks.push(fail_check(
                "memory_provider",
                &layout.profile_config_path().display().to_string(),
                format!("failed to inspect memory provider configuration: {error:#}"),
            )),
        }

        host_integrations = host::inspect(repo_root, layout, &marker.locality_id)?;
        for integration in &host_integrations {
            checks.extend(host_integration_checks(integration));
        }
    }

    if options.include_repo_native_checks {
        checks.extend(validate_repo_native_checks(repo_root));
    }

    let has_mirror = repo_root.join("CLAUDE.md").exists()
        || repo_root.join("GEMINI.md").exists()
        || repo_root.join(".claude/CLAUDE.md").exists()
        || repo_root.join("skills/canonical").is_dir();

    if has_mirror {
        match agents_contents.as_deref() {
            Some(agents) => {
                let hash = sync::sha256(agents);
                match sync::render_all(repo_root, agents, &hash, &sync_profile) {
                    Ok(generated) => {
                        let check = sync::check_generated(&generated);
                        if check.ok {
                            checks.push(pass_check(
                                "mirror_sync",
                                "generated mirrors",
                                "Generated mirrors are in sync",
                            ));
                        } else {
                            for issue in sync::with_surface_messages(
                                check.issues,
                                sync::SyncIssueSurface::Doctor,
                                repo_root,
                            ) {
                                checks.push(fail_check(
                                    "mirror_sync",
                                    &issue.label,
                                    &issue.message,
                                ));
                            }
                        }
                    }
                    Err(error) => {
                        checks.push(fail_check(
                            "mirror_sync",
                            "generated mirrors",
                            format!("failed to render generated mirrors: {error:#}"),
                        ));
                    }
                }
            }
            None => {
                checks.push(fail_check(
                    "mirror_sync",
                    "AGENTS.md",
                    "Generated mirrors exist but AGENTS.md is missing",
                ));
            }
        }
    } else {
        checks.push(pass_check(
            "mirror_sync",
            "generated mirrors",
            "No generated mirrors present; skipping sync check",
        ));
    }

    let failures = checks
        .iter()
        .filter(|check| check.severity == "error")
        .count();
    let warnings = checks
        .iter()
        .filter(|check| check.severity == "warning")
        .count();

    Ok(DoctorReport {
        command: "doctor",
        ok: failures == 0,
        repo_root: repo_root.display().to_string(),
        failures,
        warnings,
        host_integrations,
        checks,
    })
}

fn host_integration_checks(status: &host::HostIntegrationStatus) -> Vec<DoctorCheck> {
    let mut checks = Vec::new();
    if status.scaffold_status != host::IntegrationAssetStatus::NotApplicable {
        let (check_status, severity, message) = match status.scaffold_status {
            host::IntegrationAssetStatus::Present => (
                "pass",
                "info",
                format!(
                    "repo expects {} ({}) and the CCD-managed scaffold is present",
                    status.host, status.mode
                ),
            ),
            host::IntegrationAssetStatus::Missing => (
                "warn",
                "warning",
                format!(
                    "repo expects {} ({}) but the CCD-managed scaffold is missing; run `ccd init --host {} --path .`",
                    status.host, status.mode, status.host
                ),
            ),
            host::IntegrationAssetStatus::Drifted => (
                "warn",
                "warning",
                format!(
                    "repo expects {} ({}) but the CCD-managed scaffold has drifted from the generated content",
                    status.host, status.mode
                ),
            ),
            host::IntegrationAssetStatus::InvalidMode => unreachable!(),
            host::IntegrationAssetStatus::NotApplicable => unreachable!(),
        };
        checks.push(DoctorCheck {
            check: "host_scaffold".to_owned(),
            file: status.source_paths.join(", "),
            status: check_status,
            severity,
            message,
        });
    }

    if status.install_status != host::IntegrationAssetStatus::NotApplicable {
        let (check_status, severity, message) = match status.install_status {
            host::IntegrationAssetStatus::Present => (
                "pass",
                "info",
                format!(
                    "{} ({}) is installed at the expected runtime path",
                    status.host, status.mode
                ),
            ),
            host::IntegrationAssetStatus::Missing => (
                "warn",
                "warning",
                format!(
                    "{} ({}) is expected but not installed; run `ccd host install {} --path .`",
                    status.host, status.mode, status.host
                ),
            ),
            host::IntegrationAssetStatus::Drifted => (
                "warn",
                "warning",
                format!(
                    "{} ({}) is installed but drifted from the CCD-managed apply output",
                    status.host, status.mode
                ),
            ),
            host::IntegrationAssetStatus::InvalidMode => (
                "warn",
                "warning",
                format!(
                    "{} ({}) is configured with an unsupported install mode; repair the repo overlay before applying runtime assets",
                    status.host, status.mode
                ),
            ),
            host::IntegrationAssetStatus::NotApplicable => unreachable!(),
        };
        checks.push(DoctorCheck {
            check: "host_install".to_owned(),
            file: status.applied_paths.join(", "),
            status: check_status,
            severity,
            message,
        });
    }
    checks
}

fn validate_profile_kernel(layout: &StateLayout) -> Result<Vec<DoctorCheck>> {
    let mut checks = Vec::new();
    let profile_root = layout.profile_root();
    if !profile_root.is_dir() {
        checks.push(fail_check(
            "profile_kernel",
            &profile_root.display().to_string(),
            format!(
                "profile `{}` does not exist at {}",
                layout.profile(),
                profile_root.display()
            ),
        ));
        return Ok(checks);
    }

    checks.push(pass_check(
        "profile_kernel",
        &profile_root.display().to_string(),
        format!(
            "profile `{}` exists at {}",
            layout.profile(),
            profile_root.display()
        ),
    ));

    for path in [
        layout.profile_config_path(),
        layout.profile_policy_path(),
        layout.profile_memory_path(),
    ] {
        let label = path.display().to_string();
        if path.is_file() {
            checks.push(pass_check(
                "profile_file",
                &label,
                format!("{label} exists"),
            ));
        } else {
            checks.push(fail_check(
                "profile_file",
                &label,
                format!("{label} is missing"),
            ));
        }
    }

    let profile_memory_path = layout.profile_memory_path();
    if profile_memory_path.is_file() {
        checks.extend(validate_structured_memory_file(&profile_memory_path));
    }

    Ok(checks)
}

fn validate_linked_repo(
    repo_root: &Path,
    layout: &StateLayout,
    locality_id: &str,
) -> Result<Vec<DoctorCheck>> {
    let mut checks = Vec::new();
    let doctor_command = if layout.profile().as_str() == profile::DEFAULT_PROFILE {
        format!("ccd doctor --path {}", repo_root.display())
    } else {
        format!(
            "ccd doctor --path {} --profile {}",
            repo_root.display(),
            layout.profile()
        )
    };
    let registry_path = layout.repo_metadata_path(locality_id)?;
    match repo_registry::load(&registry_path) {
        Ok(Some(_)) => checks.push(pass_check(
            "repo_registry",
            &registry_path.display().to_string(),
            format!("project registry exists for project ID `{locality_id}`"),
        )),
        Ok(None) => checks.push(fail_check(
            "repo_registry",
            &registry_path.display().to_string(),
            format!("project registry is missing for project ID `{locality_id}`"),
        )),
        Err(error) => checks.push(fail_check(
            "repo_registry",
            &registry_path.display().to_string(),
            format!("failed to read project registry for project ID `{locality_id}`: {error:#}"),
        )),
    }

    let overlay_root = layout.repo_overlay_root(locality_id)?;
    if overlay_root.is_dir() {
        checks.push(pass_check(
            "repo_overlay",
            &overlay_root.display().to_string(),
            format!("project overlay exists for project ID `{locality_id}`"),
        ));
    } else {
        checks.push(fail_check(
            "repo_overlay",
            &overlay_root.display().to_string(),
            format!("project overlay is missing for project ID `{locality_id}`"),
        ));
    }

    match pod_identity::resolve_pod_identity_view(layout) {
        Ok(identity) if identity.status == "declared" => {
            let manifest_path = identity
                .manifest_path
                .as_deref()
                .unwrap_or("<unknown pod manifest>");
            checks.push(pass_check(
                "pod_identity",
                manifest_path,
                format!(
                    "pod identity `{}` is declared for profile `{}`",
                    identity.name.as_deref().unwrap_or("<unknown>"),
                    layout.profile()
                ),
            ));
            if let Some(policy_path) = identity.policy_path.as_deref() {
                let message = if Path::new(policy_path).is_file() {
                    format!("pod policy is authored at {policy_path}")
                } else {
                    format!("pod policy is not authored yet at {policy_path}")
                };
                checks.push(pass_check("pod_policy", policy_path, message));
            }
        }
        Ok(_) => checks.push(pass_check(
            "pod_identity",
            &layout.ccd_root().join("pods").display().to_string(),
            format!(
                "no active pod identity is declared for profile `{}`",
                layout.profile()
            ),
        )),
        Err(error) => checks.push(fail_check(
            "pod_identity",
            &layout.ccd_root().join("pods").display().to_string(),
            format!(
                "ccd doctor found invalid pod identity state under {}; pod-scoped memory and policy may resolve incorrectly until the pod manifests are fixed. Fix the pod manifests and rerun `{doctor_command}`: {error:#}",
                layout.ccd_root().join("pods").display()
            ),
        )),
    }

    match pod_identity::resolve_coordination_scope_view(layout, locality_id) {
        Ok(scope) if scope.status == "configured" => checks.push(pass_check(
            "coordination_scope",
            scope
                .config_path
                .as_deref()
                .unwrap_or("<unknown coordination-scope config>"),
            format!(
                "coordination scope `{}` is configured for project `{locality_id}`",
                scope.name.as_deref().unwrap_or("<unknown>")
            ),
        )),
        Ok(_) => checks.push(pass_check(
            "coordination_scope",
            &overlay_root.display().to_string(),
            "no coordination scope is configured for this project",
        )),
        Err(error) => checks.push(fail_check(
            "coordination_scope",
            &overlay_root.display().to_string(),
            format!(
                "ccd doctor found invalid coordination scope configuration for project `{locality_id}`; shared dispatch and pod compatibility may resolve incorrectly until `[dispatch].coordination_scope` or legacy pod aliases are fixed. Inspect the active profile and project overlay config, then rerun `{doctor_command}`: {error:#}"
            ),
        )),
    }

    match pod_identity::resolve_machine_identity_view(layout) {
        Ok(machine) if machine.status == "declared" => {
            let manifest_path = machine
                .manifest_path
                .as_deref()
                .unwrap_or("<unknown machine manifest>");
            checks.push(pass_check(
                "machine_identity",
                manifest_path,
                format!(
                    "machine identity `{}` is declared for pod `{}` with trust class `{}`",
                    machine.id.as_deref().unwrap_or("<unknown>"),
                    machine.pod_name.as_deref().unwrap_or("<unknown>"),
                    match machine.trust_class {
                        Some(pod_identity::MachineTrustClass::Owned) => "owned",
                        Some(pod_identity::MachineTrustClass::Limited) => "limited",
                        Some(pod_identity::MachineTrustClass::Observer) => "observer",
                        None => "unknown",
                    }
                ),
            ));
        }
        Ok(machine) => {
            let path = machine
                .manifest_path
                .unwrap_or_else(|| layout.ccd_root().join("pods").display().to_string());
            let message = machine.reason.unwrap_or_else(|| {
                format!(
                    "no active machine identity is declared for profile `{}`",
                    layout.profile()
                )
            });
            checks.push(pass_check("machine_identity", &path, message));
        }
        Err(error) => checks.push(fail_check(
            "machine_identity",
            &layout.ccd_root().join("pods").display().to_string(),
            format!(
                "ccd doctor found invalid machine identity state under {}; machine-specific reporting and capability hints may resolve incorrectly until the machine manifest is fixed. Fix `machine.toml` and rerun `{doctor_command}`: {error:#}",
                layout.ccd_root().join("pods").display()
            ),
        )),
    }

    match project_truth::resolve_manifest(repo_root, layout, locality_id) {
        Ok(resolution) => {
            if resolution.manifest_status == "loaded" {
                checks.push(pass_check(
                    "repo_manifest",
                    &resolution.manifest_path.display().to_string(),
                    format!(
                        "{} loaded with {} source entrie(s)",
                        resolution.manifest_path.display(),
                        resolution.entries.len()
                    ),
                ));
            }
            if let Some(message) = project_truth::legacy_roadmap_exclusion_warning_from_resolution(
                repo_root,
                &resolution,
            ) {
                checks.push(warn_check(
                    "legacy_roadmap",
                    project_truth::LEGACY_ROADMAP_PATH,
                    message,
                ));
            }
        }
        Err(error) => checks.push(fail_check(
            "repo_manifest",
            &layout
                .repo_manifest_path(locality_id)?
                .display()
                .to_string(),
            format!("manifest validation failed: {error:#}"),
        )),
    }

    for path in [
        layout.repo_policy_path(locality_id)?,
        layout.repo_memory_path(locality_id)?,
    ] {
        if !path.exists() {
            continue;
        }

        match fs::read_to_string(&path) {
            Ok(_) => checks.push(pass_check(
                "repo_overlay_file",
                &path.display().to_string(),
                format!("{} is readable", path.display()),
            )),
            Err(error) => checks.push(fail_check(
                "repo_overlay_file",
                &path.display().to_string(),
                format!("failed to read {}: {error}", path.display()),
            )),
        }
    }

    let repo_memory_path = layout.repo_memory_path(locality_id)?;
    if repo_memory_path.is_file() {
        checks.extend(validate_structured_memory_file(&repo_memory_path));
    }

    for diagnostic in crate::extensions::health_diagnostics(layout, repo_root, locality_id)? {
        checks.push(match diagnostic.severity {
            "error" => fail_check(diagnostic.check, &diagnostic.file, diagnostic.message),
            "warning" => warn_check(diagnostic.check, &diagnostic.file, diagnostic.message),
            _ => pass_check(diagnostic.check, &diagnostic.file, diagnostic.message),
        });
    }

    Ok(checks)
}

fn validate_clone_state_with_profile(
    repo_root: &Path,
    layout: &StateLayout,
    locality_id: &str,
    validation_profile: &ValidationProfile,
) -> Result<Vec<DoctorCheck>> {
    let mut checks = Vec::new();
    let clone_profile_root = layout.clone_profile_root();
    if clone_profile_root.is_dir() {
        checks.push(pass_check(
            "clone_state",
            &clone_profile_root.display().to_string(),
            format!(
                "workspace-local state exists for profile `{}`",
                layout.profile()
            ),
        ));
    } else {
        checks.push(fail_check(
            "clone_state",
            &clone_profile_root.display().to_string(),
            format!(
                "workspace-local state is missing for profile `{}`",
                layout.profile()
            ),
        ));
        return Ok(checks);
    }

    if layout.resolved_substrate().kind() == SubstrateKind::Directory {
        if let Some(binding_path) = layout.resolved_substrate().workspace_binding_path() {
            checks.push(pass_check(
                "workspace_binding",
                &binding_path.display().to_string(),
                format!(
                    "directory workspace binding is valid for profile `{}`",
                    layout.profile()
                ),
            ));
        }
    }

    let db_label = layout.state_db_path().display().to_string();
    let handoff_surface = match runtime_state::load_canonical_handoff_surface(layout) {
        Ok(surface) => Some(surface),
        Err(error) => {
            checks.push(fail_check(
                "runtime_state",
                &db_label,
                format!("failed to check {db_label}: {error:#}"),
            ));
            None
        }
    };
    if let Some(surface) = handoff_surface.as_ref() {
        if surface.is_missing() {
            checks.push(pass_check(
                "runtime_state",
                &db_label,
                format!(
                    "{db_label} has no handoff state; `ccd start` will create it when a session begins"
                ),
            ));
        } else {
            checks.push(pass_check(
                "runtime_state",
                &db_label,
                format!("{db_label} is present and canonical"),
            ));
        }
    }

    if let Some(handoff_surface) = handoff_surface.as_ref() {
        let label = handoff_surface.path.display().to_string();
        if handoff_surface.is_missing() {
            checks.push(configured_check(
                "handoff",
                &label,
                format!(
                    "{label} has no handoff state; run `ccd start` to create the canonical workspace-local handoff"
                ),
                validation_profile.doctor.handoff.missing,
            ));
        } else {
            checks.extend(validate_handoff_quality(
                &label,
                &handoff_surface.content,
                &validation_profile.doctor.handoff,
            ));
            if layout.resolved_substrate().is_git() {
                let git = handoff::read_git_state(repo_root, BranchMode::AllowDetachedHead)?;
                let checkout_advisory = handoff::checkout_continuity_advisory(repo_root, &git);
                if let Some(advisory) = checkout_advisory.as_ref() {
                    checks.push(warn_check(
                        "checkout_state",
                        &label,
                        advisory.doctor_message(&git),
                    ));
                }
            } else {
                checks.push(pass_check(
                    "checkout_state",
                    &label,
                    format!(
                        "{label} uses the directory substrate; Git checkout freshness is unavailable by design"
                    ),
                ));
            }
        }
    }

    match session_state::load_for_layout(layout) {
        Ok(Some(state)) => {
            let now = session_state::now_epoch_s()?;
            if session_state::is_stale(&state, now) {
                checks.push(warn_check(
                    "session_state",
                    &db_label,
                    format!(
                        "{db_label} is stale; refresh session-state before relying on context-health telemetry"
                    ),
                ));
            } else {
                checks.push(pass_check(
                    "session_state",
                    &db_label,
                    format!("{db_label} is present and fresh"),
                ));
            }
        }
        Ok(None) => checks.push(pass_check(
            "session_state",
            &db_label,
            format!(
                "{db_label} has no session telemetry; run `ccd session-state start` to record it"
            ),
        )),
        Err(error) => checks.push(fail_check(
            "session_state",
            &db_label,
            format!("failed to read session state from {db_label}: {error:#}"),
        )),
    }

    let compiled_state_label = layout.compiled_state_path().display().to_string();
    let compiled_state_message = if layout.compiled_state_path().exists() {
        format!(
            "{compiled_state_label} is present as an implementation-private optimization artifact; default CCD correctness does not require it"
        )
    } else {
        format!(
            "{compiled_state_label} is absent; default CCD correctness computes derived runtime views on demand from canonical state"
        )
    };
    checks.push(pass_check(
        "compiled_state",
        &compiled_state_label,
        compiled_state_message,
    ));

    match consistency::evaluate(repo_root, layout, locality_id) {
        Ok(consistency) => checks.extend(consistency_doctor_checks(
            layout,
            locality_id,
            &consistency.axes,
        )?),
        Err(error) => checks.push(warn_check(
            "consistency_audit",
            &layout.state_db_path().display().to_string(),
            format!(
                "artifact consistency audit was skipped because runtime state could not be loaded deterministically: {error:#}"
            ),
        )),
    }

    Ok(checks)
}

fn load_repo_validation_profile(
    layout: &StateLayout,
    locality_id: &str,
    checks: &mut Vec<DoctorCheck>,
) -> Result<ValidationProfile> {
    let loaded = validation_profile::load_for_layout(layout, locality_id)?;
    let label = loaded.path.display().to_string();

    match loaded.status {
        "loaded" => {
            checks.push(pass_check(
                "repo_validation_profile",
                &label,
                format!("{label} loaded"),
            ));
            Ok(loaded.profile)
        }
        "missing" => Ok(loaded.profile),
        _ => {
            checks.push(fail_check(
                "repo_validation_profile",
                &label,
                format!(
                    "failed to load {label}: {}",
                    loaded
                        .error
                        .unwrap_or_else(|| "invalid validation profile".to_owned())
                ),
            ));
            Ok(loaded.profile)
        }
    }
}

fn validate_repo_native_checks(repo_root: &Path) -> Vec<DoctorCheck> {
    match check::run(repo_root) {
        Ok(report) if report.surface.status == "absent" => vec![pass_check(
            "repo_native_check",
            check::COMMANDS_DIR,
            report.surface.note.unwrap_or_else(|| {
                format!(
                    "No repo-native `{}` commands registered under {}.",
                    check::CHECK_PREFIX,
                    check::COMMANDS_DIR
                )
            }),
        )],
        Ok(report) if report.surface.status == "loaded" && report.surface.entries.is_empty() => {
            vec![pass_check(
                "repo_native_check",
                check::COMMANDS_DIR,
                report.surface.note.unwrap_or_else(|| {
                    format!(
                        "No repo-native `{}` commands registered under {}.",
                        check::CHECK_PREFIX,
                        check::COMMANDS_DIR
                    )
                }),
            )]
        }
        Ok(report) => report
            .checks
            .into_iter()
            .map(|result| match result.severity {
                "info" => pass_check("repo_native_check", &result.path, result.message),
                "warning" => warn_check("repo_native_check", &result.path, result.message),
                _ => fail_check(
                    "repo_native_check",
                    &result.path,
                    format!(
                        "{} Rerun `ccd check --path .` for captured stdout/stderr.",
                        result.message
                    ),
                ),
            })
            .collect(),
        Err(error) => vec![fail_check(
            "repo_native_check",
            check::COMMANDS_DIR,
            format!("failed to inspect repo-native checks: {error:#}"),
        )],
    }
}

fn known_file_rules<'a>(
    file: &'a str,
    sync: &sync::SyncProfile,
) -> (&'a [&'a str], Option<(usize, usize)>) {
    match file {
        "AGENTS.md" => (
            AGENTS_PLACEHOLDERS,
            Some((sync.soft_line_limit, sync.hard_line_limit)),
        ),
        "MEMORY.md" => (MEMORY_PLACEHOLDERS, None),
        _ => (&[], None),
    }
}

fn inspect_core_file(
    path: &Path,
    label: &str,
    placeholders: &[&str],
    budget: Option<(usize, usize)>,
) -> Result<InspectedCoreFile> {
    let mut checks = Vec::new();

    let contents = match fs::read_to_string(path) {
        Ok(contents) => contents,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            checks.push(fail_check("exists", label, format!("{label} is missing")));
            return Ok(InspectedCoreFile {
                checks,
                contents: None,
            });
        }
        Err(error) => return Err(error.into()),
    };

    checks.push(pass_check("exists", label, format!("{label} exists")));
    let unresolved = unresolved_placeholders(&contents, placeholders);
    if !unresolved.is_empty() {
        checks.push(warn_check(
            "placeholders",
            label,
            format!(
                "{label} still contains template placeholders: {}",
                unresolved.join(", ")
            ),
        ));
    }

    if let Some((soft, hard)) = budget {
        let lines = sync::line_count(&contents);
        if lines > hard {
            checks.push(fail_check(
                "line_budget",
                label,
                format!("{label} is {lines} lines (hard limit: {hard})"),
            ));
        } else if lines > soft {
            checks.push(warn_check(
                "line_budget",
                label,
                format!("{label} is {lines} lines (soft limit: {soft})"),
            ));
        }
    }

    Ok(InspectedCoreFile {
        checks,
        contents: Some(contents),
    })
}

fn validate_structured_memory_file(path: &Path) -> Vec<DoctorCheck> {
    let label = path.display().to_string();
    let contents = match fs::read_to_string(path) {
        Ok(contents) => contents,
        Err(error) => {
            return vec![fail_check(
                "memory_structure",
                &label,
                format!("failed to read {}: {error}", path.display()),
            )];
        }
    };

    let report = memory_entries::parse_document(&contents);
    if !report.diagnostics.is_empty() {
        return vec![fail_check(
            "memory_structure",
            &label,
            format!(
                "{} has invalid structured CCD memory entries: {}",
                path.display(),
                report.diagnostics.join("; ")
            ),
        )];
    }

    if report.block_count == 0 {
        return Vec::new();
    }

    let noun = if report.entries.len() == 1 {
        "entry"
    } else {
        "entries"
    };
    vec![pass_check(
        "memory_structure",
        &label,
        format!(
            "{} has {} valid structured CCD memory {}",
            path.display(),
            report.entries.len(),
            noun
        ),
    )]
}

fn unresolved_placeholders<'a>(contents: &str, placeholders: &[&'a str]) -> Vec<&'a str> {
    placeholders
        .iter()
        .copied()
        .filter(|placeholder| contents.contains(placeholder))
        .collect()
}

fn validate_handoff_quality(
    label: &str,
    contents: &str,
    handoff_profile: &HandoffDoctorValidationProfile,
) -> Vec<DoctorCheck> {
    let mut checks = Vec::new();

    let mut missing_sections = Vec::new();

    for &section in handoff::REQUIRED_SECTIONS {
        if !handoff::has_section(contents, section) {
            missing_sections.push(section);
        }
    }

    if missing_sections.is_empty() {
        checks.push(pass_check(
            "handoff_quality",
            label,
            format!("{label} has all required sections"),
        ));
    } else {
        checks.push(configured_check(
            "handoff_sections",
            label,
            format!(
                "{label} is missing required sections: {}",
                missing_sections.join(", ")
            ),
            handoff_profile.sections,
        ));
    }

    let matched: Vec<&&str> = SESSION_LOG_PHRASES
        .iter()
        .filter(|phrase| contains_ascii_case_insensitive(contents, phrase))
        .collect();

    if !matched.is_empty() {
        checks.push(configured_check(
            "handoff_narration",
            label,
            format!(
                "{label} reads like a session log — found narration phrases: {}. \
                 Prefer factual state descriptions over action narration.",
                matched
                    .iter()
                    .map(|p| format!("\"{p}\""))
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
            handoff_profile.narration,
        ));
    }

    checks
}

fn contains_ascii_case_insensitive(contents: &str, needle: &str) -> bool {
    let haystack = contents.as_bytes();
    let needle = needle.as_bytes();
    haystack
        .windows(needle.len())
        .any(|window| window.eq_ignore_ascii_case(needle))
}

#[cfg(test)]
mod tests {
    use super::contains_ascii_case_insensitive;

    #[test]
    fn contains_ascii_case_insensitive_matches_mixed_case_boundaries() {
        assert!(contains_ascii_case_insensitive("Session Log", "session"));
        assert!(contains_ascii_case_insensitive("Session Log", "LOG"));
        assert!(!contains_ascii_case_insensitive("Session Log", "logout"));
    }
}

fn pass_check(check: &str, file: &str, message: impl Into<String>) -> DoctorCheck {
    DoctorCheck {
        check: check.to_owned(),
        file: file.to_owned(),
        status: "pass",
        severity: "info",
        message: message.into(),
    }
}

fn warn_check(check: &str, file: &str, message: impl Into<String>) -> DoctorCheck {
    DoctorCheck {
        check: check.to_owned(),
        file: file.to_owned(),
        status: "warn",
        severity: "warning",
        message: message.into(),
    }
}

fn consistency_doctor_checks(
    layout: &StateLayout,
    locality_id: &str,
    axes: &[consistency::ConsistencyAxis],
) -> Result<Vec<DoctorCheck>> {
    axes.iter()
        .map(|axis| {
            let label = consistency_axis_surface(layout, locality_id, axis.id)?;
            let check = match axis.status {
                consistency::ConsistencyStatus::Aligned
                | consistency::ConsistencyStatus::NoSignal => {
                    pass_check(axis.id, &label, axis.summary.clone())
                }
                consistency::ConsistencyStatus::Drift => {
                    warn_check(axis.id, &label, axis.summary.clone())
                }
            };
            Ok(check)
        })
        .collect()
}

fn consistency_axis_surface(
    layout: &StateLayout,
    locality_id: &str,
    axis_id: &str,
) -> Result<String> {
    let label = match axis_id {
        consistency::MEMORY_COHERENCE_AXIS => format!(
            "{}, {}",
            layout.profile_runtime_state_path().display(),
            layout.locality_runtime_state_path(locality_id)?.display()
        ),
        _ => layout.state_db_path().display().to_string(),
    };
    Ok(label)
}

struct InspectedCoreFile {
    checks: Vec<DoctorCheck>,
    contents: Option<String>,
}

fn fail_check(check: &str, file: &str, message: impl Into<String>) -> DoctorCheck {
    DoctorCheck {
        check: check.to_owned(),
        file: file.to_owned(),
        status: "fail",
        severity: "error",
        message: message.into(),
    }
}

fn configured_check(
    check: &str,
    file: &str,
    message: impl Into<String>,
    severity: ValidationSeverity,
) -> DoctorCheck {
    match severity {
        ValidationSeverity::Warning => warn_check(check, file, message),
        ValidationSeverity::Error => fail_check(check, file, message),
    }
}