specsync 2.2.0

Bidirectional spec-to-code validation — language-agnostic, blazing fast
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
use crate::exports::get_exported_symbols;
use crate::parser::{get_missing_sections, get_spec_symbols, parse_frontmatter};
use crate::types::SpecSyncConfig;
use std::collections::HashSet;
use std::fs;
use std::path::Path;

/// Quality score for a single spec file.
#[derive(Debug)]
pub struct SpecScore {
    pub spec_path: String,
    /// Frontmatter completeness (0-20).
    pub frontmatter_score: u32,
    /// Required sections present (0-20).
    pub sections_score: u32,
    /// API documentation coverage (0-20).
    pub api_score: u32,
    /// Content depth — sections have real content, not just TODOs (0-20).
    pub depth_score: u32,
    /// Freshness — files exist, no stale references (0-20).
    pub freshness_score: u32,
    /// Overall score (0-100).
    pub total: u32,
    /// Letter grade.
    pub grade: &'static str,
    /// Actionable suggestions for improvement.
    pub suggestions: Vec<String>,
}

/// Score a single spec file.
pub fn score_spec(spec_path: &Path, root: &Path, config: &SpecSyncConfig) -> SpecScore {
    let rel_path = spec_path
        .strip_prefix(root)
        .unwrap_or(spec_path)
        .to_string_lossy()
        .to_string();

    let mut score = SpecScore {
        spec_path: rel_path,
        frontmatter_score: 0,
        sections_score: 0,
        api_score: 0,
        depth_score: 0,
        freshness_score: 0,
        total: 0,
        grade: "F",
        suggestions: Vec::new(),
    };

    let content = match fs::read_to_string(spec_path) {
        Ok(c) => c.replace("\r\n", "\n"),
        Err(_) => {
            score.suggestions.push("Cannot read spec file".to_string());
            return score;
        }
    };

    let parsed = match parse_frontmatter(&content) {
        Some(p) => p,
        None => {
            score
                .suggestions
                .push("Add YAML frontmatter with --- delimiters".to_string());
            return score;
        }
    };

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

    // ─── Frontmatter (0-20) ──────────────────────────────────────────
    let mut fm_points = 0u32;
    if fm.module.is_some() {
        fm_points += 5;
    } else {
        score
            .suggestions
            .push("Add `module:` field to frontmatter".to_string());
    }
    if fm.version.is_some() {
        fm_points += 5;
    } else {
        score
            .suggestions
            .push("Add `version:` field to frontmatter".to_string());
    }
    if fm.status.is_some() {
        fm_points += 4;
    } else {
        score
            .suggestions
            .push("Add `status:` field to frontmatter".to_string());
    }
    if !fm.files.is_empty() {
        fm_points += 6;
    } else {
        score
            .suggestions
            .push("Add `files:` list linking spec to source files".to_string());
    }
    score.frontmatter_score = fm_points;

    // ─── Sections (0-20) ─────────────────────────────────────────────
    let missing = get_missing_sections(body, &config.required_sections);
    let present = config.required_sections.len() - missing.len();
    let total_sections = config.required_sections.len();
    score.sections_score = if total_sections == 0 {
        20
    } else {
        ((present as f64 / total_sections as f64) * 20.0).round() as u32
    };
    if !missing.is_empty() {
        let names = missing
            .iter()
            .take(3)
            .cloned()
            .collect::<Vec<_>>()
            .join(", ");
        let suffix = if missing.len() > 3 {
            format!(" (+{} more)", missing.len() - 3)
        } else {
            String::new()
        };
        score
            .suggestions
            .push(format!("Add missing sections: {names}{suffix}"));
    }

    // ─── API Coverage (0-20) ─────────────────────────────────────────
    if !fm.files.is_empty() {
        let mut all_exports: Vec<String> = Vec::new();
        for file in &fm.files {
            let full_path = root.join(file);
            all_exports.extend(get_exported_symbols(&full_path));
        }
        let mut seen = HashSet::new();
        all_exports.retain(|s| seen.insert(s.clone()));

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

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

        if all_exports.is_empty() {
            score.api_score = 20; // No exports to document
        } else {
            score.api_score =
                ((documented as f64 / all_exports.len() as f64) * 20.0).round() as u32;
            let undocumented = all_exports.len() - documented;
            if undocumented > 0 {
                score.suggestions.push(format!(
                    "Document {undocumented} undocumented export(s) in ## Public API"
                ));
            }
        }
    } else {
        score.api_score = 0;
    }

    // ─── Content Depth (0-20) ────────────────────────────────────────
    let mut depth_points = 0u32;
    let todo_count = count_placeholder_todos(body);
    let placeholder_count = body.matches("<!-- ").count();

    // Check each required section has meaningful content
    let sections_with_content = count_sections_with_content(body, &config.required_sections);
    let content_ratio = if config.required_sections.is_empty() {
        1.0
    } else {
        sections_with_content as f64 / config.required_sections.len() as f64
    };
    depth_points += (content_ratio * 14.0).round() as u32;

    // Penalize TODOs
    if todo_count == 0 && placeholder_count == 0 {
        depth_points += 6;
    } else if todo_count <= 2 {
        depth_points += 3;
    } else {
        score.suggestions.push(format!(
            "Fill in {todo_count} TODO placeholder(s) with real content"
        ));
    }
    score.depth_score = depth_points.min(20);

    // ─── Freshness (0-20) ────────────────────────────────────────────
    let mut fresh_points = 20u32;
    let mut stale_files = 0u32;
    for file in &fm.files {
        if !root.join(file).exists() {
            stale_files += 1;
        }
    }
    if stale_files > 0 {
        let penalty = (stale_files * 5).min(15);
        fresh_points = fresh_points.saturating_sub(penalty);
        score.suggestions.push(format!(
            "Fix {stale_files} stale file reference(s) in frontmatter"
        ));
    }

    // Check depends_on references
    let mut stale_deps = 0u32;
    for dep in &fm.depends_on {
        if !root.join(dep).exists() {
            stale_deps += 1;
        }
    }
    if stale_deps > 0 {
        fresh_points = fresh_points.saturating_sub(stale_deps * 3);
        score.suggestions.push(format!(
            "Fix {stale_deps} stale dependency reference(s) in frontmatter"
        ));
    }
    score.freshness_score = fresh_points;

    // ─── Total & Grade ───────────────────────────────────────────────
    score.total = score.frontmatter_score
        + score.sections_score
        + score.api_score
        + score.depth_score
        + score.freshness_score;

    score.grade = match score.total {
        90..=100 => "A",
        80..=89 => "B",
        70..=79 => "C",
        60..=69 => "D",
        _ => "F",
    };

    score
}

/// Count TODO/todo occurrences that are actual placeholders, ignoring:
/// - Occurrences inside fenced code blocks (``` ... ```)
/// - Compound terms like "TODO-marker", "TODO_detection", "TODOs"
/// - Descriptive prose where TODO is used as a concept (e.g., "TODO comments", "detect TODO")
fn count_placeholder_todos(body: &str) -> usize {
    use regex::Regex;

    // Strip fenced code blocks
    let code_block_re = Regex::new(r"(?s)```[^\n]*\n.*?```").unwrap();
    let stripped = code_block_re.replace_all(body, "");

    // Placeholder pattern: line is just "TODO"/"todo", or starts with "TODO:"
    let todo_line_re = Regex::new(r"(?i)^TODO\s*(:.*)?$").unwrap();

    let mut count = 0;
    for line in stripped.lines() {
        let trimmed = line
            .trim()
            .trim_start_matches("- ")
            .trim_start_matches("* ");
        if todo_line_re.is_match(trimmed) {
            count += 1;
        }
    }
    count
}

/// Count how many required sections have meaningful content (more than just a heading).
fn count_sections_with_content(body: &str, required_sections: &[String]) -> usize {
    let mut count = 0;
    for section in required_sections {
        let header = format!("## {section}");
        if let Some(start) = body.find(&header) {
            let after = start + header.len();
            // Find end of this section (next ## or end of body)
            let rest = &body[after..];
            let end = rest.find("\n## ").unwrap_or(rest.len());
            let section_body = rest[..end].trim();

            // Has content beyond placeholders?
            let meaningful = section_body
                .lines()
                .filter(|l| {
                    let t = l.trim();
                    !t.is_empty()
                        && !t.starts_with("<!--")
                        && !t.starts_with("|--")
                        && !t.starts_with("| -")
                        && t != "TODO"
                        && !t.contains("<!-- TODO")
                })
                .count();

            if meaningful >= 1 {
                count += 1;
            }
        }
    }
    count
}

/// Aggregate scores for a project.
pub struct ProjectScore {
    pub spec_scores: Vec<SpecScore>,
    pub average_score: f64,
    pub grade: &'static str,
    pub total_specs: usize,
    pub grade_distribution: [usize; 5], // A, B, C, D, F
}

pub fn compute_project_score(spec_scores: Vec<SpecScore>) -> ProjectScore {
    let total_specs = spec_scores.len();
    let average_score = if total_specs == 0 {
        0.0
    } else {
        spec_scores.iter().map(|s| s.total as f64).sum::<f64>() / total_specs as f64
    };

    let mut distribution = [0usize; 5];
    for s in &spec_scores {
        match s.grade {
            "A" => distribution[0] += 1,
            "B" => distribution[1] += 1,
            "C" => distribution[2] += 1,
            "D" => distribution[3] += 1,
            _ => distribution[4] += 1,
        }
    }

    let grade = match average_score.round() as u32 {
        90..=100 => "A",
        80..=89 => "B",
        70..=79 => "C",
        60..=69 => "D",
        _ => "F",
    };

    ProjectScore {
        spec_scores,
        average_score,
        grade,
        total_specs,
        grade_distribution: distribution,
    }
}

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

    #[test]
    fn test_count_placeholder_todos() {
        let body = "## Purpose\nSomething useful\n\n## Invariants\n- TODO: fill this in\n- TODO\n";
        assert_eq!(count_placeholder_todos(body), 2);
    }

    #[test]
    fn test_count_placeholder_todos_in_code_blocks() {
        let body = "## Purpose\n```\nTODO: this is in a code block\n```\n\nTODO: this is real\n";
        assert_eq!(count_placeholder_todos(body), 1);
    }

    #[test]
    fn test_count_placeholder_todos_zero() {
        let body = "## Purpose\nAll sections filled in with real content.\n";
        assert_eq!(count_placeholder_todos(body), 0);
    }

    #[test]
    fn test_count_sections_with_content() {
        let body =
            "## Purpose\nReal content here\n\n## Public API\n\n## Invariants\n1. Must be valid\n";
        let sections = vec![
            "Purpose".to_string(),
            "Public API".to_string(),
            "Invariants".to_string(),
        ];
        assert_eq!(count_sections_with_content(body, &sections), 2); // Purpose + Invariants
    }

    #[test]
    fn test_count_sections_with_content_empty() {
        let body = "## Purpose\n\n## Public API\n\n";
        let sections = vec!["Purpose".to_string(), "Public API".to_string()];
        assert_eq!(count_sections_with_content(body, &sections), 0);
    }

    #[test]
    fn test_compute_project_score_empty() {
        let project = compute_project_score(vec![]);
        assert_eq!(project.total_specs, 0);
        assert_eq!(project.average_score, 0.0);
        assert_eq!(project.grade, "F");
    }

    #[test]
    fn test_compute_project_score_distribution() {
        let scores = vec![
            SpecScore {
                spec_path: "a".to_string(),
                frontmatter_score: 20,
                sections_score: 20,
                api_score: 20,
                depth_score: 20,
                freshness_score: 15,
                total: 95,
                grade: "A",
                suggestions: vec![],
            },
            SpecScore {
                spec_path: "b".to_string(),
                frontmatter_score: 10,
                sections_score: 10,
                api_score: 10,
                depth_score: 10,
                freshness_score: 10,
                total: 50,
                grade: "F",
                suggestions: vec![],
            },
        ];
        let project = compute_project_score(scores);
        assert_eq!(project.total_specs, 2);
        assert_eq!(project.grade_distribution[0], 1); // 1 A
        assert_eq!(project.grade_distribution[4], 1); // 1 F
        assert!((project.average_score - 72.5).abs() < 0.1);
    }

    #[test]
    fn test_score_spec_complete() {
        let tmp = tempfile::tempdir().unwrap();
        let src_dir = tmp.path().join("src");
        std::fs::create_dir_all(&src_dir).unwrap();
        std::fs::write(
            src_dir.join("auth.ts"),
            "export function createAuth() {}\nexport class AuthService {}\n",
        )
        .unwrap();

        let spec_dir = tmp.path().join("specs").join("auth");
        std::fs::create_dir_all(&spec_dir).unwrap();
        let spec_content = r#"---
module: auth
version: 1
status: active
files:
  - src/auth.ts
db_tables: []
depends_on: []
---

# Auth

## Purpose

The auth module handles authentication.

## Public API

| Export | Description |
|--------|-------------|
| `createAuth` | Creates auth instance |
| `AuthService` | Main auth service class |

## Invariants

1. Tokens must be validated before use

## Behavioral Examples

### Scenario: Valid login

- **Given** valid credentials
- **When** login is called
- **Then** a token is returned

## Error Cases

| Condition | Behavior |
|-----------|----------|
| Invalid token | Returns 401 |

## Dependencies

None.

## Change Log

| Date | Change |
|------|--------|
| 2024-01-01 | Initial |
"#;
        let spec_file = spec_dir.join("auth.spec.md");
        std::fs::write(&spec_file, spec_content).unwrap();

        let config = SpecSyncConfig::default();
        let score = score_spec(&spec_file, tmp.path(), &config);

        assert_eq!(score.frontmatter_score, 20);
        assert!(
            score.total >= 80,
            "Expected high score, got {}",
            score.total
        );
        assert!(score.grade == "A" || score.grade == "B");
    }
}