specsync 3.1.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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
use colored::Colorize;
use std::fs;
use std::path::Path;

// ─── Agent instruction templates ─────────────────────────────────────────────

const CLAUDE_MD_SNIPPET: &str = r#"# Spec-Sync Integration

This project uses [spec-sync](https://github.com/CorvidLabs/spec-sync) for bidirectional spec-to-code validation.

## Before modifying any module

1. Read the relevant spec in `specs/<module>/<module>.spec.md`
2. Check companion files: `specs/<module>/tasks.md` and `specs/<module>/context.md`
3. After changes, run `specsync check` to verify specs still pass

## Before creating a PR

Run `specsync check --strict` — all specs must pass with zero warnings.

## When adding new modules

Run `specsync add-spec <module-name>` to scaffold the spec and companion files, then fill in the spec before writing code.

## Key commands

- `specsync check` — validate all specs against source code
- `specsync check --json` — machine-readable validation output
- `specsync coverage` — show which modules lack specs
- `specsync score` — quality score for each spec (0-100)
- `specsync add-spec <name>` — scaffold a new spec with companion files
- `specsync resolve --remote` — verify cross-project dependencies
"#;

const CURSORRULES_SNIPPET: &str = r#"# Spec-Sync Rules

This project uses spec-sync for spec-to-code validation. Specs live in the `specs/` directory.

## Rules

- Before editing a module, read its spec at `specs/<module>/<module>.spec.md`
- Check `specs/<module>/tasks.md` for outstanding work and `specs/<module>/context.md` for decisions
- After modifying code, ensure `specsync check` still passes
- When creating new modules, run `specsync add-spec <module-name>` first
- Keep specs in sync: if you change exports, parameters, or types, update the spec's Public API table
- Run `specsync check --strict` before committing
"#;

const COPILOT_INSTRUCTIONS_SNIPPET: &str = r#"# Spec-Sync Integration

This project uses spec-sync for bidirectional spec-to-code validation.

## Guidelines

- Specs are in `specs/<module>/<module>.spec.md` — read the relevant spec before modifying a module
- Companion files `tasks.md` and `context.md` in each spec directory provide additional context
- After changes, `specsync check` should pass with no errors
- New modules need specs: run `specsync add-spec <module-name>`
- Keep the Public API table in each spec up to date with actual exports
"#;

const AGENTS_MD_SNIPPET: &str = r#"# Spec-Sync Integration

This project uses [spec-sync](https://github.com/CorvidLabs/spec-sync) for bidirectional spec-to-code validation.

## Before modifying any module

1. Read the relevant spec in `specs/<module>/<module>.spec.md`
2. Check companion files: `specs/<module>/tasks.md` and `specs/<module>/context.md`
3. After changes, run `specsync check` to verify specs still pass

## Before creating a PR

Run `specsync check --strict` — all specs must pass with zero warnings.

## When adding new modules

Run `specsync add-spec <module-name>` to scaffold the spec and companion files, then fill in the spec before writing code.

## Key commands

- `specsync check` — validate all specs against source code
- `specsync check --json` — machine-readable validation output
- `specsync coverage` — show which modules lack specs
- `specsync score` — quality score for each spec (0-100)
- `specsync add-spec <name>` — scaffold a new spec with companion files
- `specsync resolve --remote` — verify cross-project dependencies
"#;

const PRE_COMMIT_HOOK: &str = r#"#!/bin/sh
# spec-sync pre-commit hook — validates specs before allowing commits.
# Installed by: specsync hooks install --precommit
# Remove by deleting this file or running: specsync hooks uninstall --precommit

if command -v specsync >/dev/null 2>&1; then
    echo "specsync: checking specs..."
    if ! specsync check --strict; then
        echo ""
        echo "specsync: specs have errors — fix them before committing."
        echo "  Run 'specsync check' to see details."
        echo "  Use 'git commit --no-verify' to skip this check."
        exit 1
    fi
else
    echo "specsync: not installed, skipping spec check"
fi
"#;

const CLAUDE_CODE_HOOK_SETTINGS: &str = r#"{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write|NotebookEdit",
        "hooks": [
          {
            "type": "command",
            "command": "specsync check --json 2>/dev/null | head -1 || true"
          }
        ]
      }
    ]
  }
}"#;

/// All hook targets that can be installed.
#[derive(Debug, Clone, Copy, PartialEq)]
#[allow(dead_code)]
pub enum HookTarget {
    Claude,
    Cursor,
    Copilot,
    Agents,
    Precommit,
    ClaudeCodeHook,
}

impl HookTarget {
    pub fn all() -> &'static [HookTarget] {
        &[
            HookTarget::Claude,
            HookTarget::Cursor,
            HookTarget::Copilot,
            HookTarget::Agents,
            HookTarget::Precommit,
            HookTarget::ClaudeCodeHook,
        ]
    }

    #[allow(dead_code)]
    pub fn name(&self) -> &'static str {
        match self {
            HookTarget::Claude => "claude",
            HookTarget::Cursor => "cursor",
            HookTarget::Copilot => "copilot",
            HookTarget::Agents => "agents",
            HookTarget::Precommit => "precommit",
            HookTarget::ClaudeCodeHook => "claude-code-hook",
        }
    }

    pub fn description(&self) -> &'static str {
        match self {
            HookTarget::Claude => "CLAUDE.md agent instructions",
            HookTarget::Cursor => ".cursorrules agent instructions",
            HookTarget::Copilot => ".github/copilot-instructions.md",
            HookTarget::Agents => "AGENTS.md agent instructions",
            HookTarget::Precommit => "Git pre-commit hook",
            HookTarget::ClaudeCodeHook => "Claude Code settings.json hook",
        }
    }

    #[allow(dead_code)]
    pub fn from_str(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "claude" => Some(HookTarget::Claude),
            "cursor" => Some(HookTarget::Cursor),
            "copilot" => Some(HookTarget::Copilot),
            "agents" => Some(HookTarget::Agents),
            "precommit" | "pre-commit" => Some(HookTarget::Precommit),
            "claude-code-hook" | "claude-hook" => Some(HookTarget::ClaudeCodeHook),
            _ => None,
        }
    }
}

/// Check if a hook target is already installed.
pub fn is_installed(root: &Path, target: HookTarget) -> bool {
    match target {
        HookTarget::Claude => {
            let path = root.join("CLAUDE.md");
            path.exists()
                && fs::read_to_string(&path)
                    .map(|c| c.contains("Spec-Sync Integration"))
                    .unwrap_or(false)
        }
        HookTarget::Cursor => {
            let path = root.join(".cursorrules");
            path.exists()
                && fs::read_to_string(&path)
                    .map(|c| c.contains("Spec-Sync Rules"))
                    .unwrap_or(false)
        }
        HookTarget::Copilot => {
            let path = root.join(".github").join("copilot-instructions.md");
            path.exists()
                && fs::read_to_string(&path)
                    .map(|c| c.contains("Spec-Sync Integration"))
                    .unwrap_or(false)
        }
        HookTarget::Agents => {
            let path = root.join("AGENTS.md");
            path.exists()
                && fs::read_to_string(&path)
                    .map(|c| c.contains("Spec-Sync Integration"))
                    .unwrap_or(false)
        }
        HookTarget::Precommit => {
            let path = root.join(".git").join("hooks").join("pre-commit");
            path.exists()
                && fs::read_to_string(&path)
                    .map(|c| c.contains("spec-sync pre-commit hook"))
                    .unwrap_or(false)
        }
        HookTarget::ClaudeCodeHook => {
            let path = root.join(".claude").join("settings.json");
            path.exists()
                && fs::read_to_string(&path)
                    .map(|c| c.contains("specsync check"))
                    .unwrap_or(false)
        }
    }
}

/// Install a single hook target. Returns Ok(true) if installed, Ok(false) if already present.
pub fn install_hook(root: &Path, target: HookTarget) -> Result<bool, String> {
    if is_installed(root, target) {
        return Ok(false);
    }

    match target {
        HookTarget::Claude => install_claude_md(root),
        HookTarget::Cursor => install_cursorrules(root),
        HookTarget::Copilot => install_copilot(root),
        HookTarget::Agents => install_agents_md(root),
        HookTarget::Precommit => install_precommit(root),
        HookTarget::ClaudeCodeHook => install_claude_code_hook(root),
    }
}

/// Uninstall a single hook target. Returns Ok(true) if removed, Ok(false) if not found.
pub fn uninstall_hook(root: &Path, target: HookTarget) -> Result<bool, String> {
    if !is_installed(root, target) {
        return Ok(false);
    }

    match target {
        HookTarget::Claude => {
            // Remove the spec-sync section from CLAUDE.md
            let path = root.join("CLAUDE.md");
            remove_section_from_file(&path, "# Spec-Sync Integration")
        }
        HookTarget::Cursor => {
            let path = root.join(".cursorrules");
            remove_section_from_file(&path, "# Spec-Sync Rules")
        }
        HookTarget::Copilot => {
            let path = root.join(".github").join("copilot-instructions.md");
            remove_section_from_file(&path, "# Spec-Sync Integration")
        }
        HookTarget::Agents => {
            let path = root.join("AGENTS.md");
            remove_section_from_file(&path, "# Spec-Sync Integration")
        }
        HookTarget::Precommit => {
            let path = root.join(".git").join("hooks").join("pre-commit");
            if path.exists() {
                let content = fs::read_to_string(&path)
                    .map_err(|e| format!("Failed to read pre-commit hook: {e}"))?;
                if content.contains("spec-sync pre-commit hook") {
                    // If the entire file is our hook, remove it
                    if content.trim().starts_with("#!/bin/sh")
                        && content.contains("specsync check")
                        && content.lines().count() < 20
                    {
                        fs::remove_file(&path)
                            .map_err(|e| format!("Failed to remove pre-commit hook: {e}"))?;
                        return Ok(true);
                    }
                }
            }
            Ok(false)
        }
        HookTarget::ClaudeCodeHook => {
            // Don't auto-remove Claude Code settings — too risky
            Err(
                "Claude Code hook settings must be removed manually from .claude/settings.json"
                    .to_string(),
            )
        }
    }
}

// ─── Installation helpers ────────────────────────────────────────────────────

fn install_claude_md(root: &Path) -> Result<bool, String> {
    let path = root.join("CLAUDE.md");

    if path.exists() {
        // Append to existing CLAUDE.md
        let existing =
            fs::read_to_string(&path).map_err(|e| format!("Failed to read CLAUDE.md: {e}"))?;

        if existing.contains("Spec-Sync") {
            return Ok(false);
        }

        let new_content = format!("{}\n\n{}", existing.trim_end(), CLAUDE_MD_SNIPPET);
        fs::write(&path, new_content).map_err(|e| format!("Failed to write CLAUDE.md: {e}"))?;
    } else {
        fs::write(&path, CLAUDE_MD_SNIPPET)
            .map_err(|e| format!("Failed to create CLAUDE.md: {e}"))?;
    }

    Ok(true)
}

fn install_cursorrules(root: &Path) -> Result<bool, String> {
    let path = root.join(".cursorrules");

    if path.exists() {
        let existing =
            fs::read_to_string(&path).map_err(|e| format!("Failed to read .cursorrules: {e}"))?;

        if existing.contains("Spec-Sync") {
            return Ok(false);
        }

        let new_content = format!("{}\n\n{}", existing.trim_end(), CURSORRULES_SNIPPET);
        fs::write(&path, new_content).map_err(|e| format!("Failed to write .cursorrules: {e}"))?;
    } else {
        fs::write(&path, CURSORRULES_SNIPPET)
            .map_err(|e| format!("Failed to create .cursorrules: {e}"))?;
    }

    Ok(true)
}

fn install_copilot(root: &Path) -> Result<bool, String> {
    let github_dir = root.join(".github");
    if !github_dir.exists() {
        fs::create_dir_all(&github_dir).map_err(|e| format!("Failed to create .github/: {e}"))?;
    }

    let path = github_dir.join("copilot-instructions.md");

    if path.exists() {
        let existing = fs::read_to_string(&path)
            .map_err(|e| format!("Failed to read copilot-instructions.md: {e}"))?;

        if existing.contains("Spec-Sync") {
            return Ok(false);
        }

        let new_content = format!(
            "{}\n\n{}",
            existing.trim_end(),
            COPILOT_INSTRUCTIONS_SNIPPET
        );
        fs::write(&path, new_content)
            .map_err(|e| format!("Failed to write copilot-instructions.md: {e}"))?;
    } else {
        fs::write(&path, COPILOT_INSTRUCTIONS_SNIPPET)
            .map_err(|e| format!("Failed to create copilot-instructions.md: {e}"))?;
    }

    Ok(true)
}

fn install_agents_md(root: &Path) -> Result<bool, String> {
    let path = root.join("AGENTS.md");

    if path.exists() {
        let existing =
            fs::read_to_string(&path).map_err(|e| format!("Failed to read AGENTS.md: {e}"))?;

        if existing.contains("Spec-Sync") {
            return Ok(false);
        }

        let new_content = format!("{}\n\n{}", existing.trim_end(), AGENTS_MD_SNIPPET);
        fs::write(&path, new_content).map_err(|e| format!("Failed to write AGENTS.md: {e}"))?;
    } else {
        fs::write(&path, AGENTS_MD_SNIPPET)
            .map_err(|e| format!("Failed to create AGENTS.md: {e}"))?;
    }

    Ok(true)
}

fn install_precommit(root: &Path) -> Result<bool, String> {
    let hooks_dir = root.join(".git").join("hooks");
    if !hooks_dir.exists() {
        fs::create_dir_all(&hooks_dir).map_err(|e| format!("Failed to create .git/hooks/: {e}"))?;
    }

    let path = hooks_dir.join("pre-commit");

    if path.exists() {
        let existing = fs::read_to_string(&path)
            .map_err(|e| format!("Failed to read pre-commit hook: {e}"))?;

        if existing.contains("specsync") {
            return Ok(false);
        }

        // Append to existing pre-commit hook
        let new_content = format!(
            "{}\n\n# --- spec-sync pre-commit hook ---\n{}",
            existing.trim_end(),
            PRE_COMMIT_HOOK
                .lines()
                .skip(1) // Skip the shebang since the existing file has one
                .collect::<Vec<_>>()
                .join("\n")
        );
        fs::write(&path, new_content)
            .map_err(|e| format!("Failed to write pre-commit hook: {e}"))?;
    } else {
        fs::write(&path, PRE_COMMIT_HOOK)
            .map_err(|e| format!("Failed to create pre-commit hook: {e}"))?;
    }

    // Make executable on Unix
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let perms = std::fs::Permissions::from_mode(0o755);
        fs::set_permissions(&path, perms)
            .map_err(|e| format!("Failed to set pre-commit hook permissions: {e}"))?;
    }

    Ok(true)
}

fn install_claude_code_hook(root: &Path) -> Result<bool, String> {
    let claude_dir = root.join(".claude");
    if !claude_dir.exists() {
        fs::create_dir_all(&claude_dir).map_err(|e| format!("Failed to create .claude/: {e}"))?;
    }

    let path = claude_dir.join("settings.json");

    if path.exists() {
        let existing = fs::read_to_string(&path)
            .map_err(|e| format!("Failed to read .claude/settings.json: {e}"))?;

        if existing.contains("specsync") {
            return Ok(false);
        }

        // Parse existing JSON, merge hooks in
        let mut parsed: serde_json::Value = serde_json::from_str(&existing)
            .map_err(|e| format!("Failed to parse .claude/settings.json: {e}"))?;

        let hook_value: serde_json::Value = serde_json::from_str(CLAUDE_CODE_HOOK_SETTINGS)
            .expect("built-in hook template is valid JSON");

        if let Some(obj) = parsed.as_object_mut()
            && let Some(hooks) = hook_value.get("hooks")
        {
            obj.insert("hooks".to_string(), hooks.clone());
        }

        let new_content = serde_json::to_string_pretty(&parsed)
            .map_err(|e| format!("Failed to serialize settings: {e}"))?;
        fs::write(&path, format!("{new_content}\n"))
            .map_err(|e| format!("Failed to write .claude/settings.json: {e}"))?;
    } else {
        fs::write(&path, format!("{CLAUDE_CODE_HOOK_SETTINGS}\n"))
            .map_err(|e| format!("Failed to create .claude/settings.json: {e}"))?;
    }

    Ok(true)
}

/// Remove a section starting with `marker` from a file.
/// If the file becomes empty, delete it.
fn remove_section_from_file(path: &Path, marker: &str) -> Result<bool, String> {
    if !path.exists() {
        return Ok(false);
    }

    let content =
        fs::read_to_string(path).map_err(|e| format!("Failed to read {}: {e}", path.display()))?;

    if !content.contains(marker) {
        return Ok(false);
    }

    // Find the marker and remove everything from it to end-of-file or next top-level heading
    let mut lines: Vec<&str> = content.lines().collect();
    let mut start = None;
    let mut end = lines.len();

    for (i, line) in lines.iter().enumerate() {
        if line.contains(marker) {
            start = Some(i);
            // Look for the next top-level heading that isn't part of our section
            for (j, line) in lines.iter().enumerate().skip(i + 1) {
                if line.starts_with("# ") && !line.contains("Spec-Sync") {
                    end = j;
                    break;
                }
            }
            break;
        }
    }

    if let Some(start) = start {
        // Remove trailing blank lines before our section too
        let mut actual_start = start;
        while actual_start > 0 && lines[actual_start - 1].trim().is_empty() {
            actual_start -= 1;
        }
        lines.drain(actual_start..end);
    }

    let new_content = lines.join("\n");
    let trimmed = new_content.trim();

    if trimmed.is_empty() {
        fs::remove_file(path).map_err(|e| format!("Failed to remove {}: {e}", path.display()))?;
    } else {
        fs::write(path, format!("{trimmed}\n"))
            .map_err(|e| format!("Failed to write {}: {e}", path.display()))?;
    }

    Ok(true)
}

// ─── CLI command handlers ────────────────────────────────────────────────────

/// Install hooks for the specified targets (or all if empty).
pub fn cmd_install(root: &Path, targets: &[HookTarget]) {
    let targets = if targets.is_empty() {
        HookTarget::all().to_vec()
    } else {
        targets.to_vec()
    };

    println!(
        "\n--- {} ------------------------------------------------",
        "Installing Hooks".bold()
    );

    let mut installed = 0;
    let mut skipped = 0;
    let mut errors = 0;

    for target in &targets {
        match install_hook(root, *target) {
            Ok(true) => {
                println!("  {} Installed {}", "".green(), target.description());
                installed += 1;
            }
            Ok(false) => {
                println!(
                    "  {} Already installed: {}",
                    "·".dimmed(),
                    target.description()
                );
                skipped += 1;
            }
            Err(e) => {
                println!("  {} {}: {e}", "".red(), target.description());
                errors += 1;
            }
        }
    }

    println!();
    if installed > 0 {
        println!("{installed} hook(s) installed.");
    }
    if skipped > 0 {
        println!("{skipped} hook(s) already present.");
    }
    if errors > 0 {
        println!("{errors} hook(s) failed.");
        std::process::exit(1);
    }
}

/// Uninstall hooks for the specified targets (or all if empty).
pub fn cmd_uninstall(root: &Path, targets: &[HookTarget]) {
    let targets = if targets.is_empty() {
        HookTarget::all().to_vec()
    } else {
        targets.to_vec()
    };

    println!(
        "\n--- {} ------------------------------------------------",
        "Uninstalling Hooks".bold()
    );

    let mut removed = 0;

    for target in &targets {
        match uninstall_hook(root, *target) {
            Ok(true) => {
                println!("  {} Removed {}", "".green(), target.description());
                removed += 1;
            }
            Ok(false) => {
                println!("  {} Not installed: {}", "·".dimmed(), target.description());
            }
            Err(e) => {
                println!("  {} {}: {e}", "!".yellow(), target.description());
            }
        }
    }

    println!();
    if removed > 0 {
        println!("{removed} hook(s) removed.");
    } else {
        println!("No hooks to remove.");
    }
}

/// Show status of all hook targets.
pub fn cmd_status(root: &Path) {
    println!(
        "\n--- {} ------------------------------------------------",
        "Hook Status".bold()
    );

    for target in HookTarget::all() {
        let installed = is_installed(root, *target);
        let status = if installed {
            "installed".green().to_string()
        } else {
            "not installed".dimmed().to_string()
        };
        println!("  {:20} {}", target.description(), status);
    }

    println!();
    println!("Install all: specsync hooks install");
    println!("Install one: specsync hooks install --claude --precommit");
}