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
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
use clap::ValueEnum;
use serde::Deserialize;
use std::fmt;

/// Supported AI provider presets.
#[derive(Debug, Clone, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum AiProvider {
    Claude,
    Cursor,
    Copilot,
    Ollama,
    /// Direct Anthropic API (no CLI needed — uses ANTHROPIC_API_KEY).
    Anthropic,
    /// Direct OpenAI-compatible API (no CLI needed — uses OPENAI_API_KEY).
    #[serde(alias = "openai")]
    OpenAi,
    Custom,
}

impl AiProvider {
    /// The CLI command for this provider (if it has one).
    #[allow(dead_code)]
    pub fn default_command(&self) -> Option<&'static str> {
        match self {
            AiProvider::Claude => Some("claude -p --output-format text"),
            AiProvider::Ollama => Some("ollama run llama3"),
            AiProvider::Copilot => Some("gh copilot suggest -t shell"),
            AiProvider::Cursor
            | AiProvider::Custom
            | AiProvider::Anthropic
            | AiProvider::OpenAi => None,
        }
    }

    /// The binary name to check for availability (empty for API-only providers).
    pub fn binary_name(&self) -> &'static str {
        match self {
            AiProvider::Claude => "claude",
            AiProvider::Cursor => "cursor",
            AiProvider::Copilot => "gh",
            AiProvider::Ollama => "ollama",
            AiProvider::Anthropic | AiProvider::OpenAi | AiProvider::Custom => "",
        }
    }

    /// Whether this provider uses a direct API call (no CLI binary needed).
    pub fn is_api_provider(&self) -> bool {
        matches!(self, AiProvider::Anthropic | AiProvider::OpenAi)
    }

    /// The environment variable name for the API key.
    pub fn api_key_env_var(&self) -> Option<&'static str> {
        match self {
            AiProvider::Anthropic => Some("ANTHROPIC_API_KEY"),
            AiProvider::OpenAi => Some("OPENAI_API_KEY"),
            _ => None,
        }
    }

    /// Default model for API providers.
    pub fn default_model(&self) -> Option<&'static str> {
        match self {
            AiProvider::Anthropic => Some("claude-sonnet-4-20250514"),
            AiProvider::OpenAi => Some("gpt-4o"),
            _ => None,
        }
    }

    /// Parse a provider name from a string (for CLI flag).
    pub fn from_str_loose(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "claude" => Some(AiProvider::Claude),
            "cursor" => Some(AiProvider::Cursor),
            "copilot" | "gh-copilot" => Some(AiProvider::Copilot),
            "ollama" => Some(AiProvider::Ollama),
            "anthropic" | "anthropic-api" => Some(AiProvider::Anthropic),
            "openai" | "openai-api" => Some(AiProvider::OpenAi),
            _ => None,
        }
    }

    /// All providers that can be auto-detected, in preference order.
    /// CLI providers first, then API providers (checked via env vars).
    pub fn detection_order() -> &'static [AiProvider] {
        &[
            AiProvider::Claude,
            AiProvider::Ollama,
            AiProvider::Copilot,
            AiProvider::Anthropic,
            AiProvider::OpenAi,
        ]
    }
}

impl fmt::Display for AiProvider {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AiProvider::Claude => write!(f, "claude"),
            AiProvider::Cursor => write!(f, "cursor"),
            AiProvider::Copilot => write!(f, "copilot"),
            AiProvider::Ollama => write!(f, "ollama"),
            AiProvider::Anthropic => write!(f, "anthropic"),
            AiProvider::OpenAi => write!(f, "openai"),
            AiProvider::Custom => write!(f, "custom"),
        }
    }
}

/// Output format for CLI commands.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum, Default)]
pub enum OutputFormat {
    /// Colored terminal output (default)
    #[default]
    Text,
    /// Machine-readable JSON
    Json,
    /// Markdown suitable for PR comments and agent consumption
    Markdown,
}

/// Valid spec lifecycle statuses.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpecStatus {
    Draft,
    Active,
    Stable,
    Deprecated,
}

impl SpecStatus {
    /// Parse a status string (case-insensitive).
    pub fn from_str_loose(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "draft" => Some(Self::Draft),
            "active" => Some(Self::Active),
            "stable" => Some(Self::Stable),
            "deprecated" => Some(Self::Deprecated),
            _ => None,
        }
    }

    #[allow(dead_code)]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Draft => "draft",
            Self::Active => "active",
            Self::Stable => "stable",
            Self::Deprecated => "deprecated",
        }
    }
}

/// YAML frontmatter parsed from a spec file.
#[derive(Debug, Default, Clone)]
pub struct Frontmatter {
    pub module: Option<String>,
    pub version: Option<String>,
    pub status: Option<String>,
    pub files: Vec<String>,
    pub db_tables: Vec<String>,
    pub depends_on: Vec<String>,
    pub agent_policy: Option<String>,
    /// GitHub issue numbers this spec implements (e.g., `[42, 57]`).
    pub implements: Vec<u64>,
    /// GitHub issue numbers for ongoing/epic-style tracking.
    pub tracks: Vec<u64>,
}

impl Frontmatter {
    /// Parse the status field into a typed enum.
    pub fn parsed_status(&self) -> Option<SpecStatus> {
        self.status.as_deref().and_then(SpecStatus::from_str_loose)
    }
}

/// Result of validating a single spec.
#[derive(Debug)]
pub struct ValidationResult {
    pub spec_path: String,
    pub errors: Vec<String>,
    pub warnings: Vec<String>,
    pub export_summary: Option<String>,
    /// Actionable fix suggestions mapped to errors.
    pub fixes: Vec<String>,
}

impl ValidationResult {
    pub fn new(spec_path: String) -> Self {
        Self {
            spec_path,
            errors: Vec::new(),
            warnings: Vec::new(),
            export_summary: None,
            fixes: Vec::new(),
        }
    }
}

/// Coverage report for the project.
#[derive(Debug)]
pub struct CoverageReport {
    pub total_source_files: usize,
    pub specced_file_count: usize,
    pub unspecced_files: Vec<String>,
    pub unspecced_modules: Vec<String>,
    pub coverage_percent: usize,
    pub total_loc: usize,
    pub specced_loc: usize,
    pub loc_coverage_percent: usize,
    /// (file_path, line_count) sorted by LOC descending.
    pub unspecced_file_loc: Vec<(String, usize)>,
}

/// Controls export extraction granularity.
/// - `type`: Only top-level type declarations (class, struct, enum, protocol, trait, etc.)
/// - `member`: Every public symbol including members (functions, properties, etc.)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum ExportLevel {
    /// Only top-level type declarations (class, struct, enum, protocol, trait, etc.)
    Type,
    /// Every public symbol including members (default for backwards compatibility).
    #[default]
    Member,
}

/// User-provided configuration (from specsync.json).
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SpecSyncConfig {
    #[serde(default = "default_specs_dir")]
    pub specs_dir: String,

    #[serde(default = "default_source_dirs")]
    pub source_dirs: Vec<String>,

    pub schema_dir: Option<String>,
    pub schema_pattern: Option<String>,

    #[serde(default = "default_required_sections")]
    pub required_sections: Vec<String>,

    #[serde(default = "default_exclude_dirs")]
    pub exclude_dirs: Vec<String>,

    #[serde(default = "default_exclude_patterns")]
    pub exclude_patterns: Vec<String>,

    /// Source file extensions to scan (default: all supported languages).
    #[serde(default)]
    pub source_extensions: Vec<String>,

    /// Export granularity: "type" (top-level types only) or "member" (all public symbols).
    /// Default: "member" for backwards compatibility.
    #[serde(default)]
    pub export_level: ExportLevel,

    /// Module definitions — override auto-detected modules with explicit groupings.
    /// Keys are module names, values are objects with `files` and optional `depends_on`.
    #[serde(default)]
    pub modules: std::collections::HashMap<String, ModuleDefinition>,

    /// AI provider preset: "claude", "cursor", "copilot", "ollama".
    /// Resolves to the correct CLI command automatically.
    #[serde(default)]
    pub ai_provider: Option<AiProvider>,

    /// Model name for the AI provider (e.g. "llama3" for ollama).
    #[serde(default)]
    pub ai_model: Option<String>,

    /// Command to run for AI-powered spec generation (overrides aiProvider).
    /// The prompt is piped to stdin; spec markdown is expected on stdout.
    /// Examples: "claude -p --output-format text", "ollama run llama3"
    #[serde(default)]
    pub ai_command: Option<String>,

    /// API key for direct API providers (anthropic, openai).
    /// Can also be set via ANTHROPIC_API_KEY or OPENAI_API_KEY env vars.
    #[serde(default)]
    pub ai_api_key: Option<String>,

    /// Base URL override for OpenAI-compatible APIs (e.g. local proxies).
    #[serde(default)]
    pub ai_base_url: Option<String>,

    /// Timeout in seconds for each AI command invocation (default: 120).
    #[serde(default)]
    pub ai_timeout: Option<u64>,

    /// Custom validation rules for project-specific lint checks.
    #[serde(default)]
    pub rules: ValidationRules,

    /// Auto-archive completed tasks older than this many days.
    #[serde(default)]
    pub task_archive_days: Option<u32>,

    /// GitHub integration settings for linking specs to issues.
    #[serde(default)]
    pub github: Option<GitHubConfig>,
}

/// GitHub integration configuration for linking specs to issues.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GitHubConfig {
    /// Repository in `owner/repo` format (auto-detected from git remote if omitted).
    #[serde(default)]
    pub repo: Option<String>,
    /// Labels to apply when creating drift issues (default: `["spec-drift"]`).
    #[serde(default = "default_drift_labels")]
    pub drift_labels: Vec<String>,
    /// Whether to verify linked issues exist during `specsync check`.
    #[serde(default = "default_true")]
    pub verify_issues: bool,
}

/// Custom validation rules configurable per-project.
#[derive(Debug, Default, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ValidationRules {
    /// Warn if a spec's Change Log has more entries than this.
    #[serde(default)]
    pub max_changelog_entries: Option<usize>,
    /// Require at least one Behavioral Example scenario.
    #[serde(default)]
    pub require_behavioral_examples: Option<bool>,
    /// Minimum number of invariants required.
    #[serde(default)]
    pub min_invariants: Option<usize>,
    /// Warn if spec file exceeds this size in KB.
    #[serde(default)]
    pub max_spec_size_kb: Option<usize>,
    /// Require non-empty depends_on in frontmatter.
    #[serde(default)]
    pub require_depends_on: Option<bool>,
}

/// A user-defined module grouping in specsync.json.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(dead_code)]
pub struct ModuleDefinition {
    /// Source files belonging to this module (relative to project root).
    #[serde(default)]
    pub files: Vec<String>,
    /// Other module names this module depends on.
    #[serde(default)]
    pub depends_on: Vec<String>,
}

/// Registry entry mapping module names to spec file paths.
/// Used in `specsync-registry.toml` for cross-project resolution.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct RegistryEntry {
    pub name: String,
    pub specs: Vec<(String, String)>, // (module_name, spec_path)
}

/// Detected language for export extraction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Language {
    TypeScript,
    Rust,
    Go,
    Python,
    Swift,
    Kotlin,
    Java,
    CSharp,
    Dart,
    Php,
    Ruby,
}

impl Language {
    /// Detect language from file extension.
    pub fn from_extension(ext: &str) -> Option<Self> {
        match ext {
            "ts" | "tsx" | "js" | "jsx" | "mts" | "cts" => Some(Language::TypeScript),
            "rs" => Some(Language::Rust),
            "go" => Some(Language::Go),
            "py" => Some(Language::Python),
            "swift" => Some(Language::Swift),
            "kt" | "kts" => Some(Language::Kotlin),
            "java" => Some(Language::Java),
            "cs" => Some(Language::CSharp),
            "dart" => Some(Language::Dart),
            "php" => Some(Language::Php),
            "rb" => Some(Language::Ruby),
            _ => None,
        }
    }

    /// Default source file extensions for this language.
    #[allow(dead_code)]
    pub fn extensions(&self) -> &[&str] {
        match self {
            Language::TypeScript => &["ts", "tsx", "js", "jsx", "mts", "cts"],
            Language::Rust => &["rs"],
            Language::Go => &["go"],
            Language::Python => &["py"],
            Language::Swift => &["swift"],
            Language::Kotlin => &["kt", "kts"],
            Language::Java => &["java"],
            Language::CSharp => &["cs"],
            Language::Dart => &["dart"],
            Language::Php => &["php"],
            Language::Ruby => &["rb"],
        }
    }

    /// File patterns to exclude (test files, etc.).
    pub fn test_patterns(&self) -> &[&str] {
        match self {
            Language::TypeScript => &[".test.ts", ".spec.ts", ".test.tsx", ".spec.tsx", ".d.ts"],
            Language::Rust => &[], // Rust tests are inline, not separate files
            Language::Go => &["_test.go"],
            Language::Python => &["test_", "_test.py"],
            Language::Swift => &[
                "Tests.swift",
                "Test.swift",
                "Spec.swift",
                "Specs.swift",
                "Mock.swift",
                "Mocks.swift",
                "Stub.swift",
                "Fake.swift",
            ],
            Language::Kotlin => &[
                "Test.kt", "Tests.kt", "Spec.kt", "Specs.kt", "Mock.kt", "Fake.kt",
            ],
            Language::Java => &[
                "Test.java",
                "Tests.java",
                "Spec.java",
                "Mock.java",
                "IT.java",
            ],
            Language::CSharp => &["Tests.cs", "Test.cs", "Spec.cs", "Mock.cs"],
            Language::Dart => &["_test.dart"],
            Language::Php => &["Test.php", "test_"],
            Language::Ruby => &["_spec.rb", "_test.rb", "test_"],
        }
    }
}

// Default value functions for serde

fn default_specs_dir() -> String {
    "specs".to_string()
}

fn default_source_dirs() -> Vec<String> {
    vec!["src".to_string()]
}

fn default_required_sections() -> Vec<String> {
    vec![
        "Purpose".to_string(),
        "Public API".to_string(),
        "Invariants".to_string(),
        "Behavioral Examples".to_string(),
        "Error Cases".to_string(),
        "Dependencies".to_string(),
        "Change Log".to_string(),
    ]
}

fn default_exclude_dirs() -> Vec<String> {
    vec!["__tests__".to_string()]
}

fn default_exclude_patterns() -> Vec<String> {
    vec![
        "**/__tests__/**".to_string(),
        "**/*.test.ts".to_string(),
        "**/*.spec.ts".to_string(),
    ]
}

fn default_drift_labels() -> Vec<String> {
    vec!["spec-drift".to_string()]
}

fn default_true() -> bool {
    true
}

impl Default for SpecSyncConfig {
    fn default() -> Self {
        Self {
            specs_dir: default_specs_dir(),
            source_dirs: default_source_dirs(),
            schema_dir: None,
            schema_pattern: None,
            required_sections: default_required_sections(),
            exclude_dirs: default_exclude_dirs(),
            exclude_patterns: default_exclude_patterns(),
            source_extensions: Vec::new(),
            export_level: ExportLevel::default(),
            modules: std::collections::HashMap::new(),
            ai_provider: None,
            ai_model: None,
            ai_command: None,
            ai_api_key: None,
            ai_base_url: None,
            ai_timeout: None,
            rules: ValidationRules::default(),
            task_archive_days: None,
            github: None,
        }
    }
}