specsync 4.1.0

Bidirectional spec-to-code validation with schema column checking — 11 languages, single binary
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
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
use crate::config::{default_schema_pattern, discover_manifest_modules};
use crate::exports::{get_exported_symbols_full, has_extension, is_test_file};
use crate::parser::{
    find_stub_sections, get_missing_sections, get_spec_symbols, parse_frontmatter,
};
use crate::schema::{self, SchemaTable};
use crate::types::{
    CoverageReport, CustomRuleType, Frontmatter, RuleSeverity, SpecSyncConfig, ValidationResult,
};
use regex::Regex;
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
use walkdir::WalkDir;

static CONSUMED_BY_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?s)### Consumed By\s*\n(.*?)(?:\n## |\n### |$)").unwrap());
static FILE_REF_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\|\s*`([^`]+\.\w+)`\s*\|").unwrap());
static NUMBERED_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?m)^\d+\.\s+\S").unwrap());

/// Check if a dependency reference is a cross-project reference.
/// Cross-project refs use the format `owner/repo@module` (e.g. `corvid-labs/algochat@auth`).
pub fn is_cross_project_ref(dep: &str) -> bool {
    dep.contains('/') && dep.contains('@')
}

/// Parse a cross-project reference into (owner/repo, module).
/// Returns None if not a valid cross-project ref.
pub fn parse_cross_project_ref(dep: &str) -> Option<(&str, &str)> {
    if !is_cross_project_ref(dep) {
        return None;
    }
    let at_pos = dep.find('@')?;
    let repo = &dep[..at_pos];
    let module = &dep[at_pos + 1..];
    if repo.is_empty() || module.is_empty() {
        return None;
    }
    Some((repo, module))
}

// ─── Schema Table Discovery ──────────────────────────────────────────────

/// Extract table names from SQL schema files.
pub fn get_schema_table_names(root: &Path, config: &SpecSyncConfig) -> HashSet<String> {
    let mut tables = HashSet::new();
    let schema_dir = match &config.schema_dir {
        Some(d) => root.join(d),
        None => return tables,
    };

    if !schema_dir.exists() {
        return tables;
    }

    let pattern_str = config
        .schema_pattern
        .as_deref()
        .unwrap_or_else(|| default_schema_pattern());

    let re = match Regex::new(pattern_str) {
        Ok(r) => r,
        Err(_) => return tables,
    };

    if let Ok(entries) = fs::read_dir(&schema_dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
            if ext != "ts" && ext != "sql" {
                continue;
            }
            if let Ok(content) = fs::read_to_string(&path) {
                for caps in re.captures_iter(&content) {
                    if let Some(name) = caps.get(1) {
                        tables.insert(name.as_str().to_string());
                    }
                }
            }
        }
    }

    tables
}

// ─── File Discovery ──────────────────────────────────────────────────────

/// Find all *.spec.md files in a directory recursively.
pub fn find_spec_files(dir: &Path) -> Vec<PathBuf> {
    let mut results = Vec::new();
    if !dir.exists() {
        return results;
    }

    for entry in WalkDir::new(dir).into_iter().filter_map(|e| e.ok()) {
        let path = entry.path();
        if path.is_file()
            && let Some(name) = path.file_name().and_then(|n| n.to_str())
            && name.ends_with(".spec.md")
        {
            results.push(path.to_path_buf());
        }
    }

    results.sort();
    results
}

/// Find source files in a directory, respecting exclusions.
fn find_source_files(
    dir: &Path,
    exclude_dirs: &HashSet<String>,
    config: &SpecSyncConfig,
) -> Vec<PathBuf> {
    let mut results = Vec::new();
    if !dir.exists() {
        return results;
    }

    for entry in WalkDir::new(dir)
        .into_iter()
        .filter_entry(|e| {
            if e.file_type().is_dir() {
                let name = e.file_name().to_str().unwrap_or("");
                !exclude_dirs.contains(name)
            } else {
                true
            }
        })
        .filter_map(|e| e.ok())
    {
        let path = entry.path();
        if path.is_file() && has_extension(path, &config.source_extensions) && !is_test_file(path) {
            results.push(path.to_path_buf());
        }
    }

    results
}

// ─── Single Spec Validation ──────────────────────────────────────────────

/// Validate a single spec file against source code.
pub fn validate_spec(
    spec_path: &Path,
    root: &Path,
    schema_tables: &HashSet<String>,
    schema_columns: &HashMap<String, SchemaTable>,
    config: &SpecSyncConfig,
) -> ValidationResult {
    let rel_path = spec_path
        .strip_prefix(root)
        .unwrap_or(spec_path)
        .to_string_lossy()
        .to_string();

    let mut result = ValidationResult::new(rel_path);

    let content = match fs::read_to_string(spec_path) {
        Ok(c) => c.replace("\r\n", "\n"),
        Err(e) => {
            result.errors.push(format!("Cannot read spec: {e}"));
            return result;
        }
    };

    let parsed = match parse_frontmatter(&content) {
        Some(p) => p,
        None => {
            result.errors.push(
                "Missing or malformed YAML frontmatter (expected --- delimiters)".to_string(),
            );
            return result;
        }
    };

    let fm = &parsed.frontmatter;
    let body = &parsed.body;

    // Archived specs: skip all validation with zero diagnostics.
    // Must be invisible to --strict mode.
    if fm.parsed_status() == Some(crate::types::SpecStatus::Archived) {
        return result;
    }

    // ─── Level 1: Structural ──────────────────────────────────────────

    if fm.module.is_none() {
        result
            .errors
            .push("Frontmatter missing required field: module".to_string());
        result
            .fixes
            .push("Add `module: your-module-name` to the YAML frontmatter block".to_string());
    }
    if fm.version.is_none() {
        result
            .errors
            .push("Frontmatter missing required field: version".to_string());
        result
            .fixes
            .push("Add `version: 1` to the YAML frontmatter block".to_string());
    }
    if fm.status.is_none() {
        result
            .errors
            .push("Frontmatter missing required field: status".to_string());
        result.fixes.push(
            "Add `status: active` (or draft/review/stable/deprecated/archived) to the frontmatter"
                .to_string(),
        );
    } else if let Some(status_str) = &fm.status {
        if fm.parsed_status().is_none() {
            result.warnings.push(format!(
                "Unknown status '{}' — expected one of: draft, review, active, stable, deprecated, archived",
                status_str
            ));
        }
    }

    // Status lifecycle warnings
    let spec_status = fm.parsed_status();
    if spec_status == Some(crate::types::SpecStatus::Deprecated) {
        result
            .warnings
            .push("Spec is deprecated — consider archiving with `specsync lifecycle promote <spec>` or `specsync lifecycle set <spec> archived`".to_string());
    }

    // Validate agent_policy if present
    if let Some(policy) = &fm.agent_policy {
        match policy.as_str() {
            "read-only" | "suggest-only" | "full-access" => {}
            _ => {
                result.warnings.push(format!(
                    "Unknown agent_policy '{}' — expected: read-only, suggest-only, or full-access",
                    policy
                ));
            }
        }
    }
    if fm.files.is_empty() {
        result.errors.push(
            "Frontmatter missing required field: files (must be a non-empty list)".to_string(),
        );
        result.fixes.push(
            "Add a `files:` list with relative paths to source files this spec covers".to_string(),
        );
    }

    // Check files exist
    for file in &fm.files {
        let full_path = root.join(file);
        if !full_path.exists() {
            result.errors.push(format!("Source file not found: {file}"));
            // Suggest similar files
            if let Some(suggestion) = suggest_similar_file(root, file) {
                result.fixes.push(format!(
                    "Did you mean `{suggestion}`? Update the path in frontmatter"
                ));
            } else {
                result.fixes.push(format!(
                    "Remove `{file}` from files list or create the source file"
                ));
            }
        }
    }

    // Check db_tables exist in schema
    for table in &fm.db_tables {
        if !schema_tables.is_empty() && !schema_tables.contains(table) {
            result
                .errors
                .push(format!("DB table not found in schema: {table}"));
            result.fixes.push(format!(
                "Remove `{table}` from db_tables or add a CREATE TABLE migration"
            ));
        }
    }

    // ─── Level 1.5: Schema Columns ──────────────────────────────────────
    if !schema_columns.is_empty() {
        let spec_schema = schema::parse_spec_schema(body);
        for table_name in &fm.db_tables {
            if let Some(actual_table) = schema_columns.get(table_name)
                && let Some(spec_cols) = spec_schema.get(table_name)
            {
                let actual_names: HashSet<&str> = actual_table
                    .columns
                    .iter()
                    .map(|c| c.name.as_str())
                    .collect();
                let spec_names: HashSet<&str> = spec_cols.iter().map(|c| c.name.as_str()).collect();

                // Spec documents a column that doesn't exist = ERROR
                for sc in spec_cols {
                    if !actual_names.contains(sc.name.as_str()) {
                        result.errors.push(format!(
                            "Schema column `{}.{}` documented in spec but not found in migrations",
                            table_name, sc.name
                        ));
                        result.fixes.push(format!(
                            "Remove `{}` from the ### Schema section or add it via ALTER TABLE",
                            sc.name
                        ));
                    }
                }

                // Column exists in schema but not in spec = WARNING
                for ac in &actual_table.columns {
                    if !spec_names.contains(ac.name.as_str()) {
                        result.warnings.push(format!(
                            "Schema column `{}.{}` exists in migrations but not documented in spec",
                            table_name, ac.name
                        ));
                    }
                }

                // Type mismatch = WARNING
                for sc in spec_cols {
                    if let Some(ac) = actual_table.columns.iter().find(|c| c.name == sc.name) {
                        // Normalise both to uppercase for comparison
                        let spec_type = sc.col_type.to_uppercase();
                        let actual_type = ac.col_type.to_uppercase();
                        if spec_type != actual_type {
                            result.warnings.push(format!(
                                "Schema column `{}.{}` type mismatch: spec says {} but migrations say {}",
                                table_name, sc.name, spec_type, actual_type
                            ));
                        }
                    }
                }
            }
            // If spec has db_tables but no ### Schema section, that's fine —
            // column-level docs are optional. Only validate when present.
        }
    }

    // Required markdown sections
    // - draft: structure only — skip all required section checks
    // - review: structure + sections, but skip "Public API"
    // - active/stable/deprecated: all sections required
    let is_draft = spec_status == Some(crate::types::SpecStatus::Draft);
    let is_review = spec_status == Some(crate::types::SpecStatus::Review);

    if !is_draft {
        let missing = get_missing_sections(body, &config.required_sections);
        for section in &missing {
            if is_review && section == "Public API" {
                continue; // review specs can skip Public API
            }
            result
                .errors
                .push(format!("Missing required section: ## {section}"));
            result
                .fixes
                .push(format!("Add `## {section}` heading to the spec body"));
        }
    }

    // ─── Level 1.7: Stub/Placeholder Detection ──────────────────────
    let stub_sections = find_stub_sections(body, &config.required_sections);
    if !stub_sections.is_empty() {
        for section in &stub_sections {
            result.warnings.push(format!(
                "Section ## {section} contains only stub/placeholder text (TBD, N/A, TODO, etc.)"
            ));
            result.fixes.push(format!(
                "Replace placeholder content in ## {section} with real documentation"
            ));
        }
    }

    // ─── Level 2: API Surface ─────────────────────────────────────────
    // Draft and review specs skip API surface validation — exports may not exist yet.
    let skip_api = matches!(
        spec_status,
        Some(crate::types::SpecStatus::Draft) | Some(crate::types::SpecStatus::Review)
    );

    if !fm.files.is_empty() && !skip_api {
        // Track exports with their source file for attribution
        let mut exports_by_file: Vec<(String, String)> = Vec::new(); // (symbol, file)
        let mut all_exports: Vec<String> = Vec::new();
        for file in &fm.files {
            let full_path = root.join(file);
            let exports =
                get_exported_symbols_full(&full_path, config.export_level, config.parse_mode);
            for sym in &exports {
                exports_by_file.push((sym.clone(), file.clone()));
            }
            all_exports.extend(exports);
        }

        // Deduplicate (keep first occurrence for file attribution)
        let mut seen = HashSet::new();
        all_exports.retain(|s| seen.insert(s.clone()));

        let spec_symbols = get_spec_symbols(body);
        let spec_set: HashSet<&str> = spec_symbols.iter().map(|s| s.as_str()).collect();
        let export_set: HashSet<&str> = all_exports.iter().map(|s| s.as_str()).collect();

        // Spec documents something that doesn't exist = ERROR
        for sym in &spec_symbols {
            if !export_set.contains(sym.as_str()) {
                result.errors.push(format!(
                    "Spec documents '{sym}' but no matching export found in source"
                ));
            }
        }

        // Code exports something not in spec = WARNING (with source file attribution)
        for sym in &all_exports {
            if !spec_set.contains(sym.as_str()) {
                // Find the source file for this export
                let source_file = exports_by_file
                    .iter()
                    .find(|(s, _)| s == sym)
                    .map(|(_, f)| f.as_str());
                match source_file {
                    Some(file) => {
                        result
                            .warnings
                            .push(format!("Undocumented export '{sym}' from {file}"));
                    }
                    None => {
                        result
                            .warnings
                            .push(format!("Export '{sym}' not in spec (undocumented)"));
                    }
                }
            }
        }

        let documented = spec_symbols
            .iter()
            .filter(|s| export_set.contains(s.as_str()))
            .count();

        if !all_exports.is_empty() {
            let summary = format!("{documented}/{} exports documented", all_exports.len());
            if documented < all_exports.len() {
                result.warnings.insert(0, summary);
            } else {
                result.export_summary = Some(summary);
            }
        }
    }

    // ─── Level 3: Dependencies ────────────────────────────────────────

    if !fm.depends_on.is_empty() {
        for dep in &fm.depends_on {
            if is_cross_project_ref(dep) {
                // Cross-project refs (e.g. "owner/repo@module") are validated
                // by `specsync resolve`, not during local checks.
                continue;
            }
            let full_path = root.join(dep);
            if !full_path.exists() {
                result
                    .errors
                    .push(format!("Dependency spec not found: {dep}"));
            }
        }
    }

    // Check Consumed By section references
    if let Some(caps) = CONSUMED_BY_RE.captures(body) {
        let section = caps.get(1).unwrap().as_str();
        for caps in FILE_REF_RE.captures_iter(section) {
            if let Some(file_ref) = caps.get(1) {
                let file_path = root.join(file_ref.as_str());
                if !file_path.exists() {
                    result.warnings.push(format!(
                        "Consumed By references missing file: {}",
                        file_ref.as_str()
                    ));
                }
            }
        }
    }

    // ─── Level 4: Requirements Companion File ─────────────────────────
    // spec-sync expects requirements in a separate companion file (requirements.md),
    // not inline in the spec body. Warn if requirements appear inline.
    // Drafts and review specs skip this check.
    if !is_draft && spec_status != Some(crate::types::SpecStatus::Review) {
        let has_inline_requirements = {
            let lower = body.to_ascii_lowercase();
            lower.contains("## requirements") || lower.contains("## acceptance criteria")
        };
        if has_inline_requirements {
            result.warnings.push(
                "Inline requirements detected — specs are technical contracts; user stories and acceptance criteria belong in a companion requirements.md file".to_string()
            );
            result.fixes.push(
                "Run `specsync add-spec <name>` to scaffold requirements.md, then move ## Requirements / ## Acceptance Criteria content there".to_string()
            );
        }

        // Check that the companion requirements.md exists for non-draft specs
        if let Some(parent) = spec_path.parent() {
            let req_path = parent.join("requirements.md");
            if !req_path.exists() {
                result.warnings.push(
                    "Missing companion requirements.md — run `specsync add-spec <name>` or `specsync generate` to scaffold one".to_string()
                );
            }
        }
    }

    // ─── Custom Validation Rules ─────────────────────────────────────
    apply_custom_rules(spec_path, body, fm, config, &mut result);

    result
}

/// Apply project-specific custom validation rules from config.
fn apply_custom_rules(
    spec_path: &Path,
    body: &str,
    fm: &Frontmatter,
    config: &SpecSyncConfig,
    result: &mut ValidationResult,
) {
    let rules = &config.rules;

    // max_spec_size_kb: warn if spec file is too large
    if let Some(max_kb) = rules.max_spec_size_kb {
        if let Ok(meta) = fs::metadata(spec_path) {
            let size_kb = meta.len() as usize / 1024;
            if size_kb > max_kb {
                result.warnings.push(format!(
                    "Spec file is {size_kb} KB — exceeds limit of {max_kb} KB"
                ));
            }
        }
    }

    // max_changelog_entries: warn if Change Log has too many rows
    if let Some(max_entries) = rules.max_changelog_entries {
        let count = count_changelog_entries(body);
        if count > max_entries {
            result.warnings.push(format!(
                "Change Log has {count} entries — exceeds limit of {max_entries} (run `specsync compact`)"
            ));
        }
    }

    // require_behavioral_examples: require at least one ### Scenario
    if rules.require_behavioral_examples == Some(true) {
        let scenario_count = body.matches("### Scenario").count();
        if scenario_count == 0 {
            result.errors.push(
                "No behavioral examples found (rule: require_behavioral_examples)".to_string(),
            );
            result.fixes.push(
                "Add at least one `### Scenario:` under `## Behavioral Examples`".to_string(),
            );
        }
    }

    // min_invariants: require a minimum number of numbered invariants
    if let Some(min) = rules.min_invariants {
        let count = count_invariants(body);
        if count < min {
            result.warnings.push(format!(
                "Only {count} invariant(s) found — minimum is {min}"
            ));
        }
    }

    // require_depends_on: require non-empty depends_on in frontmatter
    if rules.require_depends_on == Some(true) && fm.depends_on.is_empty() {
        result
            .warnings
            .push("No consumed dependencies documented (rule: require_depends_on)".to_string());
    }

    // ─── Declarative Custom Rules ────────────────────────────────────
    for rule in &config.custom_rules {
        if !custom_rule_applies(rule, fm) {
            continue;
        }
        if let Some(msg) = evaluate_custom_rule(rule, body) {
            let tagged = format!("{msg} (rule: {})", rule.name);
            match rule.severity {
                RuleSeverity::Error => result.errors.push(tagged),
                RuleSeverity::Warning => result.warnings.push(tagged),
                RuleSeverity::Info => result.warnings.push(format!("[info] {tagged}")),
            }
        }
    }
}

/// Check whether a custom rule applies to the given spec based on its filter.
fn custom_rule_applies(rule: &crate::types::CustomRule, fm: &Frontmatter) -> bool {
    let Some(ref filter) = rule.applies_to else {
        return true;
    };

    if let Some(ref status) = filter.status {
        let spec_status = fm.status.as_deref().unwrap_or("");
        if !spec_status.eq_ignore_ascii_case(status) {
            return false;
        }
    }

    if let Some(ref module_pattern) = filter.module {
        let spec_module = fm.module.as_deref().unwrap_or("");
        if let Ok(re) = Regex::new(module_pattern) {
            if !re.is_match(spec_module) {
                return false;
            }
        }
    }

    true
}

/// Evaluate a single custom rule against the spec body.
/// Returns `Some(message)` if the rule is violated, `None` if it passes.
fn evaluate_custom_rule(rule: &crate::types::CustomRule, body: &str) -> Option<String> {
    match rule.rule_type {
        CustomRuleType::RequireSection => {
            let section = rule.section.as_deref()?;
            let header = format!("## {section}");
            if !body.contains(&header) {
                let msg = rule
                    .message
                    .clone()
                    .unwrap_or_else(|| format!("Missing required section: ## {section}"));
                return Some(msg);
            }
            None
        }
        CustomRuleType::MinWordCount => {
            let section = rule.section.as_deref()?;
            let min = rule.min_words.unwrap_or(1);
            let header = format!("## {section}");
            let section_start = body.find(&header)?;
            let after_header = &body[section_start + header.len()..];
            // Bound section to next ## heading
            let section_end = after_header.find("\n## ").unwrap_or(after_header.len());
            let section_body = &after_header[..section_end];
            let word_count = section_body.split_whitespace().count();
            if word_count < min {
                let msg = rule.message.clone().unwrap_or_else(|| {
                    format!("Section ## {section} has {word_count} words — minimum is {min}")
                });
                return Some(msg);
            }
            None
        }
        CustomRuleType::RequirePattern => {
            let pattern = rule.pattern.as_deref()?;
            let re = Regex::new(pattern).ok()?;
            if !re.is_match(body) {
                let msg = rule
                    .message
                    .clone()
                    .unwrap_or_else(|| format!("Required pattern not found: {pattern}"));
                return Some(msg);
            }
            None
        }
        CustomRuleType::ForbidPattern => {
            let pattern = rule.pattern.as_deref()?;
            let re = Regex::new(pattern).ok()?;
            if re.is_match(body) {
                let msg = rule
                    .message
                    .clone()
                    .unwrap_or_else(|| format!("Forbidden pattern found: {pattern}"));
                return Some(msg);
            }
            None
        }
    }
}

/// Count data rows in the Change Log table (excluding header and separator).
fn count_changelog_entries(body: &str) -> usize {
    let changelog_start = match body.find("## Change Log") {
        Some(pos) => pos,
        None => return 0,
    };
    let section = &body[changelog_start..];
    // Find next ## heading to bound the section
    let section_end = section[1..]
        .find("\n## ")
        .map(|p| p + 1)
        .unwrap_or(section.len());
    let section = &section[..section_end];

    // Count data rows: skip the first two table lines (header + separator)
    let mut table_line_count = 0usize;
    section
        .lines()
        .filter(|line| {
            let trimmed = line.trim();
            if !trimmed.starts_with('|') {
                return false;
            }
            table_line_count += 1;
            table_line_count > 2
        })
        .count()
}

/// Count numbered invariants in the Invariants section.
fn count_invariants(body: &str) -> usize {
    let inv_start = match body.find("## Invariants") {
        Some(pos) => pos,
        None => return 0,
    };
    let section = &body[inv_start..];
    let section_end = section[1..]
        .find("\n## ")
        .map(|p| p + 1)
        .unwrap_or(section.len());
    let section = &section[..section_end];

    NUMBERED_RE.find_iter(section).count()
}

/// Suggest a similar file path when a referenced file doesn't exist.
fn suggest_similar_file(root: &Path, missing_file: &str) -> Option<String> {
    let missing_name = Path::new(missing_file).file_name()?.to_str()?;

    let parent = Path::new(missing_file).parent()?;
    let search_dir = root.join(parent);
    if !search_dir.exists() {
        return None;
    }

    let entries = std::fs::read_dir(&search_dir).ok()?;
    let mut best: Option<(String, usize)> = None;

    for entry in entries.flatten() {
        let name = entry.file_name().to_string_lossy().to_string();
        if !entry.path().is_file() {
            continue;
        }
        let dist = levenshtein(missing_name, &name);
        if dist <= 3 && (best.is_none() || dist < best.as_ref().unwrap().1) {
            let suggestion = parent.join(&name).to_string_lossy().replace('\\', "/");
            best = Some((suggestion, dist));
        }
    }

    best.map(|(s, _)| s)
}

/// Simple Levenshtein distance for file name suggestions.
fn levenshtein(a: &str, b: &str) -> usize {
    let a: Vec<char> = a.chars().collect();
    let b: Vec<char> = b.chars().collect();
    let mut dp = vec![vec![0usize; b.len() + 1]; a.len() + 1];

    for (i, row) in dp.iter_mut().enumerate().take(a.len() + 1) {
        row[0] = i;
    }
    for (j, val) in dp[0].iter_mut().enumerate().take(b.len() + 1) {
        *val = j;
    }
    for i in 1..=a.len() {
        for j in 1..=b.len() {
            let cost = if a[i - 1] == b[j - 1] { 0 } else { 1 };
            dp[i][j] = (dp[i - 1][j] + 1)
                .min(dp[i][j - 1] + 1)
                .min(dp[i - 1][j - 1] + cost);
        }
    }
    dp[a.len()][b.len()]
}

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

    #[test]
    fn test_is_cross_project_ref() {
        assert!(is_cross_project_ref("corvid-labs/algochat@auth"));
        assert!(is_cross_project_ref("owner/repo@module"));
        assert!(!is_cross_project_ref("specs/auth/auth.spec.md"));
        assert!(!is_cross_project_ref("auth"));
        assert!(!is_cross_project_ref("owner/repo")); // no @
        assert!(!is_cross_project_ref("@module")); // no /
    }

    #[test]
    fn test_parse_cross_project_ref() {
        let (repo, module) = parse_cross_project_ref("corvid-labs/algochat@auth").unwrap();
        assert_eq!(repo, "corvid-labs/algochat");
        assert_eq!(module, "auth");

        assert!(parse_cross_project_ref("not-a-ref").is_none());
        assert!(parse_cross_project_ref("/@").is_none()); // empty parts
    }

    #[test]
    fn test_levenshtein() {
        assert_eq!(levenshtein("kitten", "sitting"), 3);
        assert_eq!(levenshtein("abc", "abc"), 0);
        assert_eq!(levenshtein("", "abc"), 3);
        assert_eq!(levenshtein("abc", ""), 3);
        assert_eq!(levenshtein("config.ts", "confg.ts"), 1);
    }

    #[test]
    fn test_find_spec_files_empty_dir() {
        let tmp = tempfile::tempdir().unwrap();
        let files = find_spec_files(tmp.path());
        assert!(files.is_empty());
    }

    #[test]
    fn test_find_spec_files_nonexistent() {
        let files = find_spec_files(Path::new("/nonexistent/path"));
        assert!(files.is_empty());
    }

    #[test]
    fn test_find_spec_files_with_specs() {
        let tmp = tempfile::tempdir().unwrap();
        let spec_dir = tmp.path().join("auth");
        fs::create_dir_all(&spec_dir).unwrap();
        fs::write(spec_dir.join("auth.spec.md"), "---\nmodule: auth\n---\n").unwrap();
        fs::write(spec_dir.join("not-a-spec.md"), "other").unwrap();

        let files = find_spec_files(tmp.path());
        assert_eq!(files.len(), 1);
        assert!(files[0].ends_with("auth.spec.md"));
    }

    #[test]
    fn test_validate_spec_missing_frontmatter() {
        let tmp = tempfile::tempdir().unwrap();
        let spec = tmp.path().join("bad.spec.md");
        fs::write(&spec, "# No frontmatter\n\nJust text.").unwrap();

        let tables = HashSet::new();
        let schema_cols = HashMap::new();
        let config = SpecSyncConfig::default();
        let result = validate_spec(&spec, tmp.path(), &tables, &schema_cols, &config);
        assert!(!result.errors.is_empty());
        assert!(result.errors[0].contains("frontmatter"));
    }

    #[test]
    fn test_validate_spec_missing_required_fields() {
        let tmp = tempfile::tempdir().unwrap();
        let spec = tmp.path().join("partial.spec.md");
        fs::write(&spec, "---\nmodule: test\n---\n\n## Purpose\nTest\n").unwrap();

        let tables = HashSet::new();
        let schema_cols = HashMap::new();
        let config = SpecSyncConfig::default();
        let result = validate_spec(&spec, tmp.path(), &tables, &schema_cols, &config);
        // Should have errors for missing version, status, files
        assert!(result.errors.iter().any(|e| e.contains("version")));
        assert!(result.errors.iter().any(|e| e.contains("status")));
        assert!(result.errors.iter().any(|e| e.contains("files")));
    }

    #[test]
    fn test_validate_spec_missing_source_file() {
        let tmp = tempfile::tempdir().unwrap();
        let spec = tmp.path().join("missing.spec.md");
        fs::write(
            &spec,
            "---\nmodule: test\nversion: 1\nstatus: active\nfiles:\n  - src/nonexistent.ts\n---\n\n## Purpose\nTest\n## Requirements\n## Public API\n## Invariants\n## Behavioral Examples\n## Error Cases\n## Dependencies\n## Change Log\n",
        )
        .unwrap();

        let tables = HashSet::new();
        let schema_cols = HashMap::new();
        let config = SpecSyncConfig::default();
        let result = validate_spec(&spec, tmp.path(), &tables, &schema_cols, &config);
        assert!(
            result
                .errors
                .iter()
                .any(|e| e.contains("Source file not found"))
        );
    }

    #[test]
    fn test_validate_spec_schema_columns() {
        let tmp = tempfile::tempdir().unwrap();
        let src_dir = tmp.path().join("src");
        fs::create_dir_all(&src_dir).unwrap();
        fs::write(src_dir.join("msg.ts"), "export function send() {}").unwrap();

        let spec = tmp.path().join("msg.spec.md");
        fs::write(
            &spec,
            r#"---
module: msg
version: 1
status: active
files:
  - src/msg.ts
db_tables:
  - messages
---

## Purpose
Messaging

## Requirements

### Schema: messages

| Column | Type | Constraints |
|--------|------|-------------|
| `id` | INTEGER | PRIMARY KEY |
| `content` | TEXT | NOT NULL |
| `ghost_col` | TEXT | NOT NULL |

## Public API

### Exported Functions

| Function | Parameters | Returns | Description |
|----------|-----------|---------|-------------|
| `send` | msg: string | void | Sends |

## Invariants
## Behavioral Examples
## Error Cases
## Dependencies
## Change Log
"#,
        )
        .unwrap();

        let mut table_names = HashSet::new();
        table_names.insert("messages".to_string());

        let mut schema_cols = HashMap::new();
        schema_cols.insert(
            "messages".to_string(),
            SchemaTable {
                columns: vec![
                    crate::schema::SchemaColumn {
                        name: "id".to_string(),
                        col_type: "INTEGER".to_string(),
                        nullable: false,
                        has_default: false,
                        is_primary_key: true,
                    },
                    crate::schema::SchemaColumn {
                        name: "content".to_string(),
                        col_type: "TEXT".to_string(),
                        nullable: false,
                        has_default: false,
                        is_primary_key: false,
                    },
                    crate::schema::SchemaColumn {
                        name: "created_at".to_string(),
                        col_type: "TEXT".to_string(),
                        nullable: false,
                        has_default: true,
                        is_primary_key: false,
                    },
                ],
            },
        );

        let config = SpecSyncConfig::default();
        let result = validate_spec(&spec, tmp.path(), &table_names, &schema_cols, &config);

        // ghost_col is in spec but not in schema → ERROR
        assert!(result.errors.iter().any(|e| e.contains("ghost_col")));
        // created_at is in schema but not in spec → WARNING
        assert!(result.warnings.iter().any(|w| w.contains("created_at")));
    }

    #[test]
    fn test_validate_spec_schema_type_mismatch() {
        let tmp = tempfile::tempdir().unwrap();
        let src_dir = tmp.path().join("src");
        fs::create_dir_all(&src_dir).unwrap();
        fs::write(src_dir.join("t.ts"), "export function f() {}").unwrap();

        let spec = tmp.path().join("t.spec.md");
        fs::write(
            &spec,
            r#"---
module: t
version: 1
status: active
files:
  - src/t.ts
db_tables:
  - items
---

## Purpose
Test

## Requirements

### Schema: items

| Column | Type | Constraints |
|--------|------|-------------|
| `id` | INTEGER | PRIMARY KEY |
| `price` | TEXT | |

## Public API

### Exported Functions

| Function | Parameters | Returns | Description |
|----------|-----------|---------|-------------|
| `f` | | void | Does stuff |

## Invariants
## Behavioral Examples
## Error Cases
## Dependencies
## Change Log
"#,
        )
        .unwrap();

        let mut table_names = HashSet::new();
        table_names.insert("items".to_string());

        let mut schema_cols = HashMap::new();
        schema_cols.insert(
            "items".to_string(),
            SchemaTable {
                columns: vec![
                    crate::schema::SchemaColumn {
                        name: "id".to_string(),
                        col_type: "INTEGER".to_string(),
                        nullable: false,
                        has_default: false,
                        is_primary_key: true,
                    },
                    crate::schema::SchemaColumn {
                        name: "price".to_string(),
                        col_type: "REAL".to_string(),
                        nullable: true,
                        has_default: false,
                        is_primary_key: false,
                    },
                ],
            },
        );

        let config = SpecSyncConfig::default();
        let result = validate_spec(&spec, tmp.path(), &table_names, &schema_cols, &config);

        // price type mismatch: spec says TEXT, schema says REAL → WARNING
        assert!(
            result
                .warnings
                .iter()
                .any(|w| w.contains("type mismatch") && w.contains("price"))
        );
    }
}

// ─── Coverage ────────────────────────────────────────────────────────────

fn collect_specced_files(spec_files: &[PathBuf]) -> HashSet<String> {
    let mut specced = HashSet::new();
    for spec_file in spec_files {
        if let Ok(content) = fs::read_to_string(spec_file) {
            let content = content.replace("\r\n", "\n");
            if let Some(parsed) = parse_frontmatter(&content) {
                for f in &parsed.frontmatter.files {
                    specced.insert(f.clone());
                }
            }
        }
    }
    specced
}

fn get_module_dirs(dir: &Path, exclude_dirs: &HashSet<String>) -> Vec<String> {
    let mut modules = Vec::new();
    if !dir.exists() {
        return modules;
    }

    if let Ok(entries) = fs::read_dir(dir) {
        for entry in entries.flatten() {
            if let Ok(ft) = entry.file_type()
                && ft.is_dir()
            {
                let name = entry.file_name().to_string_lossy().to_string();
                if !exclude_dirs.contains(&name) {
                    modules.push(name);
                }
            }
        }
    }

    modules.sort();
    modules
}

/// Get spec module directories that actually contain a .spec.md file.
/// Empty directories (e.g. from a failed prior generation) are ignored.
fn get_spec_module_dirs(dir: &Path) -> Vec<String> {
    let mut modules = Vec::new();
    if !dir.exists() {
        return modules;
    }

    if let Ok(entries) = fs::read_dir(dir) {
        for entry in entries.flatten() {
            if let Ok(ft) = entry.file_type()
                && ft.is_dir()
            {
                let subdir = entry.path();
                let has_spec = fs::read_dir(&subdir)
                    .ok()
                    .map(|entries| {
                        entries.flatten().any(|e| {
                            e.path().is_file()
                                && e.file_name()
                                    .to_str()
                                    .map(|n| n.ends_with(".spec.md"))
                                    .unwrap_or(false)
                        })
                    })
                    .unwrap_or(false);
                if has_spec {
                    let name = entry.file_name().to_string_lossy().to_string();
                    modules.push(name);
                }
            }
        }
    }

    modules.sort();
    modules
}

/// Compute file and module coverage.
pub fn compute_coverage(
    root: &Path,
    spec_files: &[PathBuf],
    config: &SpecSyncConfig,
) -> CoverageReport {
    let specced_files = collect_specced_files(spec_files);
    let exclude_dirs: HashSet<String> = config.exclude_dirs.iter().cloned().collect();

    let mut all_source_files: Vec<String> = Vec::new();
    for src_dir in &config.source_dirs {
        let full_dir = root.join(src_dir);
        let files: Vec<String> = find_source_files(&full_dir, &exclude_dirs, config)
            .into_iter()
            .filter_map(|f| {
                let rel = f.strip_prefix(root).ok()?;
                let rel_str = rel.to_string_lossy().replace('\\', "/");
                // Check exclude patterns (simple glob matching)
                for pattern in &config.exclude_patterns {
                    // **/dir/** — matches path containing dir
                    if pattern.starts_with("**/") && pattern.ends_with("/**") {
                        let dir_part = &pattern[3..pattern.len() - 3];
                        if rel_str.contains(dir_part) {
                            return None;
                        }
                    }
                    // **/*.ext or **/filename — matches suffix/filename
                    else if let Some(suffix) = pattern.strip_prefix("**/") {
                        if let Some(ext) = suffix.strip_prefix('*') {
                            // **/*.test.ts -> .test.ts
                            if rel_str.ends_with(ext) {
                                return None;
                            }
                        } else {
                            // **/index.ts -> matches any path ending in /index.ts or equal to index.ts
                            if rel_str.ends_with(&format!("/{suffix}")) || rel_str == *suffix {
                                return None;
                            }
                        }
                    }
                    // Literal contains match as fallback
                    else if rel_str.contains(pattern.as_str()) {
                        return None;
                    }
                }
                Some(rel_str)
            })
            .collect();
        all_source_files.extend(files);
    }

    // Count lines of code per file
    let file_loc: std::collections::HashMap<&str, usize> = all_source_files
        .iter()
        .map(|f| {
            let loc = fs::read_to_string(root.join(f))
                .map(|c| c.lines().count())
                .unwrap_or(0);
            (f.as_str(), loc)
        })
        .collect();

    let total_loc: usize = file_loc.values().sum();
    let specced_loc: usize = all_source_files
        .iter()
        .filter(|f| specced_files.contains(*f))
        .map(|f| file_loc.get(f.as_str()).copied().unwrap_or(0))
        .sum();

    let unspecced_files: Vec<String> = all_source_files
        .iter()
        .filter(|f| !specced_files.contains(*f))
        .cloned()
        .collect();

    let mut unspecced_file_loc: Vec<(String, usize)> = unspecced_files
        .iter()
        .map(|f| (f.clone(), file_loc.get(f.as_str()).copied().unwrap_or(0)))
        .collect();
    unspecced_file_loc.sort_by(|a, b| b.1.cmp(&a.1));

    // Module coverage
    let specs_dir = root.join(&config.specs_dir);
    let spec_modules: HashSet<String> = get_spec_module_dirs(&specs_dir).into_iter().collect();

    let mut unspecced_modules = Vec::new();
    let mut seen_modules: HashSet<String> = HashSet::new();

    // User-defined modules from specsync.json take priority
    if !config.modules.is_empty() {
        for name in config.modules.keys() {
            if !spec_modules.contains(name) && seen_modules.insert(name.clone()) {
                unspecced_modules.push(name.clone());
            }
        }
    }

    // Then: detect modules from manifest files (Package.swift, Cargo.toml, etc.)
    let manifest = discover_manifest_modules(root);
    for name in manifest.modules.keys() {
        if !spec_modules.contains(name) && seen_modules.insert(name.clone()) {
            unspecced_modules.push(name.clone());
        }
    }

    // Detect subdirectory-based modules
    for src_dir in &config.source_dirs {
        let full_dir = root.join(src_dir);
        for module in get_module_dirs(&full_dir, &exclude_dirs) {
            if !spec_modules.contains(&module) && seen_modules.insert(module.clone()) {
                unspecced_modules.push(module);
            }
        }
    }

    // Detect flat source files as modules (e.g. src/config.rs → module "config")
    let skip_stems: HashSet<&str> = ["main", "lib", "mod", "index", "__init__", "app"]
        .into_iter()
        .collect();
    for src_dir in &config.source_dirs {
        let full_dir = root.join(src_dir);
        if let Ok(entries) = fs::read_dir(&full_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if !path.is_file()
                    || !has_extension(&path, &config.source_extensions)
                    || is_test_file(&path)
                {
                    continue;
                }
                let stem = match path.file_stem().and_then(|s| s.to_str()) {
                    Some(s) => s.to_string(),
                    None => continue,
                };
                if skip_stems.contains(stem.as_str()) {
                    continue;
                }
                if !spec_modules.contains(&stem) && seen_modules.insert(stem.clone()) {
                    unspecced_modules.push(stem);
                }
            }
        }
    }

    let specced_count = all_source_files.len() - unspecced_files.len();
    let coverage_percent = if all_source_files.is_empty() {
        100
    } else {
        (specced_count * 100) / all_source_files.len()
    };

    let loc_coverage_percent = if total_loc == 0 {
        100
    } else {
        (specced_loc * 100) / total_loc
    };

    CoverageReport {
        total_source_files: all_source_files.len(),
        specced_file_count: specced_count,
        unspecced_files,
        unspecced_modules,
        coverage_percent,
        total_loc,
        specced_loc,
        loc_coverage_percent,
        unspecced_file_loc,
    }
}