specsync 4.2.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
//! GitHub integration for linking specs to issues.
//!
//! Uses the `gh` CLI for authenticated API calls. Falls back to `GITHUB_TOKEN`
//! with `ureq` if `gh` is not available.

use std::path::Path;
use std::process::Command;
use std::time::Duration;

/// A GitHub issue's relevant fields.
#[derive(Debug, Clone)]
pub struct GitHubIssue {
    pub number: u64,
    pub title: String,
    pub state: String, // "open" or "closed"
    #[allow(dead_code)]
    pub labels: Vec<String>,
    pub url: String,
}

/// Result of verifying issue references from spec frontmatter.
#[derive(Debug)]
pub struct IssueVerification {
    #[allow(dead_code)]
    pub spec_path: String,
    pub valid: Vec<GitHubIssue>,
    pub closed: Vec<GitHubIssue>,
    pub not_found: Vec<u64>,
    pub errors: Vec<String>,
}

/// Auto-detect the GitHub repository from git remote origin.
pub fn detect_repo(root: &Path) -> Option<String> {
    let output = Command::new("git")
        .args(["remote", "get-url", "origin"])
        .current_dir(root)
        .output()
        .ok()?;

    if !output.status.success() {
        return None;
    }

    let url = String::from_utf8_lossy(&output.stdout).trim().to_string();
    parse_repo_from_url(&url)
}

/// Parse `owner/repo` from a git remote URL.
fn parse_repo_from_url(url: &str) -> Option<String> {
    // SSH: git@github.com:owner/repo.git
    if let Some(rest) = url.strip_prefix("git@github.com:") {
        let repo = rest.strip_suffix(".git").unwrap_or(rest);
        return Some(repo.to_string());
    }
    // HTTPS: https://github.com/owner/repo.git
    if let Some(rest) = url
        .strip_prefix("https://github.com/")
        .or_else(|| url.strip_prefix("http://github.com/"))
    {
        let repo = rest.strip_suffix(".git").unwrap_or(rest);
        return Some(repo.to_string());
    }
    None
}

/// Resolve the effective repo: explicit config > auto-detect from git.
pub fn resolve_repo(config_repo: Option<&str>, root: &Path) -> Result<String, String> {
    if let Some(repo) = config_repo {
        return Ok(repo.to_string());
    }
    detect_repo(root).ok_or_else(|| {
        "Cannot determine GitHub repo. Set `github.repo` in specsync.json or ensure a git remote is configured.".to_string()
    })
}

/// Check if the `gh` CLI is available and authenticated.
pub fn gh_is_available() -> bool {
    Command::new("gh")
        .args(["auth", "status"])
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Fetch a single issue using `gh` CLI.
pub fn fetch_issue_gh(repo: &str, number: u64) -> Result<GitHubIssue, String> {
    let output = Command::new("gh")
        .args([
            "issue",
            "view",
            &number.to_string(),
            "--repo",
            repo,
            "--json",
            "number,title,state,labels,url",
        ])
        .output()
        .map_err(|e| format!("Failed to run gh: {e}"))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        if stderr.contains("not found") || stderr.contains("Could not resolve") {
            return Err(format!("Issue #{number} not found in {repo}"));
        }
        return Err(format!("gh error: {}", stderr.trim()));
    }

    let json: serde_json::Value = serde_json::from_slice(&output.stdout)
        .map_err(|e| format!("Failed to parse gh output: {e}"))?;

    Ok(GitHubIssue {
        number,
        title: json["title"].as_str().unwrap_or("").to_string(),
        state: json["state"].as_str().unwrap_or("OPEN").to_lowercase(),
        labels: json["labels"]
            .as_array()
            .map(|arr| {
                arr.iter()
                    .filter_map(|l| l["name"].as_str().map(String::from))
                    .collect()
            })
            .unwrap_or_default(),
        url: json["url"].as_str().unwrap_or("").to_string(),
    })
}

/// Fetch a single issue using the GitHub REST API with GITHUB_TOKEN.
pub fn fetch_issue_api(repo: &str, number: u64) -> Result<GitHubIssue, String> {
    let token = std::env::var("GITHUB_TOKEN")
        .map_err(|_| "GITHUB_TOKEN not set and gh CLI not available".to_string())?;

    let url = format!("https://api.github.com/repos/{repo}/issues/{number}");

    let agent = ureq::Agent::new_with_config(
        ureq::config::Config::builder()
            .timeout_global(Some(Duration::from_secs(10)))
            .build(),
    );

    let mut response = agent
        .get(&url)
        .header("Authorization", &format!("Bearer {token}"))
        .header("Accept", "application/vnd.github+json")
        .header("User-Agent", "specsync")
        .call()
        .map_err(|e| format!("GitHub API request failed: {e}"))?;

    if response.status() == 404 {
        return Err(format!("Issue #{number} not found in {repo}"));
    }
    if response.status() != 200 {
        return Err(format!("GitHub API returned HTTP {}", response.status()));
    }

    let body: serde_json::Value = response
        .body_mut()
        .read_json()
        .map_err(|e| format!("Failed to parse GitHub API response: {e}"))?;

    Ok(GitHubIssue {
        number,
        title: body["title"].as_str().unwrap_or("").to_string(),
        state: body["state"].as_str().unwrap_or("open").to_string(),
        labels: body["labels"]
            .as_array()
            .map(|arr| {
                arr.iter()
                    .filter_map(|l| l["name"].as_str().map(String::from))
                    .collect()
            })
            .unwrap_or_default(),
        url: body["html_url"].as_str().unwrap_or("").to_string(),
    })
}

/// Fetch a single issue, trying `gh` CLI first, falling back to API.
pub fn fetch_issue(repo: &str, number: u64) -> Result<GitHubIssue, String> {
    if gh_is_available() {
        fetch_issue_gh(repo, number)
    } else {
        fetch_issue_api(repo, number)
    }
}

/// Verify all issue references from a spec's frontmatter.
pub fn verify_spec_issues(
    repo: &str,
    spec_path: &str,
    implements: &[u64],
    tracks: &[u64],
) -> IssueVerification {
    let mut result = IssueVerification {
        spec_path: spec_path.to_string(),
        valid: Vec::new(),
        closed: Vec::new(),
        not_found: Vec::new(),
        errors: Vec::new(),
    };

    let all_issues: Vec<u64> = implements.iter().chain(tracks.iter()).copied().collect();

    for number in all_issues {
        match fetch_issue(repo, number) {
            Ok(issue) => {
                if issue.state == "closed" {
                    result.closed.push(issue);
                } else {
                    result.valid.push(issue);
                }
            }
            Err(e) => {
                if e.contains("not found") {
                    result.not_found.push(number);
                } else {
                    result.errors.push(format!("#{number}: {e}"));
                }
            }
        }
    }

    result
}

/// List open GitHub issues for a repository.
/// Optionally filter by label. Uses `gh` CLI first, falls back to REST API.
pub fn list_issues(repo: &str, label: Option<&str>) -> Result<Vec<GitHubIssue>, String> {
    if gh_is_available() {
        list_issues_gh(repo, label)
    } else {
        list_issues_api(repo, label)
    }
}

fn list_issues_gh(repo: &str, label: Option<&str>) -> Result<Vec<GitHubIssue>, String> {
    let mut args = vec![
        "issue",
        "list",
        "--repo",
        repo,
        "--state",
        "open",
        "--json",
        "number,title,state,labels,url",
        "--limit",
        "500",
    ];

    let label_owned;
    if let Some(l) = label {
        label_owned = l.to_string();
        args.push("--label");
        args.push(&label_owned);
    }

    let output = Command::new("gh")
        .args(&args)
        .output()
        .map_err(|e| format!("Failed to run gh: {e}"))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(format!("gh error: {}", stderr.trim()));
    }

    let json: serde_json::Value = serde_json::from_slice(&output.stdout)
        .map_err(|e| format!("Failed to parse gh output: {e}"))?;

    let issues = json
        .as_array()
        .ok_or_else(|| "Expected JSON array from gh issue list".to_string())?
        .iter()
        .map(|i| GitHubIssue {
            number: i["number"].as_u64().unwrap_or(0),
            title: i["title"].as_str().unwrap_or("").to_string(),
            state: i["state"].as_str().unwrap_or("OPEN").to_lowercase(),
            labels: i["labels"]
                .as_array()
                .map(|arr| {
                    arr.iter()
                        .filter_map(|l| l["name"].as_str().map(String::from))
                        .collect()
                })
                .unwrap_or_default(),
            url: i["url"].as_str().unwrap_or("").to_string(),
        })
        .collect();

    Ok(issues)
}

fn list_issues_api(repo: &str, label: Option<&str>) -> Result<Vec<GitHubIssue>, String> {
    let token = std::env::var("GITHUB_TOKEN")
        .map_err(|_| "GITHUB_TOKEN not set and gh CLI not available".to_string())?;

    let mut url = format!("https://api.github.com/repos/{repo}/issues?state=open&per_page=100");
    if let Some(l) = label {
        url.push_str(&format!("&labels={}", l));
    }

    let agent = ureq::Agent::new_with_config(
        ureq::config::Config::builder()
            .timeout_global(Some(Duration::from_secs(15)))
            .build(),
    );

    let mut response = agent
        .get(&url)
        .header("Authorization", &format!("Bearer {token}"))
        .header("Accept", "application/vnd.github+json")
        .header("User-Agent", "specsync")
        .call()
        .map_err(|e| format!("GitHub API request failed: {e}"))?;

    if response.status() != 200 {
        return Err(format!("GitHub API returned HTTP {}", response.status()));
    }

    let body: serde_json::Value = response
        .body_mut()
        .read_json()
        .map_err(|e| format!("Failed to parse GitHub API response: {e}"))?;

    let issues = body
        .as_array()
        .ok_or_else(|| "Expected JSON array from GitHub API".to_string())?
        .iter()
        // Skip pull requests (they appear in issues endpoint)
        .filter(|i| i["pull_request"].is_null())
        .map(|i| GitHubIssue {
            number: i["number"].as_u64().unwrap_or(0),
            title: i["title"].as_str().unwrap_or("").to_string(),
            state: i["state"].as_str().unwrap_or("open").to_string(),
            labels: i["labels"]
                .as_array()
                .map(|arr| {
                    arr.iter()
                        .filter_map(|l| l["name"].as_str().map(String::from))
                        .collect()
                })
                .unwrap_or_default(),
            url: i["html_url"].as_str().unwrap_or("").to_string(),
        })
        .collect();

    Ok(issues)
}

/// Create a GitHub issue for spec drift using `gh` CLI.
pub fn create_drift_issue(
    repo: &str,
    spec_path: &str,
    errors: &[String],
    labels: &[String],
) -> Result<GitHubIssue, String> {
    if !gh_is_available() {
        return Err("gh CLI is required to create issues".to_string());
    }

    let title = format!("Spec drift detected: {spec_path}");
    let body = format!(
        "## Spec Drift Detected\n\n\
         **Spec:** `{spec_path}`\n\n\
         ### Validation Errors\n\n{}\n\n\
         ---\n\
         *Auto-created by `specsync check --create-issues`*",
        errors
            .iter()
            .map(|e| format!("- {e}"))
            .collect::<Vec<_>>()
            .join("\n")
    );

    let mut args = vec![
        "issue", "create", "--repo", repo, "--title", &title, "--body", &body,
    ];

    let label_str = labels.join(",");
    if !labels.is_empty() {
        args.push("--label");
        args.push(&label_str);
    }

    let output = Command::new("gh")
        .args(&args)
        .output()
        .map_err(|e| format!("Failed to run gh: {e}"))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(format!("Failed to create issue: {}", stderr.trim()));
    }

    let url = String::from_utf8_lossy(&output.stdout).trim().to_string();
    // Extract issue number from URL (last path segment)
    let number = url
        .rsplit('/')
        .next()
        .and_then(|s| s.parse::<u64>().ok())
        .unwrap_or(0);

    Ok(GitHubIssue {
        number,
        title,
        state: "open".to_string(),
        labels: labels.to_vec(),
        url,
    })
}

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

    #[test]
    fn test_parse_repo_from_url_https() {
        assert_eq!(
            parse_repo_from_url("https://github.com/CorvidLabs/spec-sync.git"),
            Some("CorvidLabs/spec-sync".to_string())
        );
        assert_eq!(
            parse_repo_from_url("https://github.com/CorvidLabs/spec-sync"),
            Some("CorvidLabs/spec-sync".to_string())
        );
    }

    #[test]
    fn test_parse_repo_from_url_ssh() {
        assert_eq!(
            parse_repo_from_url("git@github.com:CorvidLabs/spec-sync.git"),
            Some("CorvidLabs/spec-sync".to_string())
        );
    }

    #[test]
    fn test_parse_repo_from_url_unknown() {
        assert_eq!(parse_repo_from_url("https://gitlab.com/foo/bar.git"), None);
    }
}