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
use crate::ai::{self, ResolvedProvider};
use crate::exports::{has_extension, is_test_file};
use crate::types::{CoverageReport, SpecSyncConfig};
use colored::Colorize;
use std::fs;
use std::io::Write;
use std::path::Path;
use walkdir::WalkDir;

const TASKS_TEMPLATE: &str = r#"---
spec: {module}.spec.md
---

## Tasks

- [ ] <!-- Add tasks for this spec -->

## Gaps

<!-- Uncovered areas, missing edge cases, or incomplete coverage -->

## Review Sign-offs

- **Product**: pending
- **QA**: pending
- **Design**: n/a
- **Dev**: pending
"#;

const CONTEXT_TEMPLATE: &str = r#"---
spec: {module}.spec.md
---

## Key Decisions

<!-- Record architectural or design decisions relevant to this spec -->

## Files to Read First

<!-- List the most important files an agent or new developer should read -->

## Current Status

<!-- What's done, what's in progress, what's blocked -->

## Notes

<!-- Free-form notes, links, or context -->
"#;

const DEFAULT_TEMPLATE: &str = r#"---
module: module-name
version: 1
status: draft
files: []
db_tables: []
depends_on: []
---

# Module Name

## Purpose

<!-- TODO: describe what this module does -->

## Public API

### Exported Functions

| Function | Parameters | Returns | Description |
|----------|-----------|---------|-------------|

### Exported Types

| Type | Description |
|------|-------------|

## Invariants

1. <!-- TODO -->

## Behavioral Examples

### Scenario: TODO

- **Given** precondition
- **When** action
- **Then** result

## Error Cases

| Condition | Behavior |
|-----------|----------|

## Dependencies

### Consumes

| Module | What is used |
|--------|-------------|

### Consumed By

| Module | What is used |
|--------|-------------|

## Change Log

| Date | Author | Change |
|------|--------|--------|
"#;

/// Find source files in a module directory.
fn find_module_source_files(dir: &Path, config: &SpecSyncConfig) -> Vec<String> {
    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() && has_extension(path, &config.source_extensions) && !is_test_file(path) {
            results.push(path.to_string_lossy().to_string());
        }
    }

    results
        .into_iter()
        .map(|p| {
            // Get path relative to root (two levels up from module dir)
            p.replace('\\', "/")
        })
        .collect()
}

/// Find source files for a module, checking subdirectories first, then flat files.
fn find_files_for_module(root: &Path, module_name: &str, config: &SpecSyncConfig) -> Vec<String> {
    let mut module_files = Vec::new();

    // First: look for subdirectory-based modules (src/module_name/)
    for src_dir in &config.source_dirs {
        let module_dir = root.join(src_dir).join(module_name);
        let files = find_module_source_files(&module_dir, config);
        module_files.extend(files);
    }

    // Fallback: look for flat files matching the module name (src/module_name.rs, etc.)
    if module_files.is_empty() {
        for src_dir in &config.source_dirs {
            let src_path = root.join(src_dir);
            if let Ok(entries) = std::fs::read_dir(&src_path) {
                for entry in entries.flatten() {
                    let path = entry.path();
                    if !path.is_file()
                        || !has_extension(&path, &config.source_extensions)
                        || is_test_file(&path)
                    {
                        continue;
                    }
                    if let Some(stem) = path.file_stem().and_then(|s| s.to_str())
                        && stem == module_name
                    {
                        module_files.push(path.to_string_lossy().replace('\\', "/"));
                    }
                }
            }
        }
    }

    module_files
}

/// Generate a spec from a template.
fn generate_spec(
    module_name: &str,
    source_files: &[String],
    root: &Path,
    specs_dir: &Path,
) -> String {
    let template_path = specs_dir.join("_template.spec.md");
    let template = if template_path.exists() {
        fs::read_to_string(&template_path).unwrap_or_else(|_| DEFAULT_TEMPLATE.to_string())
    } else {
        DEFAULT_TEMPLATE.to_string()
    };

    let title = module_name
        .split('-')
        .map(|w| {
            let mut chars = w.chars();
            match chars.next() {
                Some(c) => c.to_uppercase().to_string() + chars.as_str(),
                None => String::new(),
            }
        })
        .collect::<Vec<_>>()
        .join(" ");

    // Make paths relative to root
    let files_yaml: String = source_files
        .iter()
        .map(|f| {
            let rel = Path::new(f)
                .strip_prefix(root.to_string_lossy().as_ref())
                .map(|p| p.to_string_lossy().to_string())
                .unwrap_or_else(|_| f.clone());
            format!("  - {rel}")
        })
        .collect::<Vec<_>>()
        .join("\n");

    let mut spec = template;

    // Replace module name
    let module_re = regex::Regex::new(r"(?m)^module:\s*.+$").unwrap();
    spec = module_re
        .replace(&spec, format!("module: {module_name}"))
        .to_string();

    // Replace status
    let status_re = regex::Regex::new(r"(?m)^status:\s*.+$").unwrap();
    spec = status_re.replace(&spec, "status: draft").to_string();

    // Replace version
    let version_re = regex::Regex::new(r"(?m)^version:\s*.+$").unwrap();
    spec = version_re.replace(&spec, "version: 1").to_string();

    // Replace files list (handles both `files: []` and multi-line YAML list)
    let files_re = regex::Regex::new(r"(?m)^files:\s*\[\]|^files:\n(?:\s+-\s+.+\n?)*").unwrap();
    spec = files_re
        .replace(&spec, format!("files:\n{files_yaml}\n"))
        .to_string();

    // Replace title
    let title_re = regex::Regex::new(r"(?m)^# .+$").unwrap();
    spec = title_re.replace(&spec, format!("# {title}")).to_string();

    // Clear db_tables
    let db_re = regex::Regex::new(r"(?m)^db_tables:\n(?:\s+-\s+.+\n?)*").unwrap();
    spec = db_re.replace(&spec, "db_tables: []\n").to_string();

    spec
}

/// Generate spec content for a module, using AI if a provider is configured.
fn generate_module_spec(
    module_name: &str,
    module_files: &[String],
    root: &Path,
    specs_dir: &Path,
    config: &SpecSyncConfig,
    provider: Option<&ResolvedProvider>,
) -> String {
    if let Some(provider) = provider {
        // Make paths relative to root for the AI prompt
        let rel_files: Vec<String> = module_files
            .iter()
            .map(|f| {
                Path::new(f)
                    .strip_prefix(root.to_string_lossy().as_ref())
                    .map(|p| p.to_string_lossy().to_string())
                    .unwrap_or_else(|_| f.clone())
            })
            .collect();

        match ai::generate_spec_with_ai(module_name, &rel_files, root, config, provider) {
            Ok(spec) => return spec,
            Err(e) => {
                eprintln!(
                    "  {} AI generation failed for {module_name}: {e} — falling back to template",
                    "".yellow()
                );
            }
        }
    }

    generate_spec(module_name, module_files, root, specs_dir)
}

/// Generate companion files (tasks.md, context.md) alongside a spec file.
fn generate_companion_files(spec_dir: &Path, module_name: &str) {
    let tasks_path = spec_dir.join("tasks.md");
    let context_path = spec_dir.join("context.md");

    if !tasks_path.exists() {
        let content = TASKS_TEMPLATE.replace("{module}", module_name);
        if fs::write(&tasks_path, &content).is_ok() {
            println!("    {} Generated tasks.md", "".green());
        }
    }

    if !context_path.exists() {
        let content = CONTEXT_TEMPLATE.replace("{module}", module_name);
        if fs::write(&context_path, &content).is_ok() {
            println!("    {} Generated context.md", "".green());
        }
    }
}

/// Generate companion files for a given spec, creating the directory if needed.
/// Used by the `add-spec` command.
pub fn generate_companion_files_for_spec(spec_dir: &Path, module_name: &str) {
    generate_companion_files(spec_dir, module_name);
}

/// Generate spec files for all unspecced modules.
/// Returns the number of specs generated.
pub fn generate_specs_for_unspecced_modules(
    root: &Path,
    report: &CoverageReport,
    config: &SpecSyncConfig,
    provider: Option<&ResolvedProvider>,
) -> usize {
    let specs_dir = root.join(&config.specs_dir);
    let mut generated = 0;

    for module_name in &report.unspecced_modules {
        let spec_dir = specs_dir.join(module_name);
        let spec_file = spec_dir.join(format!("{module_name}.spec.md"));

        if spec_file.exists() {
            continue;
        }

        let module_files = find_files_for_module(root, module_name, config);

        if module_files.is_empty() {
            continue;
        }

        if let Err(e) = fs::create_dir_all(&spec_dir) {
            eprintln!("  Failed to create {}: {e}", spec_dir.display());
            continue;
        }

        if provider.is_some() {
            let rel = spec_file.strip_prefix(root).unwrap_or(&spec_file).display();
            eprintln!("  Generating {rel} with AI...");
        }

        let spec_content = generate_module_spec(
            module_name,
            &module_files,
            root,
            &specs_dir,
            config,
            provider,
        );

        match fs::write(&spec_file, &spec_content) {
            Ok(_) => {
                let rel = spec_file.strip_prefix(root).unwrap_or(&spec_file).display();
                println!(
                    "  {} Generated {rel} ({} files)",
                    "".green(),
                    module_files.len()
                );
                generate_companion_files(&spec_dir, module_name);
                let _ = std::io::stdout().flush();
                generated += 1;
            }
            Err(e) => {
                eprintln!("  Failed to write {}: {e}", spec_file.display());
            }
        }
    }

    generated
}

/// Generate spec files for all unspecced modules, returning the paths of generated files.
pub fn generate_specs_for_unspecced_modules_paths(
    root: &Path,
    report: &CoverageReport,
    config: &SpecSyncConfig,
    provider: Option<&ResolvedProvider>,
) -> Vec<String> {
    let specs_dir = root.join(&config.specs_dir);
    let mut generated_paths = Vec::new();

    for module_name in &report.unspecced_modules {
        let spec_dir = specs_dir.join(module_name);
        let spec_file = spec_dir.join(format!("{module_name}.spec.md"));

        if spec_file.exists() {
            continue;
        }

        let module_files = find_files_for_module(root, module_name, config);

        if module_files.is_empty() {
            continue;
        }

        if fs::create_dir_all(&spec_dir).is_err() {
            continue;
        }

        let spec_content = generate_module_spec(
            module_name,
            &module_files,
            root,
            &specs_dir,
            config,
            provider,
        );

        if fs::write(&spec_file, &spec_content).is_ok() {
            let rel = spec_file
                .strip_prefix(root)
                .unwrap_or(&spec_file)
                .to_string_lossy()
                .to_string();
            generated_paths.push(rel);
        }
    }

    generated_paths
}