spectra-cli 0.5.0

OpenSpectra command-line interface.
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
//! CLI-level integration tests that spawn the built `spectra` binary, for
//! contracts that depend on full dispatch through `run()` (not just clap
//! parsing) -- unit tests in `main.rs` cover the parser; these cover the
//! actual runtime behavior.

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

fn spectra() -> Command {
    Command::new(env!("CARGO_BIN_EXE_spectra"))
}

fn git(dir: &Path, args: &[&str]) {
    let ok = Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(args)
        .output()
        .expect("git runs")
        .status
        .success();
    assert!(ok, "git {args:?} failed");
}

struct TempDir(std::path::PathBuf);

impl TempDir {
    fn new(label: &str) -> Self {
        static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        let seq = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let dir = std::env::temp_dir().join(format!(
            "spectra-cli-it-{label}-{}-{seq}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        Self(dir)
    }
}

impl std::ops::Deref for TempDir {
    type Target = Path;
    fn deref(&self) -> &Path {
        &self.0
    }
}

impl Drop for TempDir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

#[test]
fn list_changes_flag_output_is_byte_identical_to_the_default() {
    let tmp = TempDir::new("list-changes");
    git(&tmp, &["init", "-q"]);
    git(&tmp, &["config", "user.email", "t@t.co"]);
    git(&tmp, &["config", "user.name", "t"]);

    let init = spectra().arg("init").current_dir(&*tmp).output().unwrap();
    assert!(init.status.success(), "init failed: {init:?}");
    let new_change = spectra()
        .args(["new", "change", "add-search-filter"])
        .current_dir(&*tmp)
        .output()
        .unwrap();
    assert!(
        new_change.status.success(),
        "new change failed: {new_change:?}"
    );

    let default_human = spectra().arg("list").current_dir(&*tmp).output().unwrap();
    let changes_human = spectra()
        .args(["list", "--changes"])
        .current_dir(&*tmp)
        .output()
        .unwrap();
    assert!(
        default_human.status.success(),
        "list failed: {default_human:?}"
    );
    assert!(
        changes_human.status.success(),
        "list --changes failed: {changes_human:?}"
    );
    assert_eq!(default_human.stdout, changes_human.stdout);

    let default_json = spectra()
        .args(["list", "--json"])
        .current_dir(&*tmp)
        .output()
        .unwrap();
    let changes_json = spectra()
        .args(["list", "--changes", "--json"])
        .current_dir(&*tmp)
        .output()
        .unwrap();
    assert!(
        default_json.status.success(),
        "list --json failed: {default_json:?}"
    );
    assert!(
        changes_json.status.success(),
        "list --changes --json failed: {changes_json:?}"
    );
    assert_eq!(default_json.stdout, changes_json.stdout);
    assert!(!default_json.stdout.is_empty());
}

#[test]
fn init_text_output_reports_root_spec_dir_and_gitignore_update() {
    let tmp = TempDir::new("init-text");
    git(&tmp, &["init", "-q"]);

    let out = spectra().arg("init").current_dir(&*tmp).output().unwrap();
    assert!(out.status.success(), "init failed: {out:?}");
    let stdout = String::from_utf8(out.stdout).unwrap();

    // Canonicalize before comparing: on macOS `std::env::temp_dir()` returns
    // a `/var/...` path that's actually a symlink to `/private/var/...`, and
    // the CLI reports whatever `std::env::current_dir()` resolves to after
    // `cd`-ing in, which follows the symlink -- a raw `contains` would only
    // pass by coincidence (see the sibling JSON test for the same issue).
    let canonical_root = tmp.canonicalize().unwrap();
    assert!(stdout.contains(&canonical_root.display().to_string()));
    assert!(stdout.contains("spec_dir: openspec"));
    assert!(stdout.contains("Added '.spectra/' to .gitignore."));
}

#[test]
fn init_json_output_matches_the_documented_shape() {
    let tmp = TempDir::new("init-json");
    git(&tmp, &["init", "-q"]);

    let out = spectra()
        .args(["init", "--json"])
        .current_dir(&*tmp)
        .output()
        .unwrap();
    assert!(out.status.success(), "init --json failed: {out:?}");
    let stdout = String::from_utf8(out.stdout).unwrap();

    let value: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(value["spec_dir"], "openspec");
    assert_eq!(value["adopted"], false);
    assert_eq!(value["gitignore_updated"], true);
    // Compare canonicalized paths: on macOS `std::env::temp_dir()` returns a
    // `/var/...` path that's actually a symlink to `/private/var/...`, and
    // the CLI reports whatever `std::env::current_dir()` resolves to after
    // `cd`-ing in, which follows the symlink.
    let reported_root = PathBuf::from(value["root"].as_str().unwrap());
    assert_eq!(
        reported_root.canonicalize().unwrap(),
        tmp.canonicalize().unwrap()
    );
}

#[test]
fn drift_exits_zero_even_when_severity_is_medium_or_higher() {
    // Regression for issue #37: a successful drift analysis must always exit 0
    // regardless of severity (matching the reference binary and the README's
    // documented contract). v0.1.0 mapped severity to the exit code (light->0,
    // medium->1, heavy->2), which reddened downstream CI on the `spectra`
    // process itself before the caller could gate on the JSON `severity` field.
    let tmp = TempDir::new("drift-exit-zero");
    git(&tmp, &["init", "-q"]);
    git(&tmp, &["config", "user.email", "t@t.co"]);
    git(&tmp, &["config", "user.name", "t"]);

    let init = spectra().arg("init").current_dir(&*tmp).output().unwrap();
    assert!(init.status.success(), "init failed: {init:?}");
    let new_change = spectra()
        .args(["new", "change", "aged-out"])
        .current_dir(&*tmp)
        .output()
        .unwrap();
    assert!(
        new_change.status.success(),
        "new change failed: {new_change:?}"
    );

    // A `created` date far in the past lands the Time dimension in the
    // "abandoned" bucket (score 4), which alone reaches `medium` severity.
    std::fs::write(
        tmp.join("openspec")
            .join("changes")
            .join("aged-out")
            .join(".openspec.yaml"),
        "schema: spec-driven\ncreated: 2020-01-01\n",
    )
    .unwrap();

    let out = spectra()
        .args(["drift", "aged-out", "--json"])
        .current_dir(&*tmp)
        .output()
        .unwrap();
    let stdout = String::from_utf8(out.stdout).unwrap();
    let report: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(
        report["severity"], "medium",
        "test setup must actually produce a medium severity, got:\n{stdout}"
    );
    assert_eq!(
        out.status.code(),
        Some(0),
        "drift must exit 0 on a medium-severity change, got {:?}; stderr:\n{}",
        out.status.code(),
        String::from_utf8_lossy(&out.stderr)
    );
}

/// Init a git repo + spectra project in `tmp` and create change `name`.
fn init_project_with_change(tmp: &Path, name: &str) {
    git(tmp, &["init", "-q"]);
    git(tmp, &["config", "user.email", "t@t.co"]);
    git(tmp, &["config", "user.name", "t"]);
    let init = spectra().arg("init").current_dir(tmp).output().unwrap();
    assert!(init.status.success(), "init failed: {init:?}");
    let nc = spectra()
        .args(["new", "change", name])
        .current_dir(tmp)
        .output()
        .unwrap();
    assert!(nc.status.success(), "new change failed: {nc:?}");
}

#[test]
fn validate_accepts_a_well_formed_nested_capability_delta() {
    // The nested `specs/<Epic>/<Feature>/spec.md` layout OSS reports as "no
    // deltas found"; validate must traverse it and pass a good delta -- exit 0.
    let tmp = TempDir::new("validate-nested-ok");
    init_project_with_change(&tmp, "billing");
    let cap = tmp
        .join("openspec")
        .join("changes")
        .join("billing")
        .join("specs")
        .join("Billing")
        .join("Invoices");
    std::fs::create_dir_all(&cap).unwrap();
    std::fs::write(
        cap.join("spec.md"),
        "## ADDED Requirements\n\n\
         ### Requirement: Invoice export\n\n\
         The system SHALL export invoices as PDF.\n\n\
         #### Scenario: Export succeeds\n\n\
         - **WHEN** a user requests a PDF\n\
         - **THEN** a PDF is produced\n",
    )
    .unwrap();

    let out = spectra()
        .args(["validate", "--changes", "--strict", "--json"])
        .current_dir(&*tmp)
        .output()
        .unwrap();
    let stdout = String::from_utf8(out.stdout).unwrap();
    let report: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(report["summary"]["totals"]["failed"], 0, "got:\n{stdout}");
    assert_eq!(report["items"][0]["id"], "billing");
    assert_eq!(report["items"][0]["valid"], true);
    assert_eq!(
        out.status.code(),
        Some(0),
        "a valid change must exit 0; stderr:\n{}",
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn validate_strict_fails_and_exits_nonzero_on_a_bad_delta() {
    let tmp = TempDir::new("validate-bad");
    init_project_with_change(&tmp, "feat");
    let cap = tmp
        .join("openspec")
        .join("changes")
        .join("feat")
        .join("specs")
        .join("auth");
    std::fs::create_dir_all(&cap).unwrap();
    // A requirement with neither a normative keyword nor a scenario.
    std::fs::write(
        cap.join("spec.md"),
        "## ADDED Requirements\n\n### Requirement: Login\n\nUsers can log in.\n",
    )
    .unwrap();

    let out = spectra()
        .args(["validate", "feat", "--strict", "--json"])
        .current_dir(&*tmp)
        .output()
        .unwrap();
    let stdout = String::from_utf8(out.stdout).unwrap();
    let report: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(report["summary"]["totals"]["failed"], 1, "got:\n{stdout}");
    assert_eq!(report["items"][0]["valid"], false);
    assert_eq!(report["items"][0]["issues"][0]["level"], "ERROR");
    assert_eq!(
        out.status.code(),
        Some(1),
        "an invalid change must exit 1 (gate semantics); stderr:\n{}",
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn validate_nonstrict_passes_a_structurally_present_delta() {
    // The same bad delta as above (no SHALL, no scenario) is structurally a
    // delta, so a non-strict run gates only on structure and exits 0.
    let tmp = TempDir::new("validate-nonstrict");
    init_project_with_change(&tmp, "feat");
    let cap = tmp
        .join("openspec")
        .join("changes")
        .join("feat")
        .join("specs")
        .join("auth");
    std::fs::create_dir_all(&cap).unwrap();
    std::fs::write(
        cap.join("spec.md"),
        "## ADDED Requirements\n\n### Requirement: Login\n\nUsers can log in.\n",
    )
    .unwrap();

    let out = spectra()
        .args(["validate", "feat", "--json"])
        .current_dir(&*tmp)
        .output()
        .unwrap();
    assert_eq!(out.status.code(), Some(0));
    let report: serde_json::Value =
        serde_json::from_str(&String::from_utf8(out.stdout).unwrap()).unwrap();
    assert_eq!(report["items"][0]["valid"], true);
}

#[test]
fn validate_errors_when_change_has_no_delta() {
    let tmp = TempDir::new("validate-nodelta");
    init_project_with_change(&tmp, "feat");
    // `new change` creates metadata only, so there are no specs/ deltas.

    let out = spectra()
        .args(["validate", "feat", "--json"])
        .current_dir(&*tmp)
        .output()
        .unwrap();
    assert_eq!(out.status.code(), Some(1));
    let report: serde_json::Value =
        serde_json::from_str(&String::from_utf8(out.stdout).unwrap()).unwrap();
    assert_eq!(report["items"][0]["valid"], false);
    let msg = report["items"][0]["issues"][0]["message"].as_str().unwrap();
    assert!(msg.contains("at least one delta"), "got: {msg}");
}

#[test]
fn validate_errors_change_not_found_for_a_nonexistent_explicit_name() {
    // Regression (mob review): an explicit typo'd / archived name must report
    // "Change '<name>' not found." (like `archive`), not a misleading
    // "must contain at least one delta" validation failure.
    let tmp = TempDir::new("validate-notfound");
    init_project_with_change(&tmp, "real-change");

    let out = spectra()
        .args(["validate", "does-not-exist", "--json"])
        .current_dir(&*tmp)
        .output()
        .unwrap();
    assert_eq!(
        out.status.code(),
        Some(1),
        "a missing change must exit 1 via the error path"
    );
    let stderr = String::from_utf8(out.stderr).unwrap();
    assert!(
        stderr.contains("Change 'does-not-exist' not found."),
        "expected not-found error, got stderr:\n{stderr}\nstdout:\n{}",
        String::from_utf8_lossy(&out.stdout)
    );
    // Must be the error path, not a JSON validation report.
    assert!(
        String::from_utf8(out.stdout).unwrap().trim().is_empty(),
        "no JSON report should be emitted for a not-found change"
    );
}

#[test]
fn list_help_does_not_mention_changes_as_unimplemented() {
    let out = spectra().args(["list", "--help"]).output().unwrap();
    assert!(out.status.success());
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(!stdout.contains("not yet implemented"));
}

/// The marker path spelled out literally, on purpose: every other assertion
/// in this file resolves it through `change::in_progress_marker_path`, the
/// same production helper that writes it, so those assertions only prove
/// "the file is wherever the code put it". Renaming the suffix or moving the
/// directory left the whole suite green until this literal landed here.
fn in_progress_marker(root: &Path, name: &str) -> PathBuf {
    root.join(".spectra")
        .join("changes")
        .join(format!("{name}.in-progress"))
}

#[test]
fn in_progress_add_marks_an_existing_change_without_output() {
    let tmp = TempDir::new("in-progress-existing");
    init_project_with_change(&tmp, "shipping");

    let out = spectra()
        .args(["in-progress", "add", "shipping"])
        .current_dir(&*tmp)
        .output()
        .unwrap();

    assert_eq!(
        out.status.code(),
        Some(0),
        "in-progress add failed: {out:?}"
    );
    assert!(out.stdout.is_empty(), "stdout must be exactly empty");
    // Exit 0 with empty stdout is also what doing nothing at all looks like:
    // without this the whole CLI-to-core wiring can be deleted and every test
    // still passes.
    assert!(
        in_progress_marker(&tmp, "shipping").is_file(),
        "marker must land at the documented .spectra/changes/<name>.in-progress"
    );

    // Idempotency at the CLI layer, not just in the core unit tests.
    let again = spectra()
        .args(["in-progress", "add", "shipping"])
        .current_dir(&*tmp)
        .output()
        .unwrap();
    assert_eq!(
        again.status.code(),
        Some(0),
        "repeated in-progress add failed: {again:?}"
    );
    assert!(again.stdout.is_empty(), "stdout must be exactly empty");
    assert!(
        in_progress_marker(&tmp, "shipping").is_file(),
        "marker must survive a repeated add"
    );
}

#[test]
fn in_progress_add_accepts_a_ghost_change() {
    let tmp = TempDir::new("in-progress-ghost");
    init_project_with_change(&tmp, "real-change");

    let out = spectra()
        .args(["in-progress", "add", "ghost-change"])
        .current_dir(&*tmp)
        .output()
        .unwrap();

    assert_eq!(
        out.status.code(),
        Some(0),
        "ghost-change add failed: {out:?}"
    );
    // The ghost marker is written, not skipped -- exit 0 alone cannot tell
    // "recorded a marker for a change that does not exist" (the oracle's
    // behavior) apart from "silently did nothing".
    assert!(
        in_progress_marker(&tmp, "ghost-change").is_file(),
        "ghost marker must be written despite the change not existing"
    );
    assert!(
        !tmp.join("openspec")
            .join("changes")
            .join("ghost-change")
            .exists(),
        "the change itself must not be created as a side effect"
    );
}

#[test]
fn in_progress_marker_does_not_change_list_or_status_output() {
    let tmp = TempDir::new("in-progress-write-only");
    init_project_with_change(&tmp, "shipping");

    // The fixture MUST report `"status": "done"` before the marker is added.
    // `list_change_items` derives `"in-progress"` for any change without a
    // fully-completed tasks.md (main.rs: `total > 0 && done == total`), and a
    // fresh `new change` has no tasks.md at all -- so on the default fixture
    // the pre-add JSON already says "in-progress", and a mutation wiring the
    // marker into that field produces byte-identical output. The lock would
    // silently prove nothing. Completing the tasks is what gives the two
    // states different bytes, and therefore gives this assertion teeth.
    std::fs::write(
        tmp.join("openspec")
            .join("changes")
            .join("shipping")
            .join("tasks.md"),
        "# Tasks\n\n- [x] 1. done\n",
    )
    .unwrap();
    let baseline = spectra()
        .args(["list", "--json"])
        .current_dir(&*tmp)
        .output()
        .unwrap();
    assert!(
        String::from_utf8_lossy(&baseline.stdout).contains("\"status\": \"done\""),
        "fixture precondition: list --json must read \"done\" before the add, \
         else a marker leak into that field is invisible: {baseline:?}"
    );

    // `list --json` carries a *derived* task status that is also spelled
    // "in-progress" (main.rs `list_change_items`). It is unrelated to this
    // marker, and it is the surface most likely to be wired to it by mistake
    // -- so it has to be in the lock, not just the human-readable listing.
    // `analyze` is here because CHANGELOG names it among the locked surfaces.
    let read_paths: [&[&str]; 6] = [
        &["list"],
        &["list", "--json"],
        &["list", "--parked"],
        &["status"],
        &["analyze", "shipping"],
        &["show", "shipping"],
    ];

    let capture = |args: &[&str]| {
        let out = spectra().args(args).current_dir(&*tmp).output().unwrap();
        assert!(out.status.success(), "{args:?} failed: {out:?}");
        out.stdout
    };

    let before: Vec<Vec<u8>> = read_paths.iter().map(|a| capture(a)).collect();

    let add = spectra()
        .args(["in-progress", "add", "shipping"])
        .current_dir(&*tmp)
        .output()
        .unwrap();
    assert!(add.status.success(), "in-progress add failed: {add:?}");
    assert!(
        in_progress_marker(&tmp, "shipping").is_file(),
        "marker must exist, else this lock proves nothing"
    );

    for (args, expected) in read_paths.iter().zip(before) {
        assert_eq!(
            capture(args),
            expected,
            "{args:?} output changed after in-progress add; the marker must stay write-only"
        );
    }
}

#[test]
fn in_progress_add_rejects_json_output() {
    let tmp = TempDir::new("in-progress-json");
    init_project_with_change(&tmp, "shipping");

    let out = spectra()
        .args(["in-progress", "add", "shipping", "--json"])
        .current_dir(&*tmp)
        .output()
        .unwrap();

    assert_eq!(out.status.code(), Some(2));
}

#[test]
fn in_progress_rejects_remove_subcommand() {
    // Runs in a TempDir like its siblings: clap rejects `remove` before any
    // root resolution today, but this test exists precisely for the day a
    // removal subcommand is added, and it must not touch the real checkout then.
    let tmp = TempDir::new("in-progress-remove");

    let out = spectra()
        .args(["in-progress", "remove", "shipping"])
        .current_dir(&*tmp)
        .output()
        .unwrap();

    assert_eq!(out.status.code(), Some(2));
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("remove"),
        "clap must name the rejected subcommand, else this passes for any error: {stderr}"
    );
}

#[test]
fn in_progress_add_requires_an_initialized_project() {
    let tmp = TempDir::new("in-progress-uninitialized");

    let out = spectra()
        .args(["in-progress", "add", "shipping"])
        .current_dir(&*tmp)
        .output()
        .unwrap();

    assert_eq!(out.status.code(), Some(1));
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("Not initialized"),
        "unexpected stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}