spec-spine-cli 0.17.0

The `spec-spine` command-line tool: compile a markdown spec corpus into a deterministic authority registry and query it. A thin wrapper over spec-spine-core.
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
//! `spec-spine couple`: the PR-time coupling gate (spec 005).
//!
//! This is the only place `git` runs: it invokes `git -c core.quotepath=false
//! diff --no-color -U0 --no-renames --end-of-options base...head`, parses the
//! unified diff into a typed [`DiffInput`] (new-side hunk spans), reads the PR
//! body for a waiver, and calls the pure `spec-spine-core` gate. Diff parsing is
//! ported from OAP `spec-code-coupling-check/src/main.rs` (`parse_unified_diff`,
//! `parse_hunk_header`). `--no-renames` makes a rename surface as a delete + add
//! (so a `git mv` of a governed file cannot slip past the gate),
//! `core.quotepath=false` keeps unicode paths matchable, and `--end-of-options`
//! stops a crafted ref from being parsed as a git flag.

use std::path::{Path, PathBuf};
use std::process::Command;

use spec_spine_core::couple::spec_id_for_spec_md_path;
use spec_spine_core::{
    CoupleReport, DiffFile, DiffInput, FileContents, couple, dependency_only_waiver,
    is_bypassed_path, load_committed_index, parse_waiver,
};
use spec_spine_types::{Config, Error, LineSpan, Verdict, Violation, verdict::verb};

use crate::load_repo_config;
use crate::out;

/// Arguments for `spec-spine couple`.
pub struct CoupleArgs {
    pub base: String,
    pub head: String,
    pub pr_body: Option<PathBuf>,
    pub paths_from: Option<PathBuf>,
    /// Emit the verdict as a JSON envelope instead of prose (spec 037).
    pub json: bool,
}

pub fn run(repo: &Path, args: &CoupleArgs) -> Result<u8, Error> {
    let cfg = load_repo_config(repo)?;

    let diff = build_diff_input(repo, args)?;
    let body = read_pr_body(args)?;
    let mut waiver = parse_waiver(&cfg, &body);
    let mut auto_waived = false;

    // Spec 005 §3.5: mechanical dependency-only auto-waiver. Opt-in,
    // git-diff mode only (`--paths-from` has no content to compare), and
    // never overrides an explicit PR-body waiver.
    if waiver.is_none() && cfg.coupling.auto_waive_dependency_only && args.paths_from.is_none() {
        waiver = try_dependency_only_waiver(repo, &cfg, args, &diff)?;
        auto_waived = waiver.is_some();
    }

    let report = couple(&cfg, repo, &diff, waiver.as_ref())?;

    if args.json {
        // The `CoupleReport` verbatim, as `spec_spine_core::couple_json`
        // returns it: `violations`, `waiver` and `checkedPaths` are the reasons
        // a consumer needs, and the prose form's C-001/C-002 breakdown is a
        // rendering of the same `code` field rather than a second fact. The
        // auto-waiver distinction the prose draws is deliberately not in the
        // envelope: the report carries the waiver's reason, and how it was
        // obtained is a CLI concern, not part of the gate's verdict.
        let value = serde_json::to_value(&report).map_err(|e| Error::Schema(e.to_string()))?;
        let code = report.exit_code();
        out::verdict(&Verdict::report(verb::COUPLE, code, value))?;
        return Ok(code);
    }

    if report.has_blocking_drift() {
        let unclaimed = report
            .violations
            .iter()
            .filter(|v| v.code == "C-002")
            .count();
        let drift = report.violations.len() - unclaimed;
        if unclaimed == 0 {
            eprintln!(
                "spec-spine couple: {drift} drift violation(s): a changed path lacks an authoring edit to an owning spec.\n"
            );
        } else {
            eprintln!(
                "spec-spine couple: {} violation(s): {drift} drift (C-001), {unclaimed} unclaimed (C-002, require_ownership is on).\n",
                report.violations.len()
            );
        }
        for v in &report.violations {
            eprintln!("  {} {}", v.code, v.message);
        }
        eprint!("{}", resolution_footer(&cfg, &report, &diff));
    } else if let Some(reason) = &report.waiver {
        outln!(
            "spec-spine couple: {} violation(s) {}, reason: {reason}",
            report.violations.len(),
            if auto_waived { "auto-waived" } else { "waived" }
        );
        for v in &report.violations {
            outln!("  {} (waived)", v.message);
        }
    } else {
        outln!(
            "spec-spine couple: OK: {} path(s) checked, no drift.",
            report.checked_paths
        );
    }

    Ok(report.exit_code())
}

/// The resolution footer a blocking report ends with (spec 052 §3.2, §3.3).
///
/// A pure function of `(config, report, diff)`: no input is read and nothing is
/// written, so the same three arguments always produce the same bytes.
///
/// The gate has always named the specs that own a drifted path and never named
/// the mechanism for crossing into their territory. Of the two doors it used to
/// offer, both are shut for the case that produces most `C-001` refusals: an
/// author building their own spec who reached into a file another spec owns.
/// Editing the other spec is the illegitimate mid-build edit
/// `.claude/rules/adversarial-prompt-refusal.md` forbids, and the waiver is a
/// human instrument an unattended session may not grant itself. The third door,
/// an `extends` edge in the author's own spec, is the corpus's actual answer,
/// and this is where the gate finally says so.
fn resolution_footer(cfg: &Config, report: &CoupleReport, diff: &DiffInput) -> String {
    let drift: Vec<&Violation> = report
        .violations
        .iter()
        .filter(|v| v.code == "C-001")
        .collect();
    let unclaimed = report.violations.len() - drift.len();
    let keyword = &cfg.coupling.waiver_keyword;

    // No `C-001`: the report is `C-002` only, and renders exactly the footer it
    // rendered before this spec (§3.2). Claiming a path is a different act from
    // crossing into somebody's territory, and the three doors do not apply.
    if drift.is_empty() {
        return format!(
            "\nResolve by editing an owning spec's spec.md (C-001), claiming the path in a spec's owning edge (C-002), or add a '{keyword}' line to the PR body.\n"
        );
    }

    let mut f = String::from("\nResolve, in the order an author should consider them");
    if unclaimed > 0 {
        f.push_str(" (1-3 answer C-001; 4 answers C-002)");
    }
    f.push_str(":\n\n");

    f.push_str(
        "  1. Edit the owning spec's spec.md. The right door when the spec that owns\n\
         \x20    the path is the one you are authoring.\n\n",
    );

    f.push_str(
        "  2. Declare an `extends` edge in your OWN spec, naming the owning spec\n\
         \x20    and the unit you touched. That makes your spec a legitimate owner of\n\
         \x20    the unit, so the gate clears on the next run. It amends nobody and\n\
         \x20    needs no waiver.\n\n",
    );
    f.push_str(&extends_guidance(cfg, &drift, diff));

    f.push_str(&format!(
        "  3. Add a '{keyword} <reason>' line to the PR body. A waiver is a\n\
         \x20    human instrument: it needs explicit human approval, and is not a\n\
         \x20    flag an unattended session sets for itself.\n"
    ));

    if unclaimed > 0 {
        f.push_str(
            "\n  4. For the unclaimed path(s) above, claim the path in a spec's owning\n\
             \x20    edge.\n",
        );
    }
    f
}

/// Door two's body: the concrete `extends` block when the diff makes it
/// concrete, else the shape to fill in (spec 052 §3.3).
///
/// The specific form triggers on **exactly one** edited `spec.md`, and needs no
/// further test: clearance is "any one owner's spec.md is in the diff", so a
/// single edited spec that owned a violating path would already have cleared it.
/// Every `C-001` reaching this footer is therefore a path that spec does not
/// own, which is exactly the crossing case. Zero or two-or-more edited specs
/// fall back to the generic form: an amendment pair is a legitimate shape and
/// the gate has no basis for guessing which of the two should declare the edge.
fn extends_guidance(cfg: &Config, drift: &[&Violation], diff: &DiffInput) -> String {
    let specs_dir = cfg.layout.specs_dir.as_str();
    let edited: Vec<&str> = diff
        .files
        .iter()
        .filter_map(|f| spec_id_for_spec_md_path(specs_dir, &f.path))
        .collect();

    let Some(id) = edited.first().filter(|_| edited.len() == 1) else {
        return concat!(
            "     In your spec's frontmatter:\n\n",
            "       extends:\n",
            "         - { spec: \"<owning-spec-id>\", unit: \"<path>\", nature: additive }\n\n",
        )
        .to_string();
    };

    let mut s = format!(
        "     spec {id} is the only spec.md edited in this diff, and owns none of\n\
         \x20    the paths above. Cross into the owning territory by declaring, in\n\
         \x20    {}:\n\n\
         \x20      extends:\n",
        spec_md_rel(specs_dir, id)
    );
    // One item per violating path, in the report's existing sorted-by-path
    // order. Three values are defaults rather than verdicts: the first owner in
    // sorted order (clearing needs only one), the file-shorthand unit, and
    // `nature: additive`. The note below says so, because a gate that presented
    // a guess as the answer would be worse than one that stayed silent.
    for v in drift {
        let (Some(path), Some(owner)) = (v.path.as_deref(), v.owners.first()) else {
            continue;
        };
        s.push_str(&format!(
            "         - {{ spec: \"{owner}\", unit: \"{path}\", nature: additive }}\n"
        ));
    }
    s.push_str(
        "\n     A suggestion, not an instruction, and not the only correct form:\n\
         \x20    where a path has several owners any one of them clears it, a narrower\n\
         \x20    section or symbol unit is available if you want the claim tighter,\n\
         \x20    and `nature` is a free-text hint (`superseding` describes a crossing\n\
         \x20    that replaces behavior rather than adding to it). If you did not mean\n\
         \x20    to touch the path, revert the touch and declare nothing.\n\n",
    );
    s
}

/// `<specs_dir>/<id>/spec.md`, matching the core gate's own `spec_md_rel`.
fn spec_md_rel(specs_dir: &str, id: &str) -> String {
    format!("{}/{id}/spec.md", specs_dir.trim_end_matches('/'))
}

/// Build the [`DiffInput`]: either from `--paths-from` (whole-file fallback, no
/// hunks) or from `git diff --no-color -U0 base...head`.
fn build_diff_input(repo: &Path, args: &CoupleArgs) -> Result<DiffInput, Error> {
    if let Some(path) = &args.paths_from {
        let text = std::fs::read_to_string(path)
            .map_err(|e| Error::Io(format!("read --paths-from {}: {e}", path.display())))?;
        let files = text
            .lines()
            .map(str::trim)
            .filter(|l| !l.is_empty())
            .map(|p| DiffFile {
                path: p.to_string(),
                hunks: Vec::new(),
                // `--paths-from` carries no history, so a listed path is never
                // known to be a deletion: the ratchet judges it as an edit.
                deleted: false,
            })
            .collect();
        return Ok(DiffInput { files });
    }

    let raw = run_git_diff(repo, &args.base, &args.head)?;
    Ok(parse_unified_diff(&raw))
}

/// Attempt the spec 005 §3.5 mechanical auto-waiver (extended to cargo and
/// workflow manifests by spec 030): every non-bypassed changed path must be a
/// recognized dependency manifest (`package.json` / `Cargo.toml` /
/// `.github/workflows/*.yml`) whose base→head change is confined to dependency
/// version pins. Contents come from `git show` at the **merge base** (the diff
/// is three-dot, so the base side is `merge-base(base, head)`, not the base
/// branch tip) and at `head`. Any git failure refuses the auto-waiver
/// fail-closed rather than erroring the gate.
///
/// The bypass verdict is claim-aware (spec 009): it assembles the committed
/// index from its shard set so a claim-overridden floor path counts as a
/// candidate and refuses the waiver, matching exactly the path set the gate
/// evaluates. An unreadable index refuses fail-closed (the gate itself will
/// report the real error).
fn try_dependency_only_waiver(
    repo: &Path,
    cfg: &Config,
    args: &CoupleArgs,
    diff: &DiffInput,
) -> Result<Option<spec_spine_core::Waiver>, Error> {
    let Ok(index) = load_committed_index(cfg, repo) else {
        return Ok(None);
    };
    let candidates: Vec<&DiffFile> = diff
        .files
        .iter()
        .filter(|f| !is_bypassed_path(cfg, &index, &f.path))
        .collect();
    // Cheap pre-filter before any git spawn: the waiver can only ever apply
    // when every non-bypassed path is a recognized dependency manifest
    // (package.json / Cargo.toml / workflow YAML).
    if candidates.is_empty()
        || !candidates
            .iter()
            .all(|f| spec_spine_core::is_dependency_manifest(&f.path))
    {
        return Ok(None);
    }

    let Some(merge_base) = git_merge_base(repo, &args.base, &args.head) else {
        return Ok(None);
    };

    let mut files: Vec<FileContents> = Vec::with_capacity(candidates.len());
    for f in &candidates {
        files.push(FileContents {
            path: f.path.clone(),
            base: git_show(repo, &merge_base, &f.path),
            head: git_show(repo, &args.head, &f.path),
        });
    }
    Ok(dependency_only_waiver(&files))
}

fn git_merge_base(repo: &Path, base: &str, head: &str) -> Option<String> {
    let out = Command::new("git")
        .arg("-C")
        .arg(repo)
        // `--end-of-options`: everything after is an operand, so a ref that looks
        // like a flag (`--foo`) can never be parsed as a git option.
        .args(["merge-base", "--end-of-options", base, head])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let rev = String::from_utf8_lossy(&out.stdout).trim().to_string();
    if rev.is_empty() { None } else { Some(rev) }
}

fn git_show(repo: &Path, rev: &str, path: &str) -> Option<String> {
    let out = Command::new("git")
        .arg("-C")
        .arg(repo)
        // `--end-of-options`: the `rev:path` operand can never be parsed as a flag.
        .args(["show", "--end-of-options", &format!("{rev}:{path}")])
        .output()
        .ok()?;
    if !out.status.success() {
        return None; // absent at this rev (created/deleted); fail closed upstream
    }
    Some(String::from_utf8_lossy(&out.stdout).into_owned())
}

fn run_git_diff(repo: &Path, base: &str, head: &str) -> Result<String, Error> {
    let out = Command::new("git")
        .arg("-C")
        .arg(repo)
        // `core.quotepath=false`: keep non-ASCII paths literal instead of octal
        // C-quoting, so a governed file with a unicode/space name still matches
        // its owning unit rather than arriving as a quoted, unmatched string.
        .args(["-c", "core.quotepath=false"])
        // `--no-renames`: a pure rename emits `rename from/to` with no +++/---
        // headers and would be invisible to the parser, letting a `git mv` of a
        // governed file slip past the gate. Disabling rename detection surfaces
        // it as a delete of the old path + an add of the new path (both parsed as
        // whole-file changes), so the gate evaluates both. `--end-of-options`:
        // the `base...head` operand can never be parsed as a git flag.
        .args([
            "diff",
            "--no-color",
            "-U0",
            "--no-renames",
            "--end-of-options",
        ])
        .arg(format!("{base}...{head}"))
        .output()
        .map_err(|e| Error::Io(format!("spawn git diff: {e}")))?;
    if !out.status.success() {
        let stderr = String::from_utf8_lossy(&out.stderr);
        return Err(Error::Io(format!(
            "git diff exited {:?}: {stderr}",
            out.status.code()
        )));
    }
    Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}

/// Parse `git diff --no-color -U0` output into a [`DiffInput`]. New-side hunk
/// ranges become inclusive [`LineSpan`]s; a deleted file (`+++ /dev/null`) is
/// registered with no hunks (a whole-file change) and flagged `deleted` so the
/// spec 032 ownership ratchet can leave it alone.
fn parse_unified_diff(diff_text: &str) -> DiffInput {
    use std::collections::BTreeMap;
    /// Per-path accumulator: new-side hunks and whether the path was deleted.
    #[derive(Default)]
    struct Entry {
        hunks: Vec<LineSpan>,
        deleted: bool,
    }
    let mut files: BTreeMap<String, Entry> = BTreeMap::new();
    let mut current_path: Option<String> = None;
    let mut minus_path: Option<String> = None;

    for line in diff_text.lines() {
        if let Some(rest) = line.strip_prefix("--- ") {
            minus_path = strip_diff_prefix(rest.trim());
        } else if let Some(rest) = line.strip_prefix("+++ ") {
            let p = rest.trim();
            let deleted = p == "/dev/null";
            if deleted {
                // Deletion: the changed path is the old (minus) side, whole-file.
                current_path = minus_path.clone();
            } else {
                current_path = strip_diff_prefix(p);
            }
            if let Some(path) = &current_path {
                let entry = files.entry(path.clone()).or_default();
                entry.deleted = deleted;
            }
        } else if line.starts_with("@@") {
            if let Some(path) = &current_path {
                if let Some(span) = parse_hunk_header(line) {
                    files.entry(path.clone()).or_default().hunks.push(span);
                }
            }
        }
    }

    DiffInput {
        files: files
            .into_iter()
            .map(|(path, entry)| DiffFile {
                path,
                hunks: entry.hunks,
                deleted: entry.deleted,
            })
            .collect(),
    }
}

/// `a/<path>` / `b/<path>` → `<path>`; `/dev/null` → `None`.
fn strip_diff_prefix(p: &str) -> Option<String> {
    if p == "/dev/null" {
        return None;
    }
    Some(
        p.strip_prefix("a/")
            .or_else(|| p.strip_prefix("b/"))
            .unwrap_or(p)
            .to_string(),
    )
}

/// Parse `@@ -<old> +<new> @@` into the inclusive new-side span. A pure-deletion
/// hunk (`+start,0`) collapses to the single line at `start`.
fn parse_hunk_header(line: &str) -> Option<LineSpan> {
    let after_at = line.strip_prefix("@@")?.trim_start();
    let rest = after_at.strip_prefix('-')?;
    let plus_pos = rest.find('+')?;
    let new_part = rest[plus_pos + 1..].trim_start();
    let new_range = new_part.split_whitespace().next()?;
    let (start_s, count_s) = match new_range.split_once(',') {
        Some((a, b)) => (a, b),
        None => (new_range, "1"),
    };
    let start: usize = start_s.parse().ok()?;
    let count: usize = count_s.parse().ok()?;
    if start == 0 {
        // `+0,0`: a deletion with no new-side line. Whole-file fallback handles
        // the path; emit nothing for this hunk.
        return None;
    }
    let count = count.max(1);
    Some(LineSpan::new(start, start + count - 1))
}

fn read_pr_body(args: &CoupleArgs) -> Result<String, Error> {
    if let Some(path) = &args.pr_body {
        std::fs::read_to_string(path)
            .map_err(|e| Error::Io(format!("read --pr-body {}: {e}", path.display())))
    } else if let Ok(s) = std::env::var("SPEC_SPINE_PR_BODY") {
        Ok(s)
    } else {
        Ok(String::new())
    }
}

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

    #[test]
    fn parses_modification_hunks_to_inclusive_spans() {
        let diff = "diff --git a/Makefile b/Makefile\n\
                    --- a/Makefile\n\
                    +++ b/Makefile\n\
                    @@ -10,2 +10,3 @@ ctx\n\
                    @@ -50 +51,5 @@\n";
        let d = parse_unified_diff(diff);
        let f = d.files.iter().find(|f| f.path == "Makefile").unwrap();
        assert_eq!(f.hunks, vec![LineSpan::new(10, 12), LineSpan::new(51, 55)]);
    }

    #[test]
    fn deleted_file_is_whole_file_change() {
        let diff = "diff --git a/gone.rs b/gone.rs\n\
                    deleted file mode 100644\n\
                    --- a/gone.rs\n\
                    +++ /dev/null\n\
                    @@ -1,5 +0,0 @@\n";
        let d = parse_unified_diff(diff);
        let f = d.files.iter().find(|f| f.path == "gone.rs").unwrap();
        assert!(f.hunks.is_empty(), "deletion ⇒ whole-file (no hunks)");
        assert!(f.deleted, "deletion is flagged for the ownership ratchet");
    }

    #[test]
    fn modified_and_added_files_are_not_deleted() {
        let diff = "diff --git a/Makefile b/Makefile\n\
                    --- a/Makefile\n\
                    +++ b/Makefile\n\
                    @@ -10,2 +10,3 @@ ctx\n\
                    diff --git a/new.rs b/new.rs\n\
                    new file mode 100644\n\
                    --- /dev/null\n\
                    +++ b/new.rs\n\
                    @@ -0,0 +1,3 @@\n";
        let d = parse_unified_diff(diff);
        assert!(d.files.iter().all(|f| !f.deleted), "{:?}", d.files);
    }

    #[test]
    fn rename_under_no_renames_registers_both_paths() {
        // `--no-renames` turns a rename into a delete of the old path plus an add
        // of the new path, so BOTH surfaces reach the gate. Without it, a pure
        // rename emits only `rename from/to` lines (no +++/---) and would be
        // invisible: a `git mv` of a governed file could slip past coupling.
        let diff = "diff --git a/old/mod.rs b/old/mod.rs\n\
                    deleted file mode 100644\n\
                    --- a/old/mod.rs\n\
                    +++ /dev/null\n\
                    @@ -1,3 +0,0 @@\n\
                    diff --git a/new/mod.rs b/new/mod.rs\n\
                    new file mode 100644\n\
                    --- /dev/null\n\
                    +++ b/new/mod.rs\n\
                    @@ -0,0 +1,3 @@\n";
        let d = parse_unified_diff(diff);
        assert!(
            d.files.iter().any(|f| f.path == "old/mod.rs"),
            "vacated path must be seen"
        );
        assert!(
            d.files.iter().any(|f| f.path == "new/mod.rs"),
            "new path must be seen"
        );
    }
}