llman 0.0.78

A tool for managing LLM application rules(prompts) ...
Documentation
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
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
use crate::common::{TestEnvironment, assert_success, git_head, llman_command};
use serde_json::Value;
use std::fs;
use std::path::Path;
use std::process::{Command, Output};

fn run_llman(args: &[&str], work_dir: &Path, config_dir: &Path) -> Output {
    let mut cmd = llman_command(config_dir);
    cmd.args(args).current_dir(work_dir);
    if let Some(base_ref) = git_head(work_dir) {
        cmd.env("LLMANSPEC_BASE_REF", base_ref);
    }
    cmd.output().expect("Failed to run llman command")
}

fn git_commit_all(work_dir: &Path, message: &str) {
    let add_output = Command::new("git")
        .args(["add", "."])
        .current_dir(work_dir)
        .output()
        .expect("Failed to git add");
    assert_success(&add_output);

    let commit_output = Command::new("git")
        .args([
            "-c",
            "user.name=Test",
            "-c",
            "user.email=test@example.com",
            "commit",
            "-m",
            message,
        ])
        .current_dir(work_dir)
        .output()
        .expect("Failed to git commit");
    assert_success(&commit_output);
}

fn assert_no_disallowed_prompt_markers(path: &Path, content: &str) {
    const DISALLOWED: &[&str] = &[
        "Options:",
        "<option",
        "What would you like to do?",
        "/llman-sdd:",
        "{{ unit(",
    ];
    for snippet in DISALLOWED {
        assert!(
            !content.contains(snippet),
            "generated content contains disallowed snippet {snippet:?}: {}",
            path.display()
        );
    }
}

fn author_sample_spec(work_dir: &Path) {
    // Single-track (r131): one `.feature` carrying rule r1 + acceptance.
    // r42: the `# scope: src/` header must point at a real path under strict
    // validate, so the fixture creates it.
    let _ = fs::create_dir_all(work_dir.join("src"));
    let sample_dir = work_dir.join("llmanspec").join("specs").join("sample");
    std::fs::create_dir_all(&sample_dir).expect("mkdir sample");
    let feature = concat!(
        "# language: en\n",
        "# capability: sample\n",
        "# purpose: sample behaviors\n",
        "# scope: src/\n",
        "\n",
        "Feature: sample\n",
        "\n",
        "  @req:r1 @human\n",
        "  Scenario: R1\n",
        "    System MUST support R1.\n",
        "\n",
        "  @req:r1 @executable\n",
        "  Scenario: happy\n",
        "    Given a state\n",
        "    When a trigger happens\n",
        "    Then behavior is preserved\n",
    );
    fs::write(sample_dir.join("sample.feature"), feature).expect("write feature");
}

fn author_sample_change(work_dir: &Path, change_id: &str) {
    let llmanspec_dir = work_dir.join("llmanspec");
    let change_dir = llmanspec_dir.join("changes").join(change_id);
    fs::create_dir_all(&change_dir).expect("create change dir");
    // Docs-only archive fixtures: no live specs edit → needs_specs_change: false (r1).
    let proposal = "---\ndepends_on: []\nneeds_specs_change: false\n---\n\n## Why\nNeed a sample change.\n\n## What Changes\n- Add requirement.\n";
    fs::write(change_dir.join("proposal.md"), proposal).expect("write proposal");
    fs::write(change_dir.join("design.md"), "# Design\n").expect("write design");
    fs::write(change_dir.join("tasks.md"), "- [x] t1\n").expect("write tasks");
}

/// Designed → Full, ready for `change archive` (strict gates).
fn prepare_change_for_archive(work_dir: &Path, change_id: &str) {
    // r25: `change checkpoint` is removed; archive on its own no longer
    // requires any checkpointed field — binding + clean tree suffice.
    assert_success(&run_llman(
        &["sdd", "change", "start", change_id],
        work_dir,
        work_dir,
    ));
    git_commit_all(work_dir, "change start binding");
}

#[test]
fn test_sdd_init_and_list_specs_json() {
    let env = TestEnvironment::new();
    let work_dir = env.path();

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);

    let config_path = work_dir.join("llmanspec").join("config.yaml");
    assert!(config_path.exists());

    let list_output = run_llman(&["sdd", "list", "--specs", "--json"], work_dir, work_dir);
    assert_success(&list_output);

    let stdout = String::from_utf8_lossy(&list_output.stdout);
    let parsed: Value = serde_json::from_str(stdout.trim()).expect("spec list json");
    assert!(parsed.is_array());
    assert_eq!(parsed.as_array().unwrap().len(), 0);
}

#[test]
fn test_sdd_init_writes_schema_spec_driven() {
    let env = TestEnvironment::new();
    let work_dir = env.path();

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);

    let config_path = work_dir.join("llmanspec").join("config.yaml");
    let config = fs::read_to_string(&config_path).expect("read config");
    assert!(
        config.contains("schema: spec-driven"),
        "expected init config to include schema: spec-driven; got:\n{config}"
    );
    assert!(
        !config.contains("spec_style:"),
        "config must not contain spec_style field; got:\n{config}"
    );
}

#[test]
fn test_sdd_show_validate_archive_flow() {
    let env = TestEnvironment::new();
    let work_dir = env.path();
    // r42: the spec's `# scope: src` must exist under strict validate.
    fs::create_dir_all(work_dir.join("src")).expect("create fixture src scope dir");

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);

    let llmanspec_dir = work_dir.join("llmanspec");
    let spec_dir = llmanspec_dir.join("specs").join("sample");
    fs::create_dir_all(&spec_dir).expect("create spec dir");
    let feature_content = concat!(
        "# language: en\n",
        "# capability: sample\n",
        "# purpose: Describe sample behavior.\n",
        "# scope: src\n",
        "\n",
        "Feature: sample\n",
        "\n",
        "  @req:r9 @human\n",
        "  Scenario: Existing behavior\n",
        "    System MUST preserve existing behavior.\n",
        "\n",
        "  @req:r9 @executable\n",
        "  Scenario: baseline\n",
        "    When running the sample\n",
        "    Then behavior is preserved\n",
    );
    fs::write(spec_dir.join("sample.feature"), feature_content).expect("write spec");

    let change_dir = llmanspec_dir.join("changes").join("add-sample");
    fs::create_dir_all(&change_dir).expect("create change dir");
    let proposal = r#"---
depends_on: []
needs_specs_change: false
---

## Why
Need a sample change.

## What Changes
- Add a requirement to sample spec.
"#;
    fs::write(change_dir.join("proposal.md"), proposal).expect("write proposal");
    fs::write(change_dir.join("design.md"), "# Design\n").expect("write design");
    fs::write(
        change_dir.join("tasks.md"),
        "## 1. Done\n- [x] 1.1 Completed\n",
    )
    .expect("write tasks");

    git_commit_all(work_dir, "init sdd sample");

    let show_output = run_llman(
        &[
            "sdd", "show", "sample", "--type", "spec", "--output", "json",
        ],
        work_dir,
        work_dir,
    );
    assert_success(&show_output);
    let show_json: Value = serde_json::from_slice(&show_output.stdout).expect("show spec json");
    assert_eq!(show_json["id"], "sample");
    assert_eq!(show_json["requirementCount"], 1);

    let validate_output = run_llman(
        &[
            "sdd",
            "validate",
            "sample",
            "--type",
            "spec",
            "--strict",
            "--no-interactive",
            "--json",
        ],
        work_dir,
        work_dir,
    );
    assert_success(&validate_output);
    let validate_json: Value =
        serde_json::from_slice(&validate_output.stdout).expect("validate json");
    assert_eq!(validate_json["items"][0]["valid"], true);

    prepare_change_for_archive(work_dir, "add-sample");

    let archive_output = run_llman(
        &["sdd", "change", "archive", "add-sample"],
        work_dir,
        work_dir,
    );
    assert_success(&archive_output);

    let archive_root = llmanspec_dir.join("changes").join("archive");
    let entries: Vec<_> = fs::read_dir(&archive_root)
        .expect("read archive dir")
        .filter_map(|entry| entry.ok())
        .filter(|e| e.file_name() != ".gitkeep")
        .collect();
    assert_eq!(entries.len(), 1);
    let archive_name = entries[0].file_name().to_string_lossy().to_string();
    assert!(archive_name.ends_with("-add-sample"));

    let updated_spec =
        fs::read_to_string(spec_dir.join("sample.feature")).expect("read feature after archive");
    // Unified flow: archive does docs rename + ff-merge; the single-track
    // feature is untouched by a docs-only archive (r113).
    assert!(updated_spec.contains("@req:r9 @human"));
    assert!(updated_spec.contains("Existing behavior"));
}

#[test]
fn test_sdd_archive_flow_works_in_single_track_project() {
    let env = TestEnvironment::new();
    let work_dir = env.path();

    assert_success(&run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    ));

    // Seed existing main spec.
    author_sample_spec(work_dir);

    // Seed change docs (no change/specs delta — unified Git-native).
    author_sample_change(work_dir, "add-sample");
    git_commit_all(work_dir, "seed single-track spec and change");

    let validate_spec = run_llman(
        &[
            "sdd",
            "validate",
            "sample",
            "--type",
            "spec",
            "--strict",
            "--no-interactive",
        ],
        work_dir,
        work_dir,
    );
    assert_success(&validate_spec);

    prepare_change_for_archive(work_dir, "add-sample");

    let archive_output = run_llman(
        &["sdd", "change", "archive", "add-sample"],
        work_dir,
        work_dir,
    );
    assert_success(&archive_output);

    // Unified flow: archive does ff-merge + docs rename (r113); the
    // single-track feature is untouched by docs-only archive.
    let updated = fs::read_to_string(work_dir.join("llmanspec/specs/sample/sample.feature"))
        .expect("read feature after archive");
    assert!(updated.contains("# capability: sample"));
    assert!(updated.contains("@req:r1 @human"));
    assert!(
        !work_dir.join("llmanspec/changes/add-sample").exists(),
        "active change dir must be moved"
    );
}

#[test]
fn test_sdd_given_mapping_to_raw_text_is_deterministic() {
    let env = TestEnvironment::new();
    let work_dir = env.path();
    // r42: the spec's `# scope: src` must exist under strict validate.
    fs::create_dir_all(work_dir.join("src")).expect("create fixture src scope dir");

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);

    let llmanspec_dir = work_dir.join("llmanspec");
    let spec_dir = llmanspec_dir.join("specs").join("sample");
    fs::create_dir_all(&spec_dir).expect("create spec dir");
    // Single-track (r131): acceptance scenarios carry GWT; s1 has no Given.
    let feature_content = concat!(
        "# language: en\n",
        "# capability: sample\n",
        "# purpose: Describe sample behavior.\n",
        "# scope: src\n",
        "\n",
        "Feature: sample\n",
        "\n",
        "  @req:r1 @human\n",
        "  Scenario: First requirement\n",
        "    System MUST do the first thing.\n",
        "\n",
        "  @req:r1 @executable\n",
        "  Scenario: s1\n",
        "    When run the flow\n",
        "    Then it works\n",
        "\n",
        "  @req:r1 @executable\n",
        "  Scenario: s2\n",
        "    Given user exists\n",
        "    When run the flow\n",
        "    Then it works\n",
    );
    fs::write(spec_dir.join("sample.feature"), feature_content).expect("write spec");

    let show_output = run_llman(
        &[
            "sdd", "show", "sample", "--type", "spec", "--output", "json",
        ],
        work_dir,
        work_dir,
    );
    assert_success(&show_output);

    let show_json: Value = serde_json::from_slice(&show_output.stdout).expect("show spec json");
    let scenarios = show_json["requirements"][0]["scenarios"]
        .as_array()
        .expect("scenarios array");
    let raw_1 = scenarios[0]["rawText"].as_str().expect("rawText 1");
    let raw_2 = scenarios[1]["rawText"].as_str().expect("rawText 2");
    assert_eq!(raw_1, "GIVEN: \nWHEN: run the flow\nTHEN: it works");
    assert_eq!(
        raw_2,
        "GIVEN: user exists\nWHEN: run the flow\nTHEN: it works"
    );
}

#[test]
fn test_sdd_authoring_helpers_produce_strict_valid_spec_and_change() {
    let env = TestEnvironment::new();
    let work_dir = env.path();

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);
    git_commit_all(work_dir, "init");

    let spec_skel = run_llman(&["sdd", "spec", "skeleton", "sample"], work_dir, work_dir);
    assert_success(&spec_skel);

    // Skeleton seeds a placeholder rule occupying r1; the next free id is r2.
    let add_req = run_llman(
        &[
            "sdd",
            "spec",
            "add-requirement",
            "sample",
            "r2",
            "--title",
            "First requirement",
            "--statement",
            "System MUST do the first thing.",
        ],
        work_dir,
        work_dir,
    );
    assert_success(&add_req);

    let add_scenario = run_llman(
        &[
            "sdd",
            "spec",
            "add-scenario",
            "sample",
            "r2",
            "s2",
            "--when",
            "running the flow",
            "--then",
            "the first thing happens",
        ],
        work_dir,
        work_dir,
    );
    assert_success(&add_scenario);

    git_commit_all(work_dir, "add spec content");

    let validate_spec = run_llman(
        &[
            "sdd",
            "validate",
            "sample",
            "--type",
            "spec",
            "--strict",
            "--no-interactive",
            "--json",
        ],
        work_dir,
        work_dir,
    );
    assert_success(&validate_spec);
    let validate_spec_json: Value =
        serde_json::from_slice(&validate_spec.stdout).expect("validate spec json");
    assert_eq!(validate_spec_json["items"][0]["valid"], true);

    let llmanspec_dir = work_dir.join("llmanspec");
    let change_dir = llmanspec_dir.join("changes").join("add-sample");
    fs::create_dir_all(&change_dir).expect("create change dir");
    let proposal = "## Why\nNeed a sample change.\n\n## What Changes\n- Add requirement.\n";
    fs::write(change_dir.join("proposal.md"), proposal).expect("write proposal");
    fs::write(
        change_dir.join("design.md"),
        "# Design\n\nSimple change, no trade-offs.\n",
    )
    .expect("write design");
    fs::write(change_dir.join("tasks.md"), "- [x] Implement the change\n").expect("write tasks");

    let delta_skel = run_llman(
        &["sdd", "change", "delta", "skeleton", "add-sample", "sample"],
        work_dir,
        work_dir,
    );
    // change delta is removed (r115) — always rejected.
    assert!(!delta_skel.status.success(), "change delta must be removed");
    let delta_err = String::from_utf8_lossy(&delta_skel.stderr);
    assert!(delta_err.contains("removed"), "got: {delta_err}");

    // Validate the change still passes (specs are not read from change dir).
    let validate_change = run_llman(
        &[
            "sdd",
            "validate",
            "add-sample",
            "--type",
            "change",
            "--strict",
            "--no-interactive",
            "--json",
        ],
        work_dir,
        work_dir,
    );
    assert_success(&validate_change);
    let validate_change_json: Value =
        serde_json::from_slice(&validate_change.stdout).expect("validate change json");
    assert_eq!(validate_change_json["items"][0]["valid"], true);
}

#[test]
fn test_sdd_archive_help_hides_force() {
    let env = TestEnvironment::new();
    let work_dir = env.path();

    let help_output = run_llman(&["sdd", "archive", "--help"], work_dir, work_dir);
    assert_success(&help_output);

    let stdout = String::from_utf8_lossy(&help_output.stdout);
    let stderr = String::from_utf8_lossy(&help_output.stderr);
    assert!(!stdout.contains("--force"));
    assert!(!stderr.contains("--force"));
    assert!(stdout.contains("run"));
    assert!(stdout.contains("freeze"));
    assert!(stdout.contains("thaw"));
}

#[test]
fn test_sdd_list_changes_json_reports_status() {
    let env = TestEnvironment::new();
    let work_dir = env.path();

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);

    let llmanspec_dir = work_dir.join("llmanspec");
    let change_dir = llmanspec_dir.join("changes").join("add-sample");
    fs::create_dir_all(&change_dir).expect("create change dir");
    fs::write(
        change_dir.join("proposal.md"),
        "## Why\nNeed a sample change.\n\n## What Changes\n- Add sample.\n",
    )
    .expect("write proposal");
    fs::write(
        change_dir.join("tasks.md"),
        "## 1. Tasks\n- [x] 1.1 Done\n- [ ] 1.2 Pending\n",
    )
    .expect("write tasks");

    let list_output = run_llman(&["sdd", "list", "--json"], work_dir, work_dir);
    assert_success(&list_output);

    let parsed: Value =
        serde_json::from_slice(&list_output.stdout).expect("parse list changes json");
    let changes = parsed["changes"].as_array().expect("changes array");
    assert_eq!(changes.len(), 1);
    let change = &changes[0];
    assert_eq!(change["name"], "add-sample");
    assert_eq!(change["completedTasks"], 1);
    assert_eq!(change["totalTasks"], 2);
    assert_eq!(change["status"], "in-progress");
}

#[test]
fn test_sdd_show_change_json_uses_delta_specs() {
    let env = TestEnvironment::new();
    let work_dir = env.path();

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);

    let llmanspec_dir = work_dir.join("llmanspec");
    let change_dir = llmanspec_dir.join("changes").join("add-sample");
    fs::create_dir_all(&change_dir).expect("create change dir");
    fs::write(
        change_dir.join("proposal.md"),
        "## Why\nNeed a sample change.\n\n## What Changes\n- Add requirement.\n",
    )
    .expect("write proposal");
    fs::write(change_dir.join("design.md"), "# Design\n").expect("write design");
    fs::write(change_dir.join("tasks.md"), "- [x] t1\n").expect("write tasks");

    // Unified flow: delta specs are removed; deltaCount is always 0 (r115).
    let show_output = run_llman(
        &[
            "sdd",
            "show",
            "add-sample",
            "--type",
            "change",
            "--output",
            "json",
        ],
        work_dir,
        work_dir,
    );
    assert_success(&show_output);

    let show_json: Value = serde_json::from_slice(&show_output.stdout).expect("show change json");
    assert_eq!(show_json["id"], "add-sample");
    // Unified flow: delta specs removed, deltaCount is always 0 (r115).
    assert_eq!(show_json["deltaCount"], 0);
    assert!(show_json["deltas"].as_array().unwrap().is_empty());

    // stage: proposal+design+tasks but no attach -> planned (r93 four tiers).
    assert_eq!(show_json["stage"], "planned");
    assert_eq!(show_json["readyToImplement"], false);
    let artifacts = show_json["artifacts"]
        .as_array()
        .expect("artifacts is an array");
    assert!(
        artifacts.iter().any(|v| v == "proposal.md"),
        "artifacts should include proposal.md, got: {artifacts:?}"
    );
    assert!(
        artifacts.iter().any(|v| v == "design.md"),
        "artifacts should include design.md, got: {artifacts:?}"
    );
    assert!(
        artifacts.iter().any(|v| v == "tasks.md"),
        "artifacts should include tasks.md, got: {artifacts:?}"
    )
}

#[test]
fn test_sdd_show_change_prefix_match_emits_hint_and_json_flag() {
    // cli spec r112: resolving a change via a unique prefix MUST emit the
    // "'input' -> 'resolved' (prefix match)" hint (human: stderr) and set
    // `matchedViaPrefix` in JSON. Exact match MUST NOT emit the hint and sets
    // `matchedViaPrefix=false`.
    let env = TestEnvironment::new();
    let work_dir = env.path();

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);

    let change_id = "c123-fix-bug";
    let change_dir = work_dir.join("llmanspec").join("changes").join(change_id);
    fs::create_dir_all(&change_dir).expect("create change dir");
    fs::write(
        change_dir.join("proposal.md"),
        "## Why\nNeed a sample change.\n\n## What Changes\n- Fix a bug.\n",
    )
    .expect("write proposal");

    // --- Prefix match: hint on stderr + matchedViaPrefix=true in JSON ---
    let prefix_json = run_llman(
        &[
            "sdd", "show", "c123", "--type", "change", "--output", "json",
        ],
        work_dir,
        work_dir,
    );
    assert_success(&prefix_json);
    let json: Value = serde_json::from_slice(&prefix_json.stdout).expect("prefix show json");
    assert_eq!(
        json["id"], change_id,
        "resolved id should be the full change"
    );
    assert_eq!(
        json["matchedViaPrefix"], true,
        "prefix match MUST set matchedViaPrefix=true"
    );

    // Human-readable output: hint goes to stderr.
    let prefix_human = run_llman(
        &["sdd", "show", "c123", "--type", "change"],
        work_dir,
        work_dir,
    );
    assert_success(&prefix_human);
    let stderr = String::from_utf8_lossy(&prefix_human.stderr);
    assert!(
        stderr.contains("'c123' -> 'c123-fix-bug' (prefix match)"),
        "human output MUST emit prefix-match hint on stderr, got stderr: {stderr}"
    );

    // --- Exact match: no hint + matchedViaPrefix=false ---
    let exact_json = run_llman(
        &[
            "sdd", "show", change_id, "--type", "change", "--output", "json",
        ],
        work_dir,
        work_dir,
    );
    assert_success(&exact_json);
    let json: Value = serde_json::from_slice(&exact_json.stdout).expect("exact show json");
    assert_eq!(json["id"], change_id);
    assert_eq!(
        json["matchedViaPrefix"], false,
        "exact match MUST set matchedViaPrefix=false"
    );

    let exact_human = run_llman(
        &["sdd", "show", change_id, "--type", "change"],
        work_dir,
        work_dir,
    );
    assert_success(&exact_human);
    let stderr = String::from_utf8_lossy(&exact_human.stderr);
    assert!(
        !stderr.contains("(prefix match)"),
        "exact match MUST NOT emit prefix-match hint, got stderr: {stderr}"
    );
}

#[test]
fn test_sdd_update_recreates_root_agents_md() {
    let env = TestEnvironment::new();
    let work_dir = env.path();

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);

    let agents_path = work_dir.join("AGENTS.md");
    fs::remove_file(&agents_path).expect("remove root AGENTS.md");
    assert!(!agents_path.exists());

    let update_output = run_llman(&["sdd", "init", "--update"], work_dir, work_dir);
    assert_success(&update_output);

    assert!(agents_path.exists());
    let content = fs::read_to_string(&agents_path).expect("read root AGENTS.md");
    assert!(content.contains("<!-- LLMANSPEC:START -->"));
    assert!(content.contains("LLMAN Spec-Driven Development"));
    assert!(content.contains("/llman-sdd-explore"));
}

#[test]
fn test_sdd_update_skills_writes_agents_skills() {
    let env = TestEnvironment::new();
    let work_dir = env.path();

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);

    let output_dir = work_dir.join(".agents/skills");
    let update_output = run_llman(&["sdd", "init", "--update"], work_dir, work_dir);
    assert_success(&update_output);

    let skill_path = output_dir.join("llman-sdd-explore").join("SKILL.md");
    assert!(skill_path.exists());
    let compact_skill_path = output_dir.join("llman-sdd-specs-compact").join("SKILL.md");
    assert!(compact_skill_path.exists());
    let compact_skill = fs::read_to_string(&compact_skill_path).expect("read specs compact skill");
    assert!(!compact_skill.contains("legacy-track"));
    assert!(!compact_skill.contains("先调用某外部技能"));
    assert!(
        !compact_skill
            .to_lowercase()
            .contains("ison-prompt-optimizer-zh")
    );
    let archive_skill_path = output_dir.join("llman-sdd-archive").join("SKILL.md");
    assert!(archive_skill_path.exists());
    let archive_skill = fs::read_to_string(&archive_skill_path).expect("read archive skill");
    assert!(archive_skill.contains("llman sdd archive freeze"));
    assert!(archive_skill.contains("llman sdd archive thaw"));
    let explore_skill_path = output_dir.join("llman-sdd-explore").join("SKILL.md");
    assert!(explore_skill_path.exists());
    let _explore_skill = fs::read_to_string(&explore_skill_path).expect("read explore skill");

    for entry in fs::read_dir(&output_dir).expect("read skills output dir") {
        let entry = entry.expect("skills entry");
        let file_type = entry.file_type().expect("skills entry file type");
        if !file_type.is_dir() {
            continue;
        }
        let skill_md = entry.path().join("SKILL.md");
        if !skill_md.exists() {
            continue;
        }
        let content = fs::read_to_string(&skill_md).expect("read generated SKILL.md");
        assert_no_disallowed_prompt_markers(&skill_md, &content);
    }
}

#[test]
fn test_sdd_update_skills_new_style_uses_markdown_override() {
    let env = TestEnvironment::new();
    let work_dir = env.path();

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);

    let override_path = work_dir.join("templates/sdd/en/skills/llman-sdd-explore.md");
    fs::create_dir_all(override_path.parent().expect("parent")).expect("mkdir override");
    fs::write(
        &override_path,
        r#"---
name: "llman-sdd-explore"
description: "markdown override"
metadata:
  version: "{{ llman_version }}"
---

# Markdown Override
MARKDOWN SOURCE MARKER

## Context
- from markdown
## Goal
- from markdown
## Constraints
- from markdown
## Workflow
- from markdown
## Decision Policy
- from markdown
## Output Contract
- from markdown
## Ethics Governance
- `ethics.risk_level`: x
- `ethics.prohibited_actions`: x
- `ethics.required_evidence`: x
- `ethics.refusal_contract`: x
- `ethics.escalation_policy`: x
"#,
    )
    .expect("write markdown override");

    let output_dir = work_dir.join(".agents/skills");
    let update_output = run_llman(&["sdd", "init", "--update"], work_dir, work_dir);
    assert_success(&update_output);

    let skill = fs::read_to_string(output_dir.join("llman-sdd-explore").join("SKILL.md"))
        .expect("read skill");
    assert!(skill.contains("MARKDOWN SOURCE MARKER"));
}

#[test]
fn test_sdd_update_skills_new_style_fails_when_override_missing_ethics_key() {
    let env = TestEnvironment::new();
    let work_dir = env.path();

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);

    let override_path = work_dir.join("templates/sdd/en/skills/llman-sdd-explore.md");
    fs::create_dir_all(override_path.parent().expect("parent")).expect("mkdir override");
    fs::write(
        &override_path,
        r#"---
name: "llman-sdd-explore"
description: "missing ethics key"
metadata:
  llman-template-version: 1
---

## Context
- test
## Goal
- test
## Constraints
- test
## Workflow
- test
## Decision Policy
- test
## Output Contract
- test
## Ethics Governance
- `ethics.risk_level`: x
- `ethics.prohibited_actions`: x
- `ethics.required_evidence`: x
- `ethics.refusal_contract`: x
"#,
    )
    .expect("write invalid override");

    let output = run_llman(&["sdd", "init", "--update"], work_dir, work_dir);
    assert!(
        !output.status.success(),
        "missing ethics key in override should fail"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("ethics.escalation_policy"),
        "unexpected stderr: {}",
        stderr
    );
}

#[test]
fn test_sdd_archive_freeze_and_thaw_single_file_flow() {
    let env = TestEnvironment::new();
    let work_dir = env.path();

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);

    let archive_root = work_dir.join("llmanspec").join("changes").join("archive");
    let archived_a = archive_root.join("2026-01-01-alpha");
    let archived_b = archive_root.join("2026-01-02-beta");
    fs::create_dir_all(&archived_a).expect("create archived a");
    fs::create_dir_all(&archived_b).expect("create archived b");
    fs::write(archived_a.join("a.txt"), "alpha").expect("write a");
    fs::write(archived_b.join("b.txt"), "beta").expect("write b");

    let freeze_output = run_llman(&["sdd", "archive", "freeze"], work_dir, work_dir);
    assert_success(&freeze_output);

    let freeze_file = archive_root.join("freezed_changes.7z.archived");
    assert!(freeze_file.exists());
    assert!(!archived_a.exists());
    assert!(!archived_b.exists());

    let thaw_output = run_llman(&["sdd", "archive", "thaw"], work_dir, work_dir);
    assert_success(&thaw_output);
    assert!(archive_root.join(".thawed/2026-01-01-alpha/a.txt").exists());
    assert!(archive_root.join(".thawed/2026-01-02-beta/b.txt").exists());
}

#[test]
fn test_sdd_archive_thaw_supports_change_filter_and_dest() {
    let env = TestEnvironment::new();
    let work_dir = env.path();

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);

    let archive_root = work_dir.join("llmanspec").join("changes").join("archive");
    let archived_a = archive_root.join("2026-01-03-alpha");
    let archived_b = archive_root.join("2026-01-04-beta");
    fs::create_dir_all(&archived_a).expect("create archived a");
    fs::create_dir_all(&archived_b).expect("create archived b");
    fs::write(archived_a.join("a.txt"), "alpha").expect("write a");
    fs::write(archived_b.join("b.txt"), "beta").expect("write b");

    let freeze_output = run_llman(&["sdd", "archive", "freeze"], work_dir, work_dir);
    assert_success(&freeze_output);

    let custom_dest = work_dir.join("restore-target");
    let thaw_output = run_llman(
        &[
            "sdd",
            "archive",
            "thaw",
            "--change",
            "2026-01-03-alpha",
            "--dest",
            custom_dest.to_str().expect("dest"),
        ],
        work_dir,
        work_dir,
    );
    assert_success(&thaw_output);

    assert!(custom_dest.join("2026-01-03-alpha/a.txt").exists());
    assert!(!custom_dest.join("2026-01-04-beta").exists());
}

#[test]
fn test_sdd_archive_freeze_dry_run_does_not_write() {
    let env = TestEnvironment::new();
    let work_dir = env.path();

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);

    let archive_root = work_dir.join("llmanspec").join("changes").join("archive");
    let archived = archive_root.join("2026-01-05-alpha");
    fs::create_dir_all(&archived).expect("create archived dir");
    fs::write(archived.join("a.txt"), "alpha").expect("write file");

    let dry_run_output = run_llman(
        &["sdd", "archive", "freeze", "--dry-run"],
        work_dir,
        work_dir,
    );
    assert_success(&dry_run_output);

    assert!(archived.exists());
    assert!(!archive_root.join("freezed_changes.7z.archived").exists());
}

#[test]
fn test_sdd_archive_freeze_failure_keeps_source_dirs() {
    let env = TestEnvironment::new();
    let work_dir = env.path();

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);

    let archive_root = work_dir.join("llmanspec").join("changes").join("archive");
    let archived = archive_root.join("2026-01-06-alpha");
    fs::create_dir_all(&archived).expect("create archived dir");
    fs::write(archived.join("a.txt"), "alpha").expect("write file");

    let freeze_file_dir = archive_root.join("freezed_changes.7z.archived");
    fs::create_dir_all(&freeze_file_dir).expect("create conflicting freeze path");

    let freeze_output = run_llman(&["sdd", "archive", "freeze"], work_dir, work_dir);
    assert!(!freeze_output.status.success());
    assert!(archived.exists());
}

#[test]
fn test_sdd_archive_freeze_second_run_preserves_first_run_content() {
    let env = TestEnvironment::new();
    let work_dir = env.path();

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);

    let archive_root = work_dir.join("llmanspec").join("changes").join("archive");
    let first = archive_root.join("2026-01-07-first");
    fs::create_dir_all(&first).expect("create first dir");
    fs::write(first.join("one.txt"), "one").expect("write first file");
    assert_success(&run_llman(
        &["sdd", "archive", "freeze"],
        work_dir,
        work_dir,
    ));

    let second = archive_root.join("2026-01-08-second");
    fs::create_dir_all(&second).expect("create second dir");
    fs::write(second.join("two.txt"), "two").expect("write second file");
    assert_success(&run_llman(
        &["sdd", "archive", "freeze"],
        work_dir,
        work_dir,
    ));

    let thaw_dest = work_dir.join("thaw-all");
    assert_success(&run_llman(
        &[
            "sdd",
            "archive",
            "thaw",
            "--dest",
            thaw_dest.to_str().expect("dest"),
        ],
        work_dir,
        work_dir,
    ));

    assert!(thaw_dest.join("2026-01-07-first/one.txt").exists());
    assert!(thaw_dest.join("2026-01-08-second/two.txt").exists());
}

#[test]
fn test_sdd_archive_freeze_list_enumerates_frozen_changes() {
    let env = TestEnvironment::new();
    let work_dir = env.path();

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);

    let archive_root = work_dir.join("llmanspec").join("changes").join("archive");
    let archived_a = archive_root.join("2026-01-09-alpha");
    let archived_b = archive_root.join("2026-01-10-beta");
    fs::create_dir_all(&archived_a).expect("create archived a");
    fs::create_dir_all(&archived_b).expect("create archived b");
    fs::write(archived_a.join("a.txt"), "alpha").expect("write a");
    fs::write(archived_b.join("b.txt"), "beta").expect("write b");

    assert_success(&run_llman(
        &["sdd", "archive", "freeze"],
        work_dir,
        work_dir,
    ));

    let list_output = run_llman(&["sdd", "archive", "freeze", "--list"], work_dir, work_dir);
    assert_success(&list_output);
    let stdout = String::from_utf8_lossy(&list_output.stdout);
    assert!(stdout.contains("2026-01-09-alpha"), "stdout was: {stdout}");
    assert!(stdout.contains("2026-01-10-beta"), "stdout was: {stdout}");
}

#[test]
fn test_sdd_archive_freeze_list_reports_missing_archive() {
    let env = TestEnvironment::new();
    let work_dir = env.path();

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);

    let archive_root = work_dir.join("llmanspec").join("changes").join("archive");
    assert!(!archive_root.join("freezed_changes.7z.archived").exists());

    let list_output = run_llman(&["sdd", "archive", "freeze", "--list"], work_dir, work_dir);
    assert_success(&list_output);
    let stdout = String::from_utf8_lossy(&list_output.stdout);
    assert!(
        stdout.contains("No freeze archive found"),
        "stdout was: {stdout}"
    );
}

#[test]
fn test_sdd_archive_freeze_list_does_not_mutate_source() {
    let env = TestEnvironment::new();
    let work_dir = env.path();

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);

    let archive_root = work_dir.join("llmanspec").join("changes").join("archive");
    let archived = archive_root.join("2026-01-11-alpha");
    fs::create_dir_all(&archived).expect("create archived dir");
    fs::write(archived.join("a.txt"), "alpha").expect("write file");

    assert_success(&run_llman(
        &["sdd", "archive", "freeze"],
        work_dir,
        work_dir,
    ));

    assert_success(&run_llman(
        &["sdd", "archive", "freeze", "--list"],
        work_dir,
        work_dir,
    ));

    // No leftover thaw staging under archive dir
    assert!(!archive_root.join(".thawed").exists());
}

#[test]
fn test_sdd_validate_tasks_without_design_is_error() {
    let env = TestEnvironment::new();
    let work_dir = env.path();

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);

    let llmanspec_dir = work_dir.join("llmanspec");
    let change_dir = llmanspec_dir.join("changes").join("tasks-no-design");
    let change_specs_dir = change_dir.join("specs").join("sample");
    fs::create_dir_all(&change_specs_dir).expect("create change spec dir");
    fs::write(
        change_dir.join("proposal.md"),
        "## Why\nTest constraint.\n\n## What Changes\n- Test.\n",
    )
    .expect("write proposal");
    fs::write(change_dir.join("tasks.md"), "## Tasks\n- [x] Done\n").expect("write tasks");
    let delta_spec = "kind: llman.sdd.delta\nops[1]{op,req_id,title,statement,from,to,name}:\n  add_requirement,r1,Test,System MUST test.,null,null,null\nop_scenarios[1]{req_id,id,given,when,then}:\n  r1,happy,\"\",trigger,outcome\n";
    fs::write(change_specs_dir.join("spec.toon"), delta_spec).expect("write delta spec");

    let validate_output = run_llman(
        &[
            "sdd",
            "validate",
            "tasks-no-design",
            "--type",
            "change",
            "--no-interactive",
        ],
        work_dir,
        work_dir,
    );
    let stderr = String::from_utf8_lossy(&validate_output.stderr);
    assert!(
        !validate_output.status.success(),
        "Should fail when tasks.md exists without design.md"
    );
    assert!(
        stderr.contains("tasks.md") && stderr.contains("design.md"),
        "Error should mention both tasks.md and design.md, got: {stderr}"
    );
}

#[test]
fn test_sdd_validate_completeness_stage_in_output() {
    let env = TestEnvironment::new();
    let work_dir = env.path();

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);

    let llmanspec_dir = work_dir.join("llmanspec");
    let change_dir = llmanspec_dir.join("changes").join("draft-only");
    fs::create_dir_all(&change_dir).expect("create change dir");
    fs::write(
        change_dir.join("proposal.md"),
        "## Why\nJust a draft.\n\n## What Changes\n- Nothing yet.\n",
    )
    .expect("write proposal");

    let validate_output = run_llman(
        &[
            "sdd",
            "validate",
            "draft-only",
            "--type",
            "change",
            "--no-interactive",
        ],
        work_dir,
        work_dir,
    );
    let stdout = String::from_utf8_lossy(&validate_output.stdout);
    assert_success(&validate_output);
    assert!(
        stdout.contains("draft"),
        "Output should contain stage 'draft', got: {stdout}"
    );
}

#[test]
fn test_sdd_list_shows_stage_column() {
    let env = TestEnvironment::new();
    let work_dir = env.path();

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);

    let llmanspec_dir = work_dir.join("llmanspec");
    let change_dir = llmanspec_dir.join("changes").join("stage-test");
    fs::create_dir_all(&change_dir).expect("create change dir");
    fs::write(
        change_dir.join("proposal.md"),
        "## Why\nTest stage display.\n",
    )
    .expect("write proposal");

    let list_output = run_llman(&["sdd", "list"], work_dir, work_dir);
    assert_success(&list_output);
    let stdout = String::from_utf8_lossy(&list_output.stdout);
    assert!(
        stdout.contains("draft"),
        "List output should show stage 'draft', got: {stdout}"
    );

    let json_output = run_llman(&["sdd", "list", "--json"], work_dir, work_dir);
    assert_success(&json_output);
    let json: Value = serde_json::from_slice(&json_output.stdout).expect("parse json");
    let stage = json["changes"][0]["stage"].as_str().unwrap_or("");
    assert_eq!(stage, "draft", "JSON output should contain stage field");
}

/// A full change with attach binding MUST report `stage: full`. Under the
/// git-native-v2 gateChecks semantics `readyToImplement` is true only when
/// EVERY gate passes — clean tree, on the bound branch, tasks done, plus a
/// `needs_specs_change: false` exemption for the missing live specs diff.
#[test]
fn test_sdd_show_change_full_stage_ready_to_implement() {
    let env = TestEnvironment::new();
    let work_dir = env.path();

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);

    // Real git repo with a seeded commit so gate plumbing has refs to work with.
    let git_repo = Command::new("git")
        .args(["init", "-q", "-b", "main"])
        .current_dir(work_dir)
        .output()
        .expect("git init");
    assert_success(&git_repo);
    git_commit_all(work_dir, "seed");
    // Bound branch for the change.
    let branch_out = Command::new("git")
        .args(["checkout", "-q", "-b", "feat/x"])
        .current_dir(work_dir)
        .output()
        .expect("git checkout branch");
    assert_success(&branch_out);

    let llmanspec_dir = work_dir.join("llmanspec");
    let change_dir = llmanspec_dir.join("changes").join("full-change");
    fs::create_dir_all(&change_dir).expect("create change dir");
    let head = git_head(work_dir).expect("branch tip");
    fs::write(
        change_dir.join("proposal.md"),
        format!(
            "---\nbranch: feat/x\nbase_sha: {head}\nneeds_specs_change: false\n---\n# Proposal\n\n## Why\nFull change.\n\n## What Changes\n- Add behavior.\n"
        ),
    )
    .expect("write proposal");
    fs::write(change_dir.join("design.md"), "# Design\nTrivial.\n").expect("write design");
    fs::write(change_dir.join("tasks.md"), "- [x] implement\n").expect("write tasks");
    git_commit_all(work_dir, "change docs");

    let show_output = run_llman(
        &[
            "sdd",
            "show",
            "full-change",
            "--type",
            "change",
            "--output",
            "json",
        ],
        work_dir,
        work_dir,
    );
    assert_success(&show_output);
    let show_json: Value = serde_json::from_slice(&show_output.stdout).expect("show change json");
    assert_eq!(show_json["stage"], "full");
    assert_eq!(show_json["needsSpecsChange"], false);
    assert_eq!(show_json["readyToImplement"], true);
    assert_eq!(show_json["specsLanded"], false);
    // gateChecks present; hint is empty exactly when pass=true. The lock-gate
    // entry is gone since the report-only rework (spec-format r135 S0).
    let gates = show_json["gateChecks"]
        .as_array()
        .expect("gateChecks array");
    assert_eq!(gates.len(), 6);
    for gate in gates {
        assert!(gate["name"].is_string());
        assert!(gate["pass"].is_boolean());
        assert_eq!(
            gate["pass"] == serde_json::Value::Bool(true),
            gate["hint"].as_str().map(|h| h.is_empty()).unwrap_or(false),
            "hint must be empty iff pass: {gate}"
        );
    }
    assert!(
        gates
            .iter()
            .all(|g| g["pass"] == serde_json::Value::Bool(true)),
        "all gates must pass: {gates:?}"
    );
}

/// A draft change (proposal-only) under non-strict validate MUST surface the
/// stage hint as INFO instead of swallowing it on the valid short-circuit
/// (sdd-workflow r45 drift fix).
#[test]
fn test_sdd_validate_draft_non_stract_shows_stage_info() {
    let env = TestEnvironment::new();
    let work_dir = env.path();

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);

    let llmanspec_dir = work_dir.join("llmanspec");
    let change_dir = llmanspec_dir.join("changes").join("draft-proposal");
    fs::create_dir_all(&change_dir).expect("create change dir");
    fs::write(
        change_dir.join("proposal.md"),
        "## Why\nDraft.\n\n## What Changes\n- Nothing yet.\n",
    )
    .expect("write proposal");

    let validate_output = run_llman(
        &[
            "sdd",
            "validate",
            "draft-proposal",
            "--type",
            "change",
            "--no-interactive",
        ],
        work_dir,
        work_dir,
    );
    // draft is valid under non-strict (no errors)
    assert_success(&validate_output);
    // the stage INFO hint is now surfaced (was previously swallowed)
    let stderr = String::from_utf8_lossy(&validate_output.stderr);
    assert!(
        stderr.contains("draft"),
        "non-strict validate should surface the draft stage INFO, got stderr: {stderr}"
    );
}

/// `llman sdd config` (no subcommand) prints a read-only overview (sdd-workflow r109).
/// `llman sdd config skills --no-interactive` prints enabled/available lists (r110).
/// `llman sdd config skills --json` outputs structured JSON (r110).
#[test]
fn test_sdd_config_skills_non_interactive() {
    let env = TestEnvironment::new();
    let work_dir = env.path();

    let init_output = run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    );
    assert_success(&init_output);

    // Overview (r109).
    let overview = run_llman(&["sdd", "config"], work_dir, work_dir);
    assert_success(&overview);
    let overview_stdout = String::from_utf8_lossy(&overview.stdout);
    assert!(
        overview_stdout.contains("spec-driven"),
        "overview should show schema, got: {overview_stdout}"
    );
    assert!(
        overview_stdout.contains("bdd"),
        "overview should show bdd status, got: {overview_stdout}"
    );

    // Non-interactive state (r110): lists all optional candidates.
    let state = run_llman(
        &["sdd", "config", "skills", "--no-interactive"],
        work_dir,
        work_dir,
    );
    assert_success(&state);
    let state_stdout = String::from_utf8_lossy(&state.stdout);
    assert!(
        state_stdout.contains("llman-sdd-arch-review"),
        "non-interactive should list arch-review, got: {state_stdout}"
    );
    assert!(
        state_stdout.contains("llman-sdd-research"),
        "non-interactive should list research, got: {state_stdout}"
    );

    // JSON (r110): structured enabled/available.
    let json_out = run_llman(&["sdd", "config", "skills", "--json"], work_dir, work_dir);
    assert_success(&json_out);
    let json: Value = serde_json::from_slice(&json_out.stdout).expect("parse config skills json");
    assert!(
        json["available"].is_array(),
        "json should have available array, got: {json}"
    );
    let available = json["available"].as_array().unwrap();
    assert_eq!(
        available.len(),
        6,
        "should list all optional skills as available (none enabled yet), got: {available:?}"
    );
}

// ---------------------------------------------------------------------------
// bdd.bindings: harness bound/unbound split (sdd-workflow r2/r3)
// ---------------------------------------------------------------------------

/// Init a project, author `sample` with r1, and plant a two-scenario feature.
fn setup_spec_with_feature(work_dir: &Path) {
    assert_success(&run_llman(
        &["sdd", "init", work_dir.to_str().unwrap()],
        work_dir,
        work_dir,
    ));
    // Single-track (r131): one `.feature` with a @human rule + acceptance.
    let sample_dir = work_dir.join("llmanspec").join("specs").join("sample");
    std::fs::create_dir_all(&sample_dir).expect("mkdir sample");
    let feature = concat!(
        "# language: en\n",
        "# capability: sample\n",
        "# purpose: sample\n",
        "# scope: llmanspec/specs/sample\n",
        "\n",
        "Feature: sample\n",
        "\n",
        "  @req:r1 @human\n",
        "  Scenario: R1\n",
        "    System MUST support R1.\n",
        "\n",
        "  @req:r1 @executable\n",
        "  Scenario: tagged-happy\n",
        "    Given a\n",
        "    When b\n",
        "    Then c\n",
        "\n",
        "  @executable\n",
        "  Scenario: orphan-scenario\n",
        "    Given x\n",
        "    When y\n",
        "    Then z\n",
    );
    fs::write(sample_dir.join("sample.feature"), feature).expect("write feature");
}

#[test]
fn test_list_specs_reports_rule_tiers() {
    let env = TestEnvironment::new();
    let work_dir = env.path();
    setup_spec_with_feature(work_dir);

    // Text output carries the three-tier rule morphology (r134).
    let list_output = run_llman(&["sdd", "list", "--specs"], work_dir, work_dir);
    assert_success(&list_output);
    let stdout = String::from_utf8_lossy(&list_output.stdout);
    assert!(
        stdout.contains("rules 1") && stdout.contains("enforced 1") && stdout.contains("pending 0"),
        "expected tier counts in list output; got:\n{stdout}"
    );

    // JSON morphology carries camelCase rule-tier keys.
    let json_output = run_llman(&["sdd", "list", "--specs", "--json"], work_dir, work_dir);
    assert_success(&json_output);
    let parsed: Value =
        serde_json::from_str(String::from_utf8_lossy(&json_output.stdout).trim()).expect("json");
    let morphology = &parsed[0]["morphology"];
    assert_eq!(morphology["ruleCount"], 1);
    assert_eq!(morphology["ruleEnforcedCount"], 1);
    assert_eq!(morphology["acceptanceCount"], 2);
    assert_eq!(morphology["orphanAcceptanceCount"], 1);

    // show prints the same tiers.
    let show_output = run_llman(
        &["sdd", "show", "sample", "--type", "spec"],
        work_dir,
        work_dir,
    );
    assert_success(&show_output);
    let show_stdout = String::from_utf8_lossy(&show_output.stdout);
    assert!(
        show_stdout.contains("ruleCount=1") && show_stdout.contains("enforced=1"),
        "show Morphology line must carry rule tiers; got:\n{show_stdout}"
    );
}