specsync 3.3.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
use crate::exports::has_extension;
use crate::manifest;
use crate::types::SpecSyncConfig;
use std::collections::HashSet;
use std::fs;
use std::path::Path;
use walkdir::WalkDir;

/// Directories that should never be treated as source directories.
const IGNORED_DIRS: &[&str] = &[
    "node_modules",
    ".git",
    ".hg",
    ".svn",
    "dist",
    "build",
    "out",
    "target",
    "vendor",
    ".next",
    ".nuxt",
    ".output",
    ".cache",
    ".turbo",
    "coverage",
    "__pycache__",
    ".mypy_cache",
    ".pytest_cache",
    ".tox",
    ".venv",
    "venv",
    "env",
    ".env",
    ".idea",
    ".vscode",
    ".DS_Store",
    "specs",
    "docs",
    "doc",
    ".github",
    ".gitlab",
    "migrations",
    "Pods",
    ".dart_tool",
    ".gradle",
    "bin",
    "obj",
];

/// Auto-detect source directories by first checking manifest files
/// (Cargo.toml, Package.swift, build.gradle.kts, package.json, etc.),
/// then falling back to scanning the project root for files with supported
/// language extensions. Returns directories relative to root.
pub fn detect_source_dirs(root: &Path) -> Vec<String> {
    // Try manifest-aware detection first
    let manifest_discovery = manifest::discover_from_manifests(root);
    if !manifest_discovery.source_dirs.is_empty() {
        let mut dirs = manifest_discovery.source_dirs;
        dirs.sort();
        dirs.dedup();
        return dirs;
    }

    // Fall back to directory scanning
    detect_source_dirs_by_scan(root)
}

/// Discover modules from manifest files (Package.swift, Cargo.toml, etc.).
/// Returns the manifest discovery result for use in module detection.
pub fn discover_manifest_modules(root: &Path) -> manifest::ManifestDiscovery {
    manifest::discover_from_manifests(root)
}

/// Scan-based source directory detection (fallback when no manifests found).
fn detect_source_dirs_by_scan(root: &Path) -> Vec<String> {
    let ignored: HashSet<&str> = IGNORED_DIRS.iter().copied().collect();
    let mut source_dirs: Vec<String> = Vec::new();
    let mut has_root_source_files = false;

    // Check immediate children of root
    let entries = match fs::read_dir(root) {
        Ok(e) => e,
        Err(_) => return vec!["src".to_string()],
    };

    for entry in entries.flatten() {
        let name = entry.file_name().to_string_lossy().to_string();

        // Skip hidden dirs and ignored dirs
        if name.starts_with('.') || ignored.contains(name.as_str()) {
            continue;
        }

        let path = entry.path();

        if path.is_dir() {
            // Check if this directory contains any source files (scan up to 3 levels deep)
            if dir_contains_source_files(&path, &ignored, 3) {
                source_dirs.push(name);
            }
        } else if path.is_file() && has_extension(&path, &[]) {
            // Source file directly in root
            has_root_source_files = true;
        }
    }

    // If source files exist directly in root, add "." as a source dir
    if has_root_source_files && source_dirs.is_empty() {
        return vec![".".to_string()];
    }

    if source_dirs.is_empty() {
        // Fallback to "src" if nothing detected
        return vec!["src".to_string()];
    }

    source_dirs.sort();
    source_dirs
}

/// Check if a directory contains source files, scanning up to `max_depth` levels.
fn dir_contains_source_files(dir: &Path, ignored: &HashSet<&str>, max_depth: usize) -> bool {
    for entry in WalkDir::new(dir)
        .max_depth(max_depth)
        .into_iter()
        .filter_entry(|e| {
            if e.file_type().is_dir() {
                let name = e.file_name().to_str().unwrap_or("");
                !name.starts_with('.') && !ignored.contains(name)
            } else {
                true
            }
        })
        .filter_map(|e| e.ok())
    {
        let path = entry.path();
        if path.is_file() && has_extension(path, &[]) {
            return true;
        }
    }
    false
}

/// Load config from specsync.json or .specsync.toml, falling back to defaults.
/// When no config file exists, auto-detects source directories.
///
/// Config file search order:
/// 1. `specsync.json` (JSON format)
/// 2. `.specsync.toml` (TOML format)
pub fn load_config(root: &Path) -> SpecSyncConfig {
    let json_path = root.join("specsync.json");
    let toml_path = root.join(".specsync.toml");

    if json_path.exists() {
        return load_json_config(&json_path, root);
    }

    if toml_path.exists() {
        return load_toml_config(&toml_path, root);
    }

    SpecSyncConfig {
        source_dirs: detect_source_dirs(root),
        ..Default::default()
    }
}

/// Known config keys in specsync.json (camelCase).
const KNOWN_JSON_KEYS: &[&str] = &[
    "specsDir",
    "sourceDirs",
    "schemaDir",
    "schemaPattern",
    "requiredSections",
    "excludeDirs",
    "excludePatterns",
    "sourceExtensions",
    "exportLevel",
    "modules",
    "aiProvider",
    "aiModel",
    "aiCommand",
    "aiApiKey",
    "aiBaseUrl",
    "aiTimeout",
    "rules",
    "taskArchiveDays",
    "github",
];

fn load_json_config(config_path: &Path, root: &Path) -> SpecSyncConfig {
    let content = match fs::read_to_string(config_path) {
        Ok(c) => c,
        Err(_) => return SpecSyncConfig::default(),
    };

    // Warn about unknown keys
    if let Ok(raw) = serde_json::from_str::<serde_json::Value>(&content)
        && let Some(obj) = raw.as_object()
    {
        for key in obj.keys() {
            if !KNOWN_JSON_KEYS.contains(&key.as_str()) {
                eprintln!("Warning: unknown key \"{key}\" in specsync.json (ignored)");
            }
        }
    }

    match serde_json::from_str::<SpecSyncConfig>(&content) {
        Ok(config) => {
            if !content.contains("\"sourceDirs\"") {
                let mut config = config;
                config.source_dirs = detect_source_dirs(root);
                return config;
            }
            config
        }
        Err(e) => {
            eprintln!("Warning: failed to parse specsync.json: {e}");
            SpecSyncConfig::default()
        }
    }
}

/// Parse a TOML config file using zero-dependency parsing.
/// Supports the same fields as specsync.json but with TOML syntax:
///
/// ```toml
/// specs_dir = "specs"
/// source_dirs = ["src", "lib"]
/// schema_dir = "db/migrations"
/// exclude_dirs = ["__tests__"]
/// exclude_patterns = ["**/*.test.ts"]
/// ai_provider = "claude"
/// ai_model = "claude-sonnet-4-20250514"
/// ai_timeout = 120
/// required_sections = ["Purpose", "Public API"]
/// ```
fn load_toml_config(config_path: &Path, root: &Path) -> SpecSyncConfig {
    let content = match fs::read_to_string(config_path) {
        Ok(c) => c,
        Err(_) => return SpecSyncConfig::default(),
    };

    let mut config = SpecSyncConfig::default();
    let mut has_source_dirs = false;
    let mut current_section: Option<String> = None;

    for line in content.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }

        // Track TOML section headers like [rules]
        if line.starts_with('[') && line.ends_with(']') {
            current_section = Some(line[1..line.len() - 1].trim().to_string());
            continue;
        }

        if let Some(eq_pos) = line.find('=') {
            let key = line[..eq_pos].trim();
            let value = line[eq_pos + 1..].trim();

            // Route to section-specific parsing
            if let Some(ref section) = current_section {
                match section.as_str() {
                    "rules" => {
                        parse_toml_rules_key(key, value, &mut config.rules);
                        continue;
                    }
                    "github" => {
                        parse_toml_github_key(key, value, &mut config);
                        continue;
                    }
                    _ => {
                        // Unknown section — skip silently
                        continue;
                    }
                }
            }

            match key {
                "specs_dir" => config.specs_dir = parse_toml_string(value),
                "source_dirs" => {
                    config.source_dirs = parse_toml_string_array(value);
                    has_source_dirs = true;
                }
                "schema_dir" => config.schema_dir = Some(parse_toml_string(value)),
                "schema_pattern" => config.schema_pattern = Some(parse_toml_string(value)),
                "exclude_dirs" => config.exclude_dirs = parse_toml_string_array(value),
                "exclude_patterns" => config.exclude_patterns = parse_toml_string_array(value),
                "source_extensions" => config.source_extensions = parse_toml_string_array(value),
                "ai_provider" => {
                    let s = parse_toml_string(value);
                    config.ai_provider = crate::types::AiProvider::from_str_loose(&s);
                }
                "ai_model" => config.ai_model = Some(parse_toml_string(value)),
                "ai_command" => config.ai_command = Some(parse_toml_string(value)),
                "ai_api_key" => config.ai_api_key = Some(parse_toml_string(value)),
                "ai_base_url" => config.ai_base_url = Some(parse_toml_string(value)),
                "ai_timeout" => {
                    if let Ok(n) = value.trim().parse::<u64>() {
                        config.ai_timeout = Some(n);
                    }
                }
                "export_level" => {
                    let s = parse_toml_string(value);
                    match s.as_str() {
                        "type" => {
                            config.export_level = crate::types::ExportLevel::Type;
                        }
                        "member" => {
                            config.export_level = crate::types::ExportLevel::Member;
                        }
                        _ => eprintln!(
                            "Warning: unknown export_level \"{s}\" (expected \"type\" or \"member\")"
                        ),
                    }
                }
                "required_sections" => {
                    config.required_sections = parse_toml_string_array(value);
                }
                "task_archive_days" => {
                    if let Ok(n) = value.trim().parse::<u32>() {
                        config.task_archive_days = Some(n);
                    }
                }
                _ => {
                    eprintln!("Warning: unknown key \"{key}\" in .specsync.toml (ignored)");
                }
            }
        }
    }

    if !has_source_dirs {
        config.source_dirs = detect_source_dirs(root);
    }

    config
}

/// Parse a TOML string value: `"value"` -> `value`
fn parse_toml_string(s: &str) -> String {
    let s = s.trim();
    if s.starts_with('"') && s.ends_with('"') && s.len() >= 2 {
        s[1..s.len() - 1].to_string()
    } else {
        s.to_string()
    }
}

/// Parse a TOML array of strings: `["a", "b"]` -> vec!["a", "b"]
fn parse_toml_string_array(s: &str) -> Vec<String> {
    let s = s.trim();
    if !s.starts_with('[') || !s.ends_with(']') {
        return vec![parse_toml_string(s)];
    }
    let inner = &s[1..s.len() - 1];
    inner
        .split(',')
        .map(|item| parse_toml_string(item.trim()))
        .filter(|item| !item.is_empty())
        .collect()
}

/// Parse a key=value pair inside a `[rules]` TOML section.
fn parse_toml_rules_key(key: &str, value: &str, rules: &mut crate::types::ValidationRules) {
    match key {
        "max_changelog_entries" => {
            if let Ok(n) = value.trim().parse::<usize>() {
                rules.max_changelog_entries = Some(n);
            }
        }
        "require_behavioral_examples" => {
            rules.require_behavioral_examples = Some(parse_toml_bool(value));
        }
        "min_invariants" => {
            if let Ok(n) = value.trim().parse::<usize>() {
                rules.min_invariants = Some(n);
            }
        }
        "max_spec_size_kb" => {
            if let Ok(n) = value.trim().parse::<usize>() {
                rules.max_spec_size_kb = Some(n);
            }
        }
        "require_depends_on" => {
            rules.require_depends_on = Some(parse_toml_bool(value));
        }
        _ => {
            eprintln!("Warning: unknown rule \"{key}\" in [rules] section (ignored)");
        }
    }
}

/// Parse a key=value pair inside a `[github]` TOML section.
fn parse_toml_github_key(key: &str, value: &str, config: &mut SpecSyncConfig) {
    let gh = config
        .github
        .get_or_insert_with(|| crate::types::GitHubConfig {
            repo: None,
            drift_labels: vec!["spec-drift".to_string()],
            verify_issues: true,
        });

    match key {
        "repo" => gh.repo = Some(parse_toml_string(value)),
        "drift_labels" => gh.drift_labels = parse_toml_string_array(value),
        "verify_issues" => gh.verify_issues = parse_toml_bool(value),
        _ => {
            eprintln!("Warning: unknown key \"{key}\" in [github] section (ignored)");
        }
    }
}

/// Parse a TOML boolean value.
fn parse_toml_bool(s: &str) -> bool {
    matches!(s.trim(), "true" | "yes" | "1")
}

/// Default schema pattern for SQL table extraction.
pub fn default_schema_pattern() -> &'static str {
    r"CREATE (?:VIRTUAL )?TABLE(?:\s+IF NOT EXISTS)?\s+(\w+)"
}