spectra-cli 0.2.1

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
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
//! OpenSpectra CLI: `init`, `drift`, `validate`, `list`, `show`, `park`,
//! `unpark`, `new change`, `task done`, `archive`.

use std::io::IsTerminal;
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use serde_json::json;

use spectra_core::{change, config::Config, drift, spec};

#[derive(Parser, Debug)]
#[command(
    name = "spectra",
    version,
    about = "Open-source Spectra spec-driven CLI"
)]
struct Cli {
    /// Disable colored output (also respects the NO_COLOR env var).
    #[arg(long, global = true)]
    no_color: bool,
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand, Debug)]
enum Command {
    /// Scaffold a fresh project: `.spectra.yaml`, `<spec_dir>/{changes,specs}/`,
    /// and a `.spectra/` entry in `.gitignore`. Every other command requires
    /// this to have run first.
    Init {
        #[arg(long)]
        adopt: bool,
        #[arg(long)]
        json: bool,
    },
    /// Detect drift between a change and the current codebase state.
    Drift {
        /// Change name (auto-detects if only one exists).
        change: Option<String>,
        /// Output as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Validate changes against the OpenSpec structural rules (a change needs
    /// at least one requirement delta; with --strict, each ADDED/MODIFIED
    /// requirement also needs a normative SHALL/MUST and a `#### Scenario:`).
    /// Unlike `drift`, this is a pass/fail gate: it exits non-zero when any
    /// change is invalid.
    Validate {
        /// Change name to validate (auto-detects if only one active change
        /// exists). Ignored when --changes is given.
        change: Option<String>,
        /// Validate every active change instead of a single one.
        #[arg(long, conflicts_with = "change")]
        changes: bool,
        /// Escalate content-quality findings (missing SHALL/MUST or missing
        /// scenario) from ignored to hard errors.
        #[arg(long)]
        strict: bool,
        #[arg(long)]
        json: bool,
    },
    /// List active changes (or specs with --specs, or parked changes with --parked).
    List {
        /// List active changes explicitly (the default when no filter flag
        /// is given; mutually exclusive with --specs/--parked).
        #[arg(long, conflicts_with_all = ["specs", "parked"])]
        changes: bool,
        /// List specs instead of changes.
        #[arg(long, conflicts_with = "parked")]
        specs: bool,
        /// List parked changes instead of active ones.
        #[arg(long)]
        parked: bool,
        #[arg(long)]
        json: bool,
    },
    /// Show a change's proposal, or a spec's content if the name isn't a change.
    Show {
        /// Change or spec name to show.
        item: String,
        #[arg(long)]
        json: bool,
    },
    /// Park a change (mark it on hold, excluding it from the active listing).
    Park {
        /// Change name to park.
        change: String,
        #[arg(long)]
        json: bool,
    },
    /// Unpark a change (resume it from a parked state).
    Unpark {
        /// Change name to unpark.
        change: String,
        #[arg(long)]
        json: bool,
    },
    /// Scaffold a new change (currently the only `new` target).
    New {
        #[command(subcommand)]
        target: NewTarget,
    },
    /// Task operations (currently the only `task` target).
    Task {
        #[command(subcommand)]
        target: TaskTarget,
    },
    /// Archive a completed change (move it to `changes/archive/<date>-<name>`
    /// and apply its added spec requirements, unless --skip-specs).
    Archive {
        /// Change to archive (auto-detects if only one active change exists).
        change: Option<String>,
        /// Skip applying the change's spec deltas to the canonical specs.
        #[arg(long)]
        skip_specs: bool,
        /// Mark all incomplete tasks as complete before archiving.
        #[arg(long)]
        mark_tasks_complete: bool,
    },
}

#[derive(Subcommand, Debug)]
enum NewTarget {
    /// Scaffold a new change directory (.openspec.yaml, proposal.md,
    /// design.md, tasks.md, and, when run inside a git repo with at least
    /// one commit, a baseline git SHA).
    Change {
        /// Name for the new change (kebab-case, e.g. 'add-search-filter').
        name: String,
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand, Debug)]
enum TaskTarget {
    /// Mark a task as done and record touched files.
    Done {
        /// Task ID (1-based sequential index across all tasks.md checkboxes).
        task_id: String,
        /// Change name (auto-detects if only one active change exists).
        #[arg(long)]
        change: Option<String>,
        #[arg(long)]
        json: bool,
    },
}

/// Walk up from `start` to find the project root (dir containing `.spectra.yaml`),
/// falling back to `start` itself.
fn find_root(start: &Path) -> PathBuf {
    let mut cur = Some(start);
    while let Some(dir) = cur {
        if dir.join(".spectra.yaml").exists() {
            return dir.to_path_buf();
        }
        cur = dir.parent();
    }
    start.to_path_buf()
}

fn require_initialized(root: &Path) -> Result<Config> {
    if !Config::is_initialized(root) {
        anyhow::bail!("Not initialized. Run 'spectra init' first.");
    }
    Config::load(root)
}

/// `--json` shape for `init`: pinned here (rather than inlined in
/// `cmd_init`), matching `show_json`/`park_status_json`/`new_change_json`.
fn init_json(outcome: &spectra_core::init::InitOutcome) -> serde_json::Value {
    json!({
        "root": outcome.root.to_string_lossy(),
        "spec_dir": outcome.spec_dir,
        "adopted": outcome.adopted,
        "gitignore_updated": outcome.gitignore_updated,
    })
}

fn cmd_init(root: &Path, adopt: bool, as_json: bool) -> Result<i32> {
    let outcome = spectra_core::init::init_with_options(root, adopt)?;
    if as_json {
        println!("{}", serde_json::to_string_pretty(&init_json(&outcome))?);
    } else if outcome.adopted {
        println!(
            "Adopted existing spectra project in {} (spec_dir: {}).",
            outcome.root.display(),
            outcome.spec_dir
        );
    } else {
        println!(
            "Initialized spectra project in {} (spec_dir: {}).",
            outcome.root.display(),
            outcome.spec_dir
        );
        if outcome.gitignore_updated {
            println!("Added '.spectra/' to .gitignore.");
        }
    }
    Ok(0)
}

fn cmd_drift(
    cfg: &Config,
    change_name: Option<&str>,
    as_json: bool,
    use_color: bool,
) -> Result<i32> {
    let name = change::resolve(cfg, change_name)?;
    let change = change::load(cfg, &name)?;
    let report = drift::analyze(cfg, &change)?;

    if as_json {
        println!("{}", serde_json::to_string_pretty(&report)?);
    } else {
        print_human(&report, use_color);
    }
    Ok(report.exit_code())
}

fn cmd_validate(
    cfg: &Config,
    change_name: Option<&str>,
    all_changes: bool,
    strict: bool,
    as_json: bool,
) -> Result<i32> {
    let report = if all_changes {
        spectra_core::validate::validate_all_active(cfg, strict)?
    } else {
        // A single named (or auto-detected) change. `resolve` yields the
        // reference CLI's "no active changes" / "multiple changes" errors on
        // the auto-detect (None) path, but passes an explicit name through
        // verbatim -- so verify it actually exists here, otherwise a typo'd,
        // parked, or archived name would be silently reported as a bogus "no
        // delta" validation failure instead of "Change '<name>' not found."
        // (matching `archive`).
        let name = change::resolve(cfg, change_name)?;
        if change::try_load(cfg, &name)?.is_none() {
            anyhow::bail!("Change '{name}' not found.");
        }
        spectra_core::validate::build_report(cfg, std::slice::from_ref(&name), strict)?
    };

    if as_json {
        println!("{}", serde_json::to_string_pretty(&report)?);
    } else {
        print_validate_human(&report);
    }
    // Gate semantics (distinct from `drift`, which always exits 0): a failed
    // validation exits non-zero so `validate` can back a CI check directly.
    Ok(i32::from(report.any_failed()))
}

fn print_validate_human(report: &spectra_core::validate::ValidateReport) {
    for item in &report.items {
        if item.valid {
            println!("{:<45} OK", item.id);
        } else {
            let n = item.issues.len();
            let noun = if n == 1 { "issue" } else { "issues" };
            println!("{:<45} FAIL ({n} {noun})", item.id);
            for issue in &item.issues {
                println!("  {} {}: {}", issue.level, issue.path, issue.message);
            }
        }
    }
    let t = &report.summary.totals;
    println!(
        "\n{} passed, {} failed ({} total).",
        t.passed, t.failed, t.total
    );
}

/// Whether to emit ANSI color codes: the `--no-color` flag and the `NO_COLOR`
/// env var (https://no-color.org — "when present, **regardless of its
/// value**") both disable it; otherwise color is only emitted when stdout is
/// a terminal (never when piped/redirected).
fn color_enabled(no_color: bool) -> bool {
    color_enabled_from(
        no_color,
        std::env::var_os("NO_COLOR").is_some(),
        std::io::stdout().is_terminal(),
    )
}

/// Pure precedence logic behind [`color_enabled`], split out so all
/// flag/env/TTY combinations are unit-testable without mutating real process
/// env vars or stdout (both of which would be flaky under parallel tests).
fn color_enabled_from(no_color: bool, no_color_env_set: bool, stdout_is_tty: bool) -> bool {
    !no_color && !no_color_env_set && stdout_is_tty
}

/// Wrap `text` in the given SGR color code (e.g. `"31"` for red) when
/// `enabled`, otherwise return it unchanged.
fn colorize(text: &str, sgr_code: &str, enabled: bool) -> String {
    if enabled {
        format!("\x1b[{sgr_code}m{text}\x1b[0m")
    } else {
        text.to_string()
    }
}

/// SGR color code for a drift severity: green for light, yellow for medium,
/// red for heavy (and any other/unknown value, treated as the worst case).
fn severity_sgr_code(severity: &str) -> &'static str {
    match severity {
        "light" => "32",
        "medium" => "33",
        _ => "31",
    }
}

/// The severity-colored conclusion sentence, composed here (rather than
/// inline in `print_human`) so the `colorize`/`severity_sgr_code` wiring
/// itself — not just each function in isolation — is unit-testable.
fn conclusion_line(severity: &str, use_color: bool) -> String {
    let conclusion = match severity {
        "light" => "Drift is minor — you can start work directly.",
        "medium" => "The change has drifted moderately; refresh the plan before implementing.",
        _ => "The change has drifted heavily; the old plan likely no longer fits — archive or restart.",
    };
    colorize(conclusion, severity_sgr_code(severity), use_color)
}

/// Conclusion-first human report (mirrors the reference layout: plain-language
/// next step, then a scorecard, then non-empty technical detail).
fn print_human(r: &drift::DriftReport, use_color: bool) {
    println!("## Drift Report: {}\n", r.change_id);
    println!("{}\n", conclusion_line(&r.severity, use_color));

    let dim = |k: &str| r.dimensions.iter().find(|d| format!("{:?}", d.kind) == k);
    let time = dim("Time").map(|d| d.status.as_str()).unwrap_or("-");
    let design = if r.broken_anchors.is_empty() {
        "No broken references".to_string()
    } else {
        format!("{} broken", r.broken_anchors.len())
    };
    let tasks = if r.tasks_blocked_external.is_empty() && r.tasks_maybe_resolved.is_empty() {
        "No task collisions".to_string()
    } else {
        format!(
            "{} blocked, {} maybe-done",
            r.tasks_blocked_external.len(),
            r.tasks_maybe_resolved.len()
        )
    };

    println!("| Dimension         | Status                                |");
    println!("|-------------------|---------------------------------------|");
    println!("| Time              | {time:<37} |");
    println!("| Design references | {design:<37} |");
    println!("| Pending tasks     | {tasks:<37} |");
    println!(
        "| Overall           | {:<37} |",
        format!("{}, total score {}", r.severity, r.total_score)
    );

    println!("\n### Recommendation\nRun `{}`.", r.primary_recommendation);

    if !r.broken_anchors.is_empty() {
        println!("\n### Broken design references");
        for a in &r.broken_anchors {
            println!("- `{}` ({}) — {}", a.anchor, a.category, a.reason);
        }
    }
}

fn list_change_items(cfg: &Config, want_parked: bool) -> Result<Vec<serde_json::Value>> {
    let names = if want_parked {
        change::list_parked(cfg)
    } else {
        change::list_active(cfg)
    };
    let mut items = Vec::new();
    for name in &names {
        let ch = change::load(cfg, name)?;
        let (done, total) = task_counts(&ch.tasks_md());
        let status = if total > 0 && done == total {
            "done"
        } else {
            "in-progress"
        };
        let summary = first_line(&ch.proposal_md());
        items.push(json!({
            "name": name,
            "status": status,
            "completedTasks": done,
            "totalTasks": total,
            "summary": summary,
        }));
    }
    Ok(items)
}

fn cmd_list(cfg: &Config, want_specs: bool, want_parked: bool, as_json: bool) -> Result<i32> {
    // clap rejects --specs with --parked (they're `conflicts_with`), so at
    // most one of the two is ever true here.
    if want_specs {
        return cmd_list_specs(cfg, as_json);
    }
    let items = list_change_items(cfg, want_parked)?;
    if as_json {
        println!(
            "{}",
            serde_json::to_string_pretty(&json!({ "changes": items }))?
        );
    } else if items.is_empty() {
        println!(
            "{}",
            if want_parked {
                "No parked changes."
            } else {
                "No active changes."
            }
        );
    } else {
        for it in &items {
            println!(
                "{:<45} {}/{} {}",
                it["name"].as_str().unwrap_or(""),
                it["completedTasks"],
                it["totalTasks"],
                it["status"].as_str().unwrap_or("")
            );
        }
    }
    Ok(0)
}

fn list_specs_items(cfg: &Config) -> Result<Vec<serde_json::Value>> {
    let names = spec::list(cfg)?;
    let mut items = Vec::new();
    for name in &names {
        // `spec::list` already confirmed `spec.md` exists for each name; skip
        // the redundant re-stat that `spec::load` would perform.
        let summary = first_line(&cfg.specs_dir().join(name).join("spec.md"));
        items.push(json!({ "name": name, "summary": summary }));
    }
    Ok(items)
}

fn cmd_list_specs(cfg: &Config, as_json: bool) -> Result<i32> {
    let items = list_specs_items(cfg)?;
    if as_json {
        println!(
            "{}",
            serde_json::to_string_pretty(&json!({ "specs": items }))?
        );
    } else if items.is_empty() {
        println!("No specs.");
    } else {
        for it in &items {
            println!(
                "{:<45} {}",
                it["name"].as_str().unwrap_or(""),
                it["summary"].as_str().unwrap_or("")
            );
        }
    }
    Ok(0)
}

#[derive(Debug)]
enum ShowContent {
    Proposal(String),
    Spec(String),
}

/// Resolve `item` to a change's proposal or a spec's content. A change name
/// takes priority (existing, regression-safe behavior); `change::try_load`/
/// `spec::try_load` distinguish "genuinely doesn't exist" from a real I/O
/// error while checking, so neither is misread as "not found."
fn resolve_show_content(cfg: &Config, item: &str) -> Result<ShowContent> {
    if let Some(ch) = change::try_load(cfg, item)? {
        return Ok(ShowContent::Proposal(read_show_content(&ch.proposal_md())?));
    }
    if let Some(sp) = spec::try_load(cfg, item)? {
        return Ok(ShowContent::Spec(read_show_content(&sp.spec_md())?));
    }
    anyhow::bail!("'{item}' is not a known change or spec")
}

/// Read `path`'s content for `show`. Unlike `first_line` (used for `list`'s
/// secondary summary column, where a warn-and-degrade is defensible because
/// other fields still carry useful data), the content read here *is* the
/// entire requested output — so besides the benign `NotFound` case (a
/// genuinely bodyless change/spec), any other I/O failure propagates instead
/// of silently printing empty content with a success exit code.
fn read_show_content(path: &Path) -> Result<String> {
    match std::fs::read_to_string(path) {
        Ok(s) => Ok(s),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(String::new()),
        Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
    }
}

fn show_json(item: &str, content: &ShowContent) -> serde_json::Value {
    match content {
        ShowContent::Proposal(text) => json!({ "name": item, "proposal": text }),
        ShowContent::Spec(text) => json!({ "name": item, "spec": text }),
    }
}

fn cmd_show(cfg: &Config, item: &str, as_json: bool) -> Result<i32> {
    let content = resolve_show_content(cfg, item)?;
    if as_json {
        println!(
            "{}",
            serde_json::to_string_pretty(&show_json(item, &content))?
        );
    } else {
        let (ShowContent::Proposal(text) | ShowContent::Spec(text)) = &content;
        print!("{text}");
    }
    Ok(0)
}

/// The exact wrapper shape is the documented `--json` contract for
/// `park`/`unpark`; pin it here so a copy/paste between the two (forgetting
/// to flip `parked`) doesn't ship silently.
fn park_status_json(name: &str, parked: bool) -> serde_json::Value {
    json!({ "name": name, "parked": parked })
}

fn cmd_park(cfg: &Config, name: &str, as_json: bool) -> Result<i32> {
    change::park(cfg, name)?;
    if as_json {
        println!(
            "{}",
            serde_json::to_string_pretty(&park_status_json(name, true))?
        );
    } else {
        println!("Parked '{name}'.");
    }
    Ok(0)
}

fn cmd_unpark(cfg: &Config, name: &str, as_json: bool) -> Result<i32> {
    change::unpark(cfg, name)?;
    if as_json {
        println!(
            "{}",
            serde_json::to_string_pretty(&park_status_json(name, false))?
        );
    } else {
        println!("Unparked '{name}'.");
    }
    Ok(0)
}

/// `--json` shape for `new change`: pinned here (rather than inlined in
/// `cmd_new_change`) so a rename/typo doesn't ship silently, matching
/// `show_json`/`park_status_json`. Renders `dir` via `to_string_lossy`
/// instead of serializing the `PathBuf` directly: `json!`'s `PathBuf`
/// support requires valid UTF-8 and panics (not a recoverable error) on a
/// path that isn't, which `to_string_lossy` avoids for that rare case.
fn new_change_json(ch: &change::Change) -> serde_json::Value {
    json!({
        "name": ch.name,
        "dir": ch.dir.to_string_lossy(),
        "started_sha": ch.started_sha,
    })
}

fn cmd_new_change(cfg: &Config, name: &str, as_json: bool) -> Result<i32> {
    let ch = change::create(cfg, name)?;
    if as_json {
        println!("{}", serde_json::to_string_pretty(&new_change_json(&ch))?);
    } else {
        println!("Created change '{}' in {}.", ch.name, ch.dir.display());
        if ch.started_sha.is_none() {
            eprintln!(
                "note: couldn't determine a git baseline for this change; \
                 task-blocked detection will be skipped for it."
            );
        }
    }
    Ok(0)
}

/// `--json` shape for `task done`, reverse-engineered against
/// `/Applications/Spectra.app` v2.3.1: `{"change","status","task_desc","task_id"}`,
/// `task_id` rendered as a string (matching the reference CLI exactly).
fn task_done_json(outcome: &change::TaskDoneOutcome) -> serde_json::Value {
    json!({
        "change": outcome.change,
        "status": "done",
        "task_desc": outcome.task_desc,
        "task_id": outcome.task_id.to_string(),
    })
}

/// Parses the raw `<TASK_ID>` CLI argument, producing the reference CLI's
/// exact error wording on a non-numeric input. Pulled out so this check
/// (which runs before any change lookup) is unit-testable without a `Config`.
fn parse_task_id(raw: &str) -> Result<usize> {
    raw.parse()
        .map_err(|_| anyhow::anyhow!("Invalid task ID '{raw}': must be a number"))
}

fn cmd_task_done(
    cfg: &Config,
    change_name: Option<&str>,
    task_id_raw: &str,
    as_json: bool,
) -> Result<i32> {
    let task_id = parse_task_id(task_id_raw)?;
    let name = change::resolve(cfg, change_name)?;
    let outcome = change::mark_task_done(cfg, &name, task_id)?;
    if as_json {
        println!(
            "{}",
            serde_json::to_string_pretty(&task_done_json(&outcome))?
        );
    } else {
        println!(
            "Task {} marked as done: {}",
            outcome.task_id, outcome.task_desc
        );
    }
    Ok(0)
}

fn cmd_archive(
    cfg: &Config,
    change_name: Option<&str>,
    skip_specs: bool,
    mark_tasks_complete: bool,
) -> Result<i32> {
    let name = change::resolve(cfg, change_name)?;
    let outcome = spectra_core::archive::archive(cfg, &name, skip_specs, mark_tasks_complete)?;
    println!(
        "Archived '{}' as '{}'.",
        outcome.name, outcome.archived_name
    );
    for applied in &outcome.specs_applied {
        println!(
            "Specs applied: {} (added: {}, modified: {}, removed: {}, renamed: {})",
            applied.capability, applied.added, applied.modified, applied.removed, applied.renamed
        );
    }
    Ok(0)
}

fn task_counts(tasks_md: &Path) -> (usize, usize) {
    let Ok(text) = std::fs::read_to_string(tasks_md) else {
        return (0, 0);
    };
    let tasks = spectra_core::tasks::parse(&text);
    (tasks.iter().filter(|t| t.done).count(), tasks.len())
}

fn first_line(path: &Path) -> String {
    match std::fs::read_to_string(path) {
        Ok(s) => s
            .lines()
            .find(|l| !l.trim().is_empty())
            .map(str::to_string)
            .unwrap_or_default(),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => {
            eprintln!("warning: reading {}: {e}", path.display());
            String::new()
        }
    }
}

fn run() -> Result<i32> {
    let cli = Cli::parse();
    let use_color = color_enabled(cli.no_color);
    let cwd = std::env::current_dir().context("getting current directory")?;
    let root = find_root(&cwd);

    match &cli.command {
        Command::Init { adopt, json } => cmd_init(&root, *adopt, *json),
        Command::Drift { change, json } => {
            let cfg = require_initialized(&root)?;
            cmd_drift(&cfg, change.as_deref(), *json, use_color)
        }
        Command::Validate {
            change,
            changes,
            strict,
            json,
        } => {
            let cfg = require_initialized(&root)?;
            cmd_validate(&cfg, change.as_deref(), *changes, *strict, *json)
        }
        Command::List {
            // `changes` is unused here on purpose: clap's `conflicts_with_all`
            // already rejects it alongside --specs/--parked, so whenever it's
            // true the other two are false and cmd_list's default branch
            // (active changes) already produces the same output -- see
            // design.md's US-002 section.
            changes: _,
            specs,
            parked,
            json,
        } => {
            let cfg = require_initialized(&root)?;
            cmd_list(&cfg, *specs, *parked, *json)
        }
        Command::Show { item, json } => {
            let cfg = require_initialized(&root)?;
            cmd_show(&cfg, item, *json)
        }
        Command::Park { change, json } => {
            let cfg = require_initialized(&root)?;
            cmd_park(&cfg, change, *json)
        }
        Command::Unpark { change, json } => {
            let cfg = require_initialized(&root)?;
            cmd_unpark(&cfg, change, *json)
        }
        Command::New { target } => match target {
            NewTarget::Change { name, json } => {
                let cfg = require_initialized(&root)?;
                cmd_new_change(&cfg, name, *json)
            }
        },
        Command::Task { target } => match target {
            TaskTarget::Done {
                task_id,
                change,
                json,
            } => {
                let cfg = require_initialized(&root)?;
                cmd_task_done(&cfg, change.as_deref(), task_id, *json)
            }
        },
        Command::Archive {
            change,
            skip_specs,
            mark_tasks_complete,
        } => {
            let cfg = require_initialized(&root)?;
            cmd_archive(&cfg, change.as_deref(), *skip_specs, *mark_tasks_complete)
        }
    }
}

fn main() -> ExitCode {
    match run() {
        Ok(code) => ExitCode::from(code as u8),
        Err(e) => {
            // The oracle exits 1 on operational errors (probed: "Change 'x'
            // not found." exits 1); successful drift always exits 0 regardless
            // of severity, so 1 is unambiguously "tool error".
            eprintln!("Error: {e:#}");
            ExitCode::from(1)
        }
    }
}

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

    #[test]
    fn color_enabled_from_only_true_when_nothing_disables_it() {
        assert!(color_enabled_from(false, false, true));
    }

    #[test]
    fn color_enabled_from_no_color_flag_wins_even_with_tty_and_no_env() {
        assert!(!color_enabled_from(true, false, true));
    }

    #[test]
    fn color_enabled_from_no_color_env_wins_even_without_flag() {
        assert!(!color_enabled_from(false, true, true));
    }

    #[test]
    fn color_enabled_from_false_when_not_a_tty_even_with_nothing_else_set() {
        assert!(!color_enabled_from(false, false, false));
    }

    #[test]
    fn colorize_wraps_text_in_sgr_codes_only_when_enabled() {
        assert_eq!(colorize("hi", "31", true), "\x1b[31mhi\x1b[0m");
        assert_eq!(colorize("hi", "31", false), "hi");
    }

    #[test]
    fn severity_sgr_code_maps_known_and_unknown_severities() {
        assert_eq!(severity_sgr_code("light"), "32");
        assert_eq!(severity_sgr_code("medium"), "33");
        assert_eq!(severity_sgr_code("heavy"), "31");
        assert_eq!(severity_sgr_code("anything-else"), "31");
    }

    #[test]
    fn conclusion_line_colors_by_severity_when_enabled() {
        assert_eq!(
            conclusion_line("light", true),
            "\x1b[32mDrift is minor — you can start work directly.\x1b[0m"
        );
        assert!(conclusion_line("light", false).starts_with("Drift is minor"));
        assert!(!conclusion_line("light", false).contains('\x1b'));
    }

    /// RAII guard for a per-test scratch directory: removes it on drop even
    /// when the test panics partway through (an assertion failure must not
    /// leak the directory).
    struct TempDir(PathBuf);

    impl TempDir {
        fn new() -> Self {
            // Nanosecond timestamps alone can collide between threads running
            // concurrently (observed in practice under `cargo test`'s default
            // parallel harness); an atomic counter guarantees uniqueness.
            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-test-{}-{}-{seq}",
                std::process::id(),
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap()
                    .as_nanos()
            ));
            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_conflicts_with_specs() {
        let err = Cli::try_parse_from(["spectra", "list", "--changes", "--specs"]).unwrap_err();
        assert_eq!(
            err.kind(),
            clap::error::ErrorKind::ArgumentConflict,
            "expected --changes/--specs to be rejected as conflicting, got: {err}"
        );
    }

    #[test]
    fn list_changes_flag_conflicts_with_parked() {
        let err = Cli::try_parse_from(["spectra", "list", "--changes", "--parked"]).unwrap_err();
        assert_eq!(
            err.kind(),
            clap::error::ErrorKind::ArgumentConflict,
            "expected --changes/--parked to be rejected as conflicting, got: {err}"
        );
    }

    #[test]
    fn list_changes_flag_parses_alone() {
        let cli = Cli::try_parse_from(["spectra", "list", "--changes"]).unwrap();
        match cli.command {
            Command::List {
                changes,
                specs,
                parked,
                json,
            } => {
                assert!(changes);
                assert!(!specs);
                assert!(!parked);
                assert!(!json);
            }
            _ => panic!("expected Command::List"),
        }
    }

    #[test]
    fn init_json_shape_matches_the_documented_contract() {
        let outcome = spectra_core::init::InitOutcome {
            root: PathBuf::from("/tmp/proj"),
            spec_dir: "openspec".to_string(),
            adopted: true,
            gitignore_updated: true,
        };
        let value = init_json(&outcome);
        assert_eq!(value["root"], "/tmp/proj");
        assert_eq!(value["spec_dir"], "openspec");
        assert_eq!(value["adopted"], true);
        assert_eq!(value["gitignore_updated"], true);
    }

    #[test]
    fn list_specs_items_shape_matches_specs_key_contract() {
        let tmp = TempDir::new();
        let cfg = Config {
            root: tmp.to_path_buf(),
            spec_dir: "openspec".to_string(),
            locale: None,
        };
        let auth_dir = cfg.specs_dir().join("auth");
        std::fs::create_dir_all(&auth_dir).unwrap();
        std::fs::write(auth_dir.join("spec.md"), "# Auth\nHandles login.\n").unwrap();

        let items = list_specs_items(&cfg).unwrap();
        assert_eq!(items.len(), 1);
        assert_eq!(items[0]["name"].as_str(), Some("auth"));
        assert_eq!(items[0]["summary"].as_str(), Some("# Auth"));

        // The exact wrapper key ("specs") is the documented --json contract;
        // pin it here so a typo doesn't ship silently.
        let wrapped = json!({ "specs": items });
        assert_eq!(wrapped["specs"][0]["name"], "auth");
    }

    #[test]
    fn list_specs_items_is_empty_when_no_specs_exist() {
        let tmp = TempDir::new();
        let cfg = Config {
            root: tmp.to_path_buf(),
            spec_dir: "openspec".to_string(),
            locale: None,
        };

        let items = list_specs_items(&cfg).unwrap();
        assert!(items.is_empty());
    }

    #[test]
    fn list_change_items_parked_flag_selects_parked_changes() {
        let tmp = TempDir::new();
        let cfg = Config {
            root: tmp.to_path_buf(),
            spec_dir: "openspec".to_string(),
            locale: None,
        };
        std::fs::create_dir_all(cfg.changes_dir().join("shipped")).unwrap();
        std::fs::write(
            cfg.changes_dir().join("shipped").join("proposal.md"),
            "# Shipped\n",
        )
        .unwrap();
        std::fs::create_dir_all(cfg.changes_dir().join("on-hold")).unwrap();
        std::fs::write(
            cfg.changes_dir().join("on-hold").join("proposal.md"),
            "# On hold\n",
        )
        .unwrap();
        std::fs::create_dir_all(tmp.join(".spectra").join("changes")).unwrap();
        std::fs::write(
            tmp.join(".spectra").join("changes").join("on-hold.parked"),
            "",
        )
        .unwrap();

        let active = list_change_items(&cfg, false).unwrap();
        assert_eq!(active.len(), 1);
        assert_eq!(active[0]["name"].as_str(), Some("shipped"));

        let parked = list_change_items(&cfg, true).unwrap();
        assert_eq!(parked.len(), 1);
        assert_eq!(parked[0]["name"].as_str(), Some("on-hold"));
    }

    #[test]
    fn list_change_items_parked_is_empty_when_none_parked() {
        let tmp = TempDir::new();
        let cfg = Config {
            root: tmp.to_path_buf(),
            spec_dir: "openspec".to_string(),
            locale: None,
        };
        std::fs::create_dir_all(cfg.changes_dir().join("shipped")).unwrap();
        std::fs::write(
            cfg.changes_dir().join("shipped").join("proposal.md"),
            "# Shipped\n",
        )
        .unwrap();

        assert!(list_change_items(&cfg, true).unwrap().is_empty());
    }

    #[test]
    fn resolve_show_content_prefers_change_over_spec() {
        let tmp = TempDir::new();
        let cfg = Config {
            root: tmp.to_path_buf(),
            spec_dir: "openspec".to_string(),
            locale: None,
        };
        std::fs::create_dir_all(cfg.changes_dir().join("auth")).unwrap();
        std::fs::write(
            cfg.changes_dir().join("auth").join("proposal.md"),
            "# Auth change\n",
        )
        .unwrap();
        std::fs::create_dir_all(cfg.specs_dir().join("auth")).unwrap();
        std::fs::write(
            cfg.specs_dir().join("auth").join("spec.md"),
            "# Auth spec\n",
        )
        .unwrap();

        match resolve_show_content(&cfg, "auth").unwrap() {
            ShowContent::Proposal(text) => assert_eq!(text, "# Auth change\n"),
            ShowContent::Spec(_) => panic!("expected the change to take priority over the spec"),
        }
    }

    #[test]
    fn resolve_show_content_falls_back_to_spec() {
        let tmp = TempDir::new();
        let cfg = Config {
            root: tmp.to_path_buf(),
            spec_dir: "openspec".to_string(),
            locale: None,
        };
        std::fs::create_dir_all(cfg.specs_dir().join("billing")).unwrap();
        std::fs::write(
            cfg.specs_dir().join("billing").join("spec.md"),
            "# Billing spec\n",
        )
        .unwrap();

        match resolve_show_content(&cfg, "billing").unwrap() {
            ShowContent::Spec(text) => assert_eq!(text, "# Billing spec\n"),
            ShowContent::Proposal(_) => panic!("expected a spec, not a change"),
        }
    }

    #[test]
    fn resolve_show_content_errors_when_neither_change_nor_spec() {
        let tmp = TempDir::new();
        let cfg = Config {
            root: tmp.to_path_buf(),
            spec_dir: "openspec".to_string(),
            locale: None,
        };

        assert!(resolve_show_content(&cfg, "ghost").is_err());
    }

    #[test]
    fn resolve_show_content_propagates_real_errors_instead_of_falling_back_to_spec() {
        let tmp = TempDir::new();
        let cfg = Config {
            root: tmp.to_path_buf(),
            spec_dir: "openspec".to_string(),
            locale: None,
        };
        std::fs::create_dir_all(cfg.changes_dir().join("broken")).unwrap();
        // A directory named `.openspec.yaml` makes `read_to_string` fail with
        // a real I/O error (cross-platform), unlike the benign
        // "no metadata file present" case `change::load` otherwise handles.
        std::fs::create_dir_all(cfg.changes_dir().join("broken").join(".openspec.yaml")).unwrap();
        // A same-named spec exists too, to prove the real error isn't
        // silently swallowed into a fallback.
        std::fs::create_dir_all(cfg.specs_dir().join("broken")).unwrap();
        std::fs::write(
            cfg.specs_dir().join("broken").join("spec.md"),
            "# Should not be used\n",
        )
        .unwrap();

        let err = resolve_show_content(&cfg, "broken").unwrap_err();
        assert!(!err.to_string().contains("is not a known change or spec"));
    }

    #[test]
    fn show_json_uses_proposal_key_for_change_content() {
        let value = show_json("my-change", &ShowContent::Proposal("hello".to_string()));
        assert_eq!(value["name"], "my-change");
        assert_eq!(value["proposal"], "hello");
        assert!(value.get("spec").is_none());
    }

    #[test]
    fn show_json_uses_spec_key_for_spec_content() {
        let value = show_json("auth", &ShowContent::Spec("# Auth\n".to_string()));
        assert_eq!(value["name"], "auth");
        assert_eq!(value["spec"], "# Auth\n");
        assert!(value.get("proposal").is_none());
    }

    #[test]
    fn park_status_json_reflects_parked_true_and_false() {
        assert_eq!(park_status_json("my-change", true)["parked"], true);
        assert_eq!(park_status_json("my-change", false)["parked"], false);
        assert_eq!(park_status_json("my-change", true)["name"], "my-change");
    }

    fn sample_change(dir: PathBuf, started_sha: Option<&str>) -> change::Change {
        change::Change {
            name: "my-change".to_string(),
            dir,
            metadata: Default::default(),
            started_sha: started_sha.map(str::to_string),
            parked: false,
        }
    }

    #[test]
    fn new_change_json_shape_matches_the_documented_contract() {
        let ch = sample_change(PathBuf::from("/tmp/changes/my-change"), Some("abc123"));
        let value = new_change_json(&ch);
        assert_eq!(value["name"], "my-change");
        assert_eq!(value["dir"], "/tmp/changes/my-change");
        assert_eq!(value["started_sha"], "abc123");
    }

    #[test]
    fn new_change_json_started_sha_is_null_when_absent() {
        let ch = sample_change(PathBuf::from("/tmp/changes/my-change"), None);
        assert!(new_change_json(&ch)["started_sha"].is_null());
    }

    #[cfg(unix)]
    #[test]
    fn new_change_json_does_not_panic_on_a_non_utf8_path() {
        use std::ffi::OsStr;
        use std::os::unix::ffi::OsStrExt;

        let dir = PathBuf::from(OsStr::from_bytes(b"/tmp/bad-\xFF-path"));
        let ch = sample_change(dir, None);
        // `json!` panics serializing a non-UTF-8 PathBuf directly; this must
        // not panic, since new_change_json renders `dir` via to_string_lossy.
        let value = new_change_json(&ch);
        assert!(value["dir"].as_str().unwrap().contains("bad-"));
    }

    #[test]
    fn task_done_json_shape_matches_the_documented_contract() {
        let outcome = change::TaskDoneOutcome {
            change: "my-change".to_string(),
            task_id: 3,
            task_desc: "do the thing".to_string(),
        };
        let value = task_done_json(&outcome);
        assert_eq!(value["change"], "my-change");
        assert_eq!(value["status"], "done");
        assert_eq!(value["task_desc"], "do the thing");
        // Matches the reference CLI: task_id is a string, not a number.
        assert_eq!(value["task_id"], "3");
    }

    #[test]
    fn task_done_json_serializes_keys_in_alphabetical_order() {
        // Relies on serde_json's default Value::Map being a BTreeMap (the
        // "preserve_order" feature isn't enabled) -- pinned here so enabling
        // that feature later would fail this test instead of silently
        // changing the --json key order documented as oracle-matching.
        let outcome = change::TaskDoneOutcome {
            change: "my-change".to_string(),
            task_id: 3,
            task_desc: "do the thing".to_string(),
        };
        let serialized = serde_json::to_string(&task_done_json(&outcome)).unwrap();
        assert_eq!(
            serialized,
            r#"{"change":"my-change","status":"done","task_desc":"do the thing","task_id":"3"}"#
        );
    }

    #[test]
    fn parse_task_id_accepts_a_valid_number() {
        assert_eq!(parse_task_id("3").unwrap(), 3);
    }

    #[test]
    fn parse_task_id_rejects_non_numeric_input() {
        let err = parse_task_id("abc").unwrap_err();
        assert_eq!(err.to_string(), "Invalid task ID 'abc': must be a number");
    }

    #[test]
    fn parse_task_id_rejects_negative_numbers() {
        let err = parse_task_id("-1").unwrap_err();
        assert_eq!(err.to_string(), "Invalid task ID '-1': must be a number");
    }
}