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
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
//! Generic BDD step library for feature-as-spec (rstest-bdd).
//!
//! Gated behind `#[cfg(feature = "bdd")]` — only compiled with `cargo test --features bdd`.
//! Provides a reusable "run llman → assert output" vocabulary so that CLI-testable
//! `.feature` scenarios can be bound without writing per-scenario step functions.
//!
//! Step vocabulary:
//!   Given:
//!     - 假如 llman 二进制已构建            (reset world + assert binary exists)
//!     - 假如 已初始化 sdd 项目且 bdd 配置为 {mode}  (create a seeded TempDir project:
//!          mode="on" writes a bdd: block, "off" omits it; author a sample spec +
//!          an add-scen change delta; git init+commit; sets cwd to the project)
//!     - 假如 项目中存在技能目录 {name}     (plant `.agents/skills/<name>/SKILL.md`)
//!     - 假如 项目 extra_skills 包含 {name} (rewrite config.yaml `extra_skills`)
//!     - 假如 已初始化含 change_id pattern 与 archive 形态存量的 sdd 项目且存在违规 active change {id}
//!     - 假如 已初始化含 change_id template 的 sdd 项目
//!     - 假如 已初始化含 change_id 段且 delayed-changes 深层目录含更大号的 sdd 项目
//!     - 假如 {env_var} 为 {value}          (accumulate env override for subprocess)
//!     - 假如今目录为 {cwd}                 (set working directory for subprocess)
//!   When:
//!     - 当 运行 llman {args}               (run llman with whitespace-split args)
//!     - 当 在非交互终端运行 llman {args}    (same, non-interactive)
//!   Then:
//!     - 那么 退出码为 {code:i32}           (exact exit code)
//!     - 那么 退出码非零                    (non-zero exit)
//!     - 那么 退出码为零                    (zero exit)
//!     - 那么 stdout 包含 {text}            (substring on stdout)
//!     - 那么 stderr 包含 {text}            (substring on stderr)
//!     - 那么 stdout 不含 {text}            (negated substring on stdout)
//!     - 那么 stderr 不含 {text}            (negated substring on stderr)
//!     - 那么 stdout 为合法 JSON            (stdout parses as JSON)
//!     - 那么 stdout 含 JSON 键 {key}       (stdout JSON has top-level key)
//!     - 那么 相对路径 {rel} 存在           (path under fixture cwd)
//!     - 那么 相对路径 {rel} 不存在         (path under fixture cwd absent)
//!     - 那么 相对路径 {rel} 内容包含 {text} (substring on file content)

#![cfg(feature = "bdd")]

use rstest_bdd_macros::{given, scenarios, then, when};
use std::cell::RefCell;
use std::collections::HashMap;
use std::path::PathBuf;
use std::process::Command;
use tempfile::TempDir;

/// Holds the last llman subprocess output so steps can chain Given→When→Then.
#[derive(Default)]
struct BddWorld {
    exit_code: Option<i32>,
    stderr: String,
    stdout: String,
    /// True when the command finished successfully (exit 0).
    success: bool,
    /// Env overrides accumulated by Given steps; merged into the subprocess.
    env_overrides: HashMap<String, String>,
    /// Optional working directory override for the subprocess.
    cwd: Option<PathBuf>,
    /// Owned temp project created by `已初始化 sdd 项目…` Given step. Kept here so
    /// it is not dropped (and deleted) before the scenario's When/Then run.
    fixture_dir: Option<TempDir>,
}

// Each scenario runs in a single thread, so thread-local storage avoids the
// parallel-test contention that a global Mutex would cause.
thread_local! {
    static WORLD: RefCell<Option<BddWorld>> = const { RefCell::new(None) };
}

fn reset_world() {
    WORLD.with(|w| *w.borrow_mut() = Some(BddWorld::default()));
}

fn with_world<F, R>(f: F) -> R
where
    F: FnOnce(&BddWorld) -> R,
{
    WORLD.with(|w| {
        let w = w.borrow();
        let w = w.as_ref().expect("world not initialized");
        f(w)
    })
}

fn llman_bin() -> PathBuf {
    PathBuf::from(env!("CARGO_BIN_EXE_llman"))
}

fn split_args(raw: &str) -> Vec<String> {
    // Whitespace split with quote awareness: keep quoted segments together.
    let mut args = Vec::new();
    let mut current = String::new();
    let mut in_single = false;
    let mut in_double = false;
    for ch in raw.chars() {
        match ch {
            '\'' if !in_double => in_single = !in_single,
            '"' if !in_single => in_double = !in_double,
            c if c.is_whitespace() && !in_single && !in_double => {
                if !current.is_empty() {
                    args.push(std::mem::take(&mut current));
                }
            }
            c => current.push(c),
        }
    }
    if !current.is_empty() {
        args.push(current);
    }
    args
}

fn run_llman(args_raw: &str) {
    let (env_overrides, cwd) = WORLD.with(|w| {
        let w = w.borrow();
        let w = w.as_ref().expect("world not initialized");
        (w.env_overrides.clone(), w.cwd.clone())
    });

    let mut cmd = Command::new(llman_bin());
    cmd.args(split_args(args_raw));
    cmd.env("LLMAN_CONFIG_DIR", "./artifacts/testing_config_home");
    for (k, v) in &env_overrides {
        cmd.env(k, v);
    }
    if let Some(dir) = &cwd {
        cmd.current_dir(dir);
    }
    let output = cmd.output().expect("run llman");
    record_output(output);
}

/// Run llman in a specific directory (for fixture setup); asserts success but
/// does NOT record output into the world (setup steps are not assertion targets).
fn run_llman_in(dir: &std::path::Path, args_raw: &str, extra_env: &[(&str, &str)]) {
    let mut cmd = Command::new(llman_bin());
    cmd.args(split_args(args_raw));
    cmd.env("LLMAN_CONFIG_DIR", "./artifacts/testing_config_home");
    for (k, v) in extra_env {
        cmd.env(k, v);
    }
    cmd.current_dir(dir);
    let output = cmd.output().expect("run llman in fixture");
    assert!(
        output.status.success(),
        "fixture setup command failed: `{args_raw}` in {}\nstdout:\n{}\nstderr:\n{}",
        dir.display(),
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );
}

// ---------------------------------------------------------------------------
// Given steps
// ---------------------------------------------------------------------------

#[given("llman 二进制已构建")]
fn given_binary_built() {
    reset_world();
    assert!(
        llman_bin().exists(),
        "llman binary not found at {}",
        llman_bin().display()
    );
}

#[given("{env_var} 为 {value}")]
fn given_env_var(env_var: String, value: String) {
    WORLD.with(|w| {
        let mut w = w.borrow_mut();
        let world = w.as_mut().expect("world not initialized");
        world.env_overrides.insert(env_var, value);
    });
}

#[given("今目录为 {cwd}")]
fn given_cwd(cwd: PathBuf) {
    WORLD.with(|w| {
        let mut w = w.borrow_mut();
        let world = w.as_mut().expect("world not initialized");
        world.cwd = Some(cwd);
    });
}

/// Create a seeded sdd project in a fresh TempDir and point the world's cwd at it.
/// `mode` = "on" writes a `bdd:` block (enables feature-as-spec); "off" omits it.
/// The project gets a `sample` spec (r1 + non-executable scenario note) and an
/// `add-scen` change whose delta adds r2, plus a live `.feature` when BDD-on so
/// index/validate have harness content. This mirrors
/// `tests/sdd_bdd_compat_tests.rs::seed_spec_and_change`.
fn seed_bdd_project(mode: &str) {
    // reset first (same convention as `llman 二进制已构建`) so the scenario starts
    // clean; then install the fixture.
    reset_world();
    let temp = TempDir::new().expect("create fixture tempdir");
    let dir = temp.path().to_path_buf();

    // init first (generates default BDD-off config); we overwrite config.yaml to
    // the requested bdd mode AFTER all authoring commands, because some sdd
    // subcommands rewrite config.yaml on write paths.
    run_llman_in(&dir, "sdd init --lang en", &[]);

    // Single-track (r131): seed `sample` as one `.feature` with a @human rule
    // plus an executable acceptance scenario for harness content.
    write_single_track_spec(&dir, "sample", &[("r1", "R1")]);
    let sample_feature = dir.join("llmanspec/specs/sample/sample.feature");
    let mut body = std::fs::read_to_string(&sample_feature).expect("read seeded feature");
    body.push_str(
        "\n  @req:r1 @executable\n  Scenario: harness-happy\n    Given a precondition\n    When an action\n    Then an outcome\n",
    );
    std::fs::write(&sample_feature, body).expect("append acceptance scenario");

    // author add-scen change: proposal only (delta specs are removed, r115).
    let change_dir = dir.join("llmanspec/changes/add-scen");
    std::fs::create_dir_all(&change_dir).expect("mkdir fixture change");
    std::fs::write(
        change_dir.join("proposal.md"),
        "## Why\nAdd r2 to sample.\n\n## What Changes\n- Add requirement r2.\n",
    )
    .expect("write fixture proposal");
    std::fs::write(change_dir.join("design.md"), "# Design\n").expect("write fixture design");
    std::fs::write(change_dir.join("tasks.md"), "- [x] t1\n").expect("write fixture tasks");

    // Overwrite config.yaml to the requested bdd mode AFTER authoring (authoring
    // commands rewrite config.yaml, so this must be the last config write).
    // rstest-bdd captures quoted placeholders verbatim, so `bdd 配置为 "on"` yields
    // mode = "\"on\"" — strip quotes before comparing.
    let mode_norm = mode.trim().trim_matches('"');
    let mut config = "schema: spec-driven\nlocale: en\n".to_string();
    if mode_norm == "on" {
        config.push_str("\nbdd:\n  run_command: \"cargo test --features bdd\"\n");
    }
    std::fs::write(dir.join("llmanspec/config.yaml"), config).expect("write fixture config");

    // Regenerated skills must match final bdd mode (r95 metadata gate).
    run_llman_in(&dir, "sdd init --update", &[]);

    // git init+commit: staleness checks need a base ref.
    Command::new("git")
        .args(["init", "--quiet", "--initial-branch=main"])
        .current_dir(&dir)
        .output()
        .expect("git init fixture");
    // Local identity so internal `git commit` calls (e.g. finalize's auto
    // commit) work on CI runners without a global git identity.
    Command::new("git")
        .args(["config", "user.name", "t"])
        .current_dir(&dir)
        .output()
        .expect("git config user.name");
    Command::new("git")
        .args(["config", "user.email", "t@x"])
        .current_dir(&dir)
        .output()
        .expect("git config user.email");
    Command::new("git")
        .args(["add", "."])
        .current_dir(&dir)
        .output()
        .expect("git add fixture");
    Command::new("git")
        .args([
            "-c",
            "user.name=t",
            "-c",
            "user.email=t@x",
            "commit",
            "-qm",
            "fixture",
        ])
        .current_dir(&dir)
        .output()
        .expect("git commit fixture");

    WORLD.with(|w| {
        let mut w = w.borrow_mut();
        let world = w.as_mut().expect("world not initialized");
        world.fixture_dir = Some(temp);
        world.cwd = Some(dir);
    });
}

fn fixture_cwd() -> PathBuf {
    WORLD.with(|w| {
        w.borrow()
            .as_ref()
            .expect("world not initialized")
            .cwd
            .clone()
            .expect("fixture cwd missing")
    })
}

#[given("已初始化含多个 capability 且无占位符计数 run_command 的 sdd 项目")]
fn given_multi_cap_counter_run_command() {
    reset_world();
    let temp = TempDir::new().expect("create fixture tempdir");
    let dir = temp.path().to_path_buf();

    run_llman_in(&dir, "sdd init --lang en", &[]);

    for (name, req) in [("sample", "r1"), ("other", "r2")] {
        write_single_track_spec(&dir, name, &[(req, name)]);
    }

    // Project-wide runner with no {feature_*} placeholders; each spawn appends one line.
    let config = "schema: spec-driven\nlocale: en\n\nbdd:\n  run_command: \"printf 'x\\n' >> .bdd-run-count\"\n";
    std::fs::write(dir.join("llmanspec/config.yaml"), config).expect("write counter config");
    run_llman_in(&dir, "sdd init --update", &[]);

    // git init+commit: staleness checks need a base ref.
    Command::new("git")
        .args(["init", "--quiet"])
        .current_dir(&dir)
        .output()
        .expect("git init fixture");
    Command::new("git")
        .args(["add", "."])
        .current_dir(&dir)
        .output()
        .expect("git add fixture");
    Command::new("git")
        .args([
            "-c",
            "user.name=t",
            "-c",
            "user.email=t@x",
            "commit",
            "-qm",
            "fixture",
        ])
        .current_dir(&dir)
        .output()
        .expect("git commit fixture");

    WORLD.with(|w| {
        let mut w = w.borrow_mut();
        let world = w.as_mut().expect("world not initialized");
        world.fixture_dir = Some(temp);
        world.cwd = Some(dir);
    });
}

/// Write a minimal valid single-track spec for `name` with the given rules.
fn write_single_track_spec(dir: &std::path::Path, name: &str, reqs: &[(&str, &str)]) {
    let spec_dir = dir.join(format!("llmanspec/specs/{name}"));
    std::fs::create_dir_all(&spec_dir).expect("mkdir spec dir");
    let mut body = format!(
        "# language: en\n# capability: {name}\n# purpose: {name}\n# scope: llmanspec/specs/{name}\n\nFeature: {name}\n"
    );
    for (id, title) in reqs {
        body.push_str(&format!(
            "\n  @req:{id} @human\n  Scenario: {title}\n    System MUST cover {title}.\n"
        ));
    }
    std::fs::write(spec_dir.join(format!("{name}.feature")), body).expect("write feature");
}

#[given("已初始化 sdd 项目且 bdd 配置为 {mode}")]
fn given_seeded_sdd_project(mode: String) {
    seed_bdd_project(&mode);
}

/// Two capabilities share the same req_id — triggers global uniqueness ERROR.
#[given("已初始化含跨 spec 重复 req_id 的 sdd 项目且 bdd 配置为 {mode}")]
fn given_sdd_project_global_req_collision(mode: String) {
    seed_bdd_project(&mode);
    let dir = fixture_cwd();
    // Second capability reuses r1 (sample already has r1).
    write_single_track_spec(&dir, "other", &[("r1", "Other")]);
}

/// Seed a project then plant an occupied custom tag for add-req guard tests.
#[given("已初始化含已占用全局 req_id 的 sdd 项目且 bdd 配置为 {mode}")]
fn given_sdd_project_occupied_req(mode: String) {
    seed_bdd_project(&mode);
    let dir = fixture_cwd();
    write_single_track_spec(&dir, "sample", &[("r1", "R1"), ("occupied-id", "Occupied")]);
}

/// Seed a project then corrupt an extra change proposal (unknown depends_on
/// ref) so `validate --all` reports a change-level ERROR — review CRITICAL
/// exit-code fixture.
#[given("已初始化含损坏 proposal 的 sdd 项目且 bdd 配置为 {mode}")]
fn given_sdd_project_corrupted_proposal(mode: String) {
    seed_bdd_project(&mode);
    let dir = fixture_cwd();
    let changes_dir = dir.join("llmanspec/changes/broken");
    std::fs::create_dir_all(&changes_dir).expect("create change dir");
    std::fs::write(
        changes_dir.join("proposal.md"),
        "---\ndepends_on: [nonexistent-change]\n---\n\n## Why\nx\n\n## What Changes\n- y\n",
    )
    .expect("write corrupted proposal");
}

/// Seed a project with one active change `c123-fix-bug` plus an archived
/// change — the r112 prefix-match resolution fixture (Given for
/// prefix-match-baseline / prefix-match-hint).
#[given("存在 active change 和 archived change 且含 c123-fix-bug")]
fn given_active_and_archived_changes_with_c123() {
    reset_world();
    let temp = TempDir::new().expect("create fixture tempdir");
    let dir = temp.path().to_path_buf();
    run_llman_in(&dir, "sdd init --lang en", &[]);
    write_single_track_spec(&dir, "sample", &[("r1", "R1")]);

    // Active change c123-fix-bug (proposal + tasks + design).
    let active = dir.join("llmanspec/changes/c123-fix-bug");
    std::fs::create_dir_all(&active).expect("mkdir active change");
    std::fs::write(
        active.join("proposal.md"),
        "---\ndepends_on: []\n---\n\n## Why\nFix bug c123.\n\n## What Changes\n- Fix it.\n",
    )
    .expect("write active proposal");
    std::fs::write(active.join("design.md"), "# Design\n").expect("write design");
    std::fs::write(active.join("tasks.md"), "- [x] t1\n").expect("write tasks");

    // Archived change under changes/archive/.
    let archived = dir.join("llmanspec/changes/archive/c9-other");
    std::fs::create_dir_all(&archived).expect("mkdir archived change");
    std::fs::write(
        archived.join("proposal.md"),
        "---\ndepends_on: []\n---\n\n## Why\nOld change.\n\n## What Changes\n- Done.\n",
    )
    .expect("write archived proposal");
    std::fs::write(archived.join("design.md"), "# Design\n").expect("write archived design");
    std::fs::write(archived.join("tasks.md"), "- [x] t1\n").expect("write archived tasks");

    WORLD.with(|w| {
        let mut w = w.borrow_mut();
        let world = w.as_mut().expect("world not initialized");
        world.fixture_dir = Some(temp);
        world.cwd = Some(dir);
    });
}

/// Seed a full active change directory (proposal + design + all-done tasks) so
/// it introduces no unrelated validate noise.
fn write_complete_change(dir: &std::path::Path, id: &str) {
    let change_dir = dir.join("llmanspec/changes").join(id);
    std::fs::create_dir_all(&change_dir).expect("mkdir change");
    std::fs::write(
        change_dir.join("proposal.md"),
        "---\ndepends_on: []\n---\n\n## Why\nWhy.\n\n## What Changes\n- What.\n",
    )
    .expect("write proposal");
    std::fs::write(change_dir.join("design.md"), "# Design\n").expect("write design");
    std::fs::write(change_dir.join("tasks.md"), "- [x] t1\n").expect("write tasks");
}

/// Append a `change_id:` block (r29) to the fixture config.
fn write_change_id_config(dir: &std::path::Path, pattern: Option<&str>, template: Option<&str>) {
    let path = dir.join("llmanspec/config.yaml");
    let mut config = std::fs::read_to_string(&path).expect("read fixture config");
    config.push_str("\nchange_id:\n");
    if let Some(pattern) = pattern {
        config.push_str(&format!("  pattern: '{pattern}'\n"));
    }
    if let Some(template) = template {
        config.push_str(&format!("  template: '{template}'\n"));
    }
    std::fs::write(&path, config).expect("write change_id config");
}

/// r29 pattern gate: an active change id violating the configured pattern is
/// an ERROR, while the equally non-matching archive shape is never back-checked.
#[given("已初始化含 change_id pattern 与 archive 形态存量的 sdd 项目且存在违规 active change {id}")]
fn given_sdd_project_change_id_pattern_violation(id: String) {
    seed_bdd_project("on");
    let dir = fixture_cwd();
    write_change_id_config(&dir, Some(r"^c[0-9]+-(add|fix)-[a-z0-9-]+$"), None);
    // rstest-bdd captures quoted placeholders verbatim — strip the quotes.
    let raw_id = id.trim().trim_matches('"');
    write_complete_change(&dir, raw_id);
    // Archive shape that also violates the pattern: must stay ERROR-free.
    let archived = dir.join("llmanspec/changes/archive/2026-09-13-c20-legacy");
    std::fs::create_dir_all(&archived).expect("mkdir archived");
    std::fs::write(
        archived.join("proposal.md"),
        "---\ndepends_on: []\n---\n\n## Why\nOld.\n\n## What Changes\n- Done.\n",
    )
    .expect("write archived proposal");
}

/// r29 template generation: `change new --from --dry-run` renders the template
/// with the whole-tree unique number without creating anything.
#[given("已初始化含 change_id template 的 sdd 项目")]
fn given_sdd_project_change_id_template() {
    seed_bdd_project("on");
    let dir = fixture_cwd();
    write_change_id_config(
        &dir,
        None,
        Some("c{{ llman_sdd_unique_id }}-{{ verb }}-{{ subject }}"),
    );
}

/// r29 whole-tree unique-id scan: a deeply nested dir under a downstream-only
/// directory (delayed-changes/) carries the highest number and must win.
#[given("已初始化含 change_id 段且 delayed-changes 深层目录含更大号的 sdd 项目")]
fn given_sdd_project_delayed_changes_deeper_number() {
    seed_bdd_project("on");
    let dir = fixture_cwd();
    write_change_id_config(
        &dir,
        Some(r"^c[0-9]+-(add|fix)-[a-z0-9-]+$"),
        Some("c{{ llman_sdd_unique_id }}-{{ verb }}-{{ subject }}"),
    );
    let deep = dir.join("llmanspec/delayed-changes/tools/c2620-tool-x");
    std::fs::create_dir_all(&deep).expect("mkdir deep delayed change");
}

/// BDD fixture with a leftover legacy `spec.toon` next to the single-track
/// feature — triggers the r131 migration-pointer ERROR.
#[given("已初始化含遗留 spec.toon 的 sdd 项目且 bdd 配置为 {mode}")]
fn given_sdd_project_legacy_toon(mode: String) {
    seed_bdd_project(&mode);
    let dir = fixture_cwd();
    std::fs::write(
        dir.join("llmanspec/specs/sample/spec.toon"),
        concat!(
            "kind: llman.sdd.spec\n",
            "name: \"sample\"\n",
            "purpose: \"sample legacy\"\n",
            "valid_scope[1]: \"llmanspec/specs/sample\"\n",
            "requirements[1]{req_id,title,statement}:\n",
            "  r1,R1,\"System MUST do X.\"\n",
            "scenarios[0]:\n",
        ),
    )
    .expect("write legacy toon");
}

/// BDD fixture with a toon-ONLY `legacy` capability (no `.feature` in the
/// dir) — migrate creates `legacy.feature` from spec.toon alone.
#[given("已初始化含仅遗留 spec.toon 的 legacy capability 且 bdd 配置为 {mode}")]
fn given_sdd_project_toon_only_capability(mode: String) {
    seed_bdd_project(&mode);
    let dir = fixture_cwd();
    let spec_dir = dir.join("llmanspec/specs/legacy");
    std::fs::create_dir_all(&spec_dir).expect("mkdir legacy capability");
    std::fs::write(
        spec_dir.join("spec.toon"),
        concat!(
            "kind: llman.sdd.spec\n",
            "name: \"legacy\"\n",
            "purpose: \"legacy notes\"\n",
            "valid_scope[1]: \"llmanspec/specs/legacy\"\n",
            "requirements[1]{req_id,title,statement}:\n",
            "  r1,R1,\"System MUST do X.\"\n",
            "scenarios[0]:\n",
        ),
    )
    .expect("write toon-only spec.toon");
}

/// BDD fixture: `sample3` has a legacy spec.toon (GWT rows: two paired, one
/// unpaired, one contentless) plus a live legacy multi-file `.feature` with an
/// @executable scenario — migrate must leave the .feature untouched and
/// convert the GWT toon rows into @human note scenarios (r136).
#[given("已初始化含遗留 spec.toon 与既有 .feature 的 sample3 capability 且 bdd 配置为 {mode}")]
fn given_sdd_project_toon_with_existing_features(mode: String) {
    seed_bdd_project(&mode);
    let dir = fixture_cwd();
    let spec_dir = dir.join("llmanspec/specs/sample3");
    std::fs::create_dir_all(&spec_dir).expect("mkdir sample3 capability");
    std::fs::write(
        spec_dir.join("spec.toon"),
        concat!(
            "kind: llman.sdd.spec\n",
            "name: \"sample3\"\n",
            "purpose: \"sample3 legacy\"\n",
            "valid_scope[1]: \"llmanspec/specs/sample3\"\n",
            "requirements[1]{req_id,title,statement}:\n",
            "  r1,R1,\"System MUST do X.\"\n",
            "scenarios[4]{req_id,id,given,when,then,feature}:\n",
            "  r1,acc-1,\"precondition ready\",\"run llman sdd validate sample3\",\"exit code is zero\",true\n",
            "  r1,acc-2,\"\",\"run llman sdd status\",\"status shows sample3\",true\n",
            "  r404,orphan,\"\",\"a trigger\",\"an outcome\",true\n",
            "  r1,note,\"\",\"\",\"\",false\n",
        ),
    )
    .expect("write sample3 spec.toon");
    std::fs::write(
        spec_dir.join("legacy-acc.feature"),
        concat!(
            "# language: en\n",
            "Feature: sample3 legacy acceptance\n",
            "  @req:r1 @executable\n",
            "  Scenario: legacy-acc\n",
            "    Given seeded\n",
            "    When noop\n",
            "    Then ok\n",
        ),
    )
    .expect("write sample3 legacy .feature");
}

/// Flat-layout fixtures (spec-format r131 dual layout + r141 specs-flatten).
/// All flat/dir spec bodies scope to `llmanspec` (always exists in the
/// fixture) so `validate --strict`'s scope-existence gate passes.

fn write_flat_spec(dir: &std::path::Path, name: &str, req_id: &str) {
    let body = format!(
        concat!(
            "# language: en\n",
            "# capability: {name}\n",
            "# purpose: {name}\n",
            "# scope: llmanspec\n",
            "\n",
            "Feature: {name}\n",
            "\n",
            "  @req:{req} @human\n",
            "  Scenario: {req}\n",
            "    System MUST cover {name}.\n",
        ),
        name = name,
        req = req_id,
    );
    std::fs::write(dir.join(format!("llmanspec/specs/{name}.feature")), body)
        .expect("write flat feature");
}

fn write_dir_spec_file(
    dir: &std::path::Path,
    cap: &str,
    file_name: &str,
    req_id: Option<&str>,
    scope: &str,
) {
    let spec_dir = dir.join(format!("llmanspec/specs/{cap}"));
    std::fs::create_dir_all(&spec_dir).expect("mkdir spec dir");
    let mut body = format!(
        "# language: en\n# capability: {cap}\n# purpose: {cap}\n# scope: {scope}\n\nFeature: {cap}\n"
    );
    if let Some(req) = req_id {
        body.push_str(&format!(
            "\n  @req:{req} @human\n  Scenario: {req}\n    System MUST cover {cap}.\n"
        ));
    }
    std::fs::write(spec_dir.join(file_name), body).expect("write dir feature");
}

/// Fixture: one flat capability `specs/flatcap.feature` — r131 flat layout is
/// recognized by list/show/validate.
#[given("已初始化含扁平 capability 的 sdd 项目且 bdd 配置为 {mode}")]
fn given_sdd_project_flat_capability(mode: String) {
    seed_bdd_project(&mode);
    let dir = fixture_cwd();
    write_flat_spec(&dir, "flatcap", "r3");
}

/// Fixture: flat `specs/foo.feature` AND directory `specs/foo/foo.feature` —
/// same-id dual-source conflict must ERROR (spec-format r131).
#[given("已初始化含同 id 扁平与目录冲突的 sdd 项目且 bdd 配置为 {mode}")]
fn given_sdd_project_flat_dir_conflict(mode: String) {
    seed_bdd_project(&mode);
    let dir = fixture_cwd();
    write_flat_spec(&dir, "foo", "r3");
    write_dir_spec_file(&dir, "foo", "foo.feature", Some("r4"), "llmanspec");
}

/// Fixture: directory `specs/multi/` with the same-named main file plus a
/// second draft `.feature` — validate stays green with a WARNING (r131, D4).
#[given("已初始化含多 .feature 目录 capability 的 sdd 项目且 bdd 配置为 {mode}")]
fn given_sdd_project_multi_feature_dir(mode: String) {
    seed_bdd_project(&mode);
    let dir = fixture_cwd();
    write_dir_spec_file(&dir, "multi", "multi.feature", Some("r3"), "llmanspec");
    write_dir_spec_file(&dir, "multi", "draft.feature", None, "llmanspec");
}

/// Fixture: directory `specs/solocap/` whose single `.feature` has a foreign
/// name — the resolver backfills it as the main file (spec-format r131).
#[given("已初始化含异名单文件目录 capability 的 sdd 项目且 bdd 配置为 {mode}")]
fn given_sdd_project_single_foreign_named_dir(mode: String) {
    seed_bdd_project(&mode);
    let dir = fixture_cwd();
    write_dir_spec_file(&dir, "solocap", "inner.feature", Some("r4"), "llmanspec");
}

/// Fixture: pure single-file directory `specs/scoped/scoped.feature` with a
/// self-referential `# scope:` — the specs-flatten target (spec-format r141).
#[given("已初始化含自引用 scope 单文件目录的 sdd 项目且 bdd 配置为 {mode}")]
fn given_sdd_project_self_scope_single_dir(mode: String) {
    seed_bdd_project(&mode);
    let dir = fixture_cwd();
    write_dir_spec_file(
        &dir,
        "scoped",
        "scoped.feature",
        Some("r5"),
        "llmanspec/specs/scoped",
    );
}

/// Fixture: one directory per non-flattenable class — conflict (flat target
/// exists), legacy (spec.toon), multi (two .feature), aux (notes.md),
/// misnamed (single foreign-named .feature). specs-flatten skips all five.
#[given("已初始化含五类不可扁平目录的 sdd 项目且 bdd 配置为 {mode}")]
fn given_sdd_project_five_skip_classes(mode: String) {
    seed_bdd_project(&mode);
    let dir = fixture_cwd();
    // conflict: flat target exists alongside the same-id directory.
    write_flat_spec(&dir, "foo", "r3");
    write_dir_spec_file(&dir, "foo", "foo.feature", Some("r4"), "llmanspec");
    // legacy: spec.toon in the directory.
    write_dir_spec_file(&dir, "legacy", "keep.feature", Some("r6"), "llmanspec");
    std::fs::write(
        dir.join("llmanspec/specs/legacy/spec.toon"),
        "kind: llman.sdd.spec\nname: \"legacy\"\n",
    )
    .expect("write legacy toon");
    // multi: two .feature files, no same-named main.
    write_dir_spec_file(&dir, "multiskip", "a.feature", Some("r7"), "llmanspec");
    write_dir_spec_file(&dir, "multiskip", "b.feature", None, "llmanspec");
    // aux: .feature plus an auxiliary file.
    write_dir_spec_file(&dir, "auxdir", "aux.feature", Some("r8"), "llmanspec");
    std::fs::write(dir.join("llmanspec/specs/auxdir/notes.md"), "notes\n").expect("write aux file");
    // misnamed: single .feature whose name differs from the directory.
    write_dir_spec_file(&dir, "bar", "other.feature", Some("r9"), "llmanspec");
}

/// BDD-on fixture whose acceptance `@req` points at a missing rule id.
#[given("已初始化含无效 @req 的 sdd 项目且 bdd 配置为 {mode}")]
fn given_sdd_project_bad_req(mode: String) {
    seed_bdd_project(&mode);
    let dir = fixture_cwd();
    let path = dir.join("llmanspec/specs/sample/sample.feature");
    let body = std::fs::read_to_string(&path).expect("read sample feature");
    let updated = body.replace("@req:r1 @executable", "@req:r999 @executable");
    std::fs::write(&path, updated).expect("write dangling @req feature");
}

#[given("项目中存在技能目录 {name}")]
fn given_skill_dir(name: String) {
    let dir = fixture_cwd();
    let skill_dir = dir
        .join(".agents/skills")
        .join(name.trim().trim_matches('"'));
    std::fs::create_dir_all(&skill_dir).expect("mkdir planted skill");
    std::fs::write(skill_dir.join("SKILL.md"), "planted\n").expect("write planted skill");
}

/// Plant a global config.yaml with one of three `skills` shapes into a fresh
/// temp dir, then point `LLMAN_CONFIG_DIR` at it. Used by config-schemas r125
/// executable scenarios (multi-repo / legacy-dir / missing-path). The temp dir
/// is owned by the world so it survives until the scenario's When/Then.
#[given("全局 config.yaml 含 {kind} skills 配置")]
fn given_global_skills_config(kind: String) {
    reset_world();
    let temp = TempDir::new().expect("create skills-config tempdir");
    let dir = temp.path().to_path_buf();
    let skills_yaml = match kind.trim() {
        "multi-repo" => {
            "skills:\n  repo:\n    - name: Team\n      path: /tmp/team-skills\n    - path: /tmp/personal-skills\n"
                .to_string()
        }
        "legacy-dir" => "skills:\n  dir: /tmp/skills\n".to_string(),
        "missing-path" => {
            // One present dir so resolve still succeeds; one missing to trigger warn+filter.
            let present = dir.join("present-skills");
            std::fs::create_dir_all(&present).expect("create present skills dir");
            let missing = dir.join("missing-skills");
            format!(
                "skills:\n  repo:\n    - name: gone\n      path: {}\n    - name: ok\n      path: {}\n",
                missing.display(),
                present.display()
            )
        }
        other => panic!("unknown skills config kind: {other}"),
    };
    let config = format!("version: \"0.1\"\ntools: {{}}\n{skills_yaml}");
    std::fs::write(dir.join("config.yaml"), config).expect("write global config");

    WORLD.with(|w| {
        let mut guard = w.borrow_mut();
        let world = guard.as_mut().expect("world not initialized");
        world.fixture_dir = Some(temp);
        world.env_overrides.insert(
            "LLMAN_CONFIG_DIR".to_string(),
            dir.to_string_lossy().to_string(),
        );
    });
}

#[given("项目 extra_skills 包含 {name}")]
fn given_extra_skills(name: String) {
    let dir = fixture_cwd();
    let skill = name.trim().trim_matches('"');
    let config_path = dir.join("llmanspec/config.yaml");
    let existing = std::fs::read_to_string(&config_path).unwrap_or_default();
    // Preserve an existing `bdd:` block so the runner config (r2/r95) stays consistent.
    let bdd_tail = existing
        .find("\nbdd:")
        .map(|i| existing[i + 1..].to_string())
        .or_else(|| {
            if existing.starts_with("bdd:") {
                Some(existing.clone())
            } else {
                None
            }
        });
    let mut config = format!("schema: spec-driven\nlocale: en\nextra_skills:\n  - {skill}\n");
    if let Some(bdd) = bdd_tail {
        // Keep only the bdd section if present at start of remainder.
        if let Some(rest) = bdd.strip_prefix("bdd:") {
            config.push_str("\nbdd:");
            config.push_str(rest);
        } else if bdd.starts_with("bdd:") {
            config.push('\n');
            config.push_str(&bdd);
        }
    }
    std::fs::write(&config_path, config).expect("write extra_skills config");
    // Refresh managed skills so the optional skill is installed with valid metadata (r95).
    run_llman_in(&dir, "sdd init --update", &[]);
}

/// Seed a project with a change directory carrying proposal+design+tasks, and
/// optionally a Git-native attach binding in proposal frontmatter. Used to
/// exercise `determine_stage` under BDD-on (r93): `attached = "yes"` writes
/// non-empty `branch` + `base_sha`; any other value omits them.
///
/// `{change}` is the change id (used as the branch name when attached). The
/// fixture must be combined with `已初始化 sdd 项目且 bdd 配置为 {mode}` first to
/// establish config + git base ref.
/// r42 fixture: seeded project whose single spec's `# scope:` header points
/// at a path that does not exist on disk, so strict validate must fail.
#[given("已初始化含失效 scope 路径 spec 的 sdd 项目且 bdd 配置为 {mode}")]
fn given_sdd_project_missing_scope_path(mode: String) {
    seed_bdd_project(&mode);
    let dir = fixture_cwd();
    let sample = dir.join("llmanspec/specs/sample/sample.feature");
    let body = std::fs::read_to_string(&sample).expect("read seeded feature");
    let body = body.replace("# scope: llmanspec/specs/sample", "# scope: docs/gone");
    std::fs::write(&sample, body).expect("rewrite scope header to missing path");
}

/// Seed a project with a change directory carrying proposal+design+tasks, and
/// optionally a Git-native attach binding in proposal frontmatter. Used to
/// exercise `determine_stage` under BDD-on (r93): `attached = "yes"` writes
/// non-empty `branch` + `base_sha`; any other value omits them.
///
/// `{change}` is the change id (used as the branch name when attached). The
/// fixture must be combined with `已初始化 sdd 项目且 bdd 配置为 {mode}` first to
/// establish config + git base ref.
/// r93 four-tier fixtures: proposal only (draft).
#[given("变更 {change} 仅含 proposal")]
fn given_change_proposal_only(change: String) {
    let dir = fixture_cwd();
    let change_dir = dir
        .join("llmanspec/changes")
        .join(change.trim().trim_matches('"'));
    std::fs::create_dir_all(&change_dir).expect("mkdir draft fixture change");
    std::fs::write(
        change_dir.join("proposal.md"),
        "---\ndepends_on: []\n---\n\n## Why\nr93 draft fixture.\n\n## What Changes\n- Probe determine_stage.\n",
    )
    .expect("write fixture proposal");
}

/// r93 four-tier fixtures: proposal + design, no tasks (designed).
#[given("变更 {change} 含 proposal 与 design 不含 tasks")]
fn given_change_proposal_and_design(change: String) {
    let dir = fixture_cwd();
    let change_dir = dir
        .join("llmanspec/changes")
        .join(change.trim().trim_matches('"'));
    std::fs::create_dir_all(&change_dir).expect("mkdir designed fixture change");
    std::fs::write(
        change_dir.join("proposal.md"),
        "---\ndepends_on: []\n---\n\n## Why\nr93 designed fixture.\n\n## What Changes\n- Probe determine_stage.\n",
    )
    .expect("write fixture proposal");
    std::fs::write(change_dir.join("design.md"), "# Design\nfixture.\n").expect("write design");
}

/// r1: lands a NEW locked rule on the bound branch (additions need no ack).
#[given("变更 {change} 绑定于已提交 specs 改动的分支")]
fn given_change_bound_with_landed_specs(change: String) {
    let dir = fixture_cwd();
    let change_dir = dir
        .join("llmanspec/changes")
        .join(change.trim().trim_matches('"'));
    std::fs::create_dir_all(&change_dir).expect("mkdir landed fixture change");
    let change_id = change.trim().trim_matches('"');
    std::fs::write(
        change_dir.join("proposal.md"),
        format!("---\ndepends_on: []\nbranch: feat/{change_id}\nbase_sha: 0000000000000000000000000000000000000000\n---\n\n## Why\nr1 landed fixture.\n\n## What Changes\n- Add a rule.\n"),
    )
    .expect("write fixture proposal");
    std::fs::write(change_dir.join("design.md"), "# Design\nfixture.\n").expect("write design");
    std::fs::write(change_dir.join("tasks.md"), "- [x] t1\n").expect("write tasks");
    run_fixture_git(
        &dir,
        &["checkout", "-q", "-b", &format!("feat/{change_id}")],
    );
    run_fixture_git(&dir, &["add", "-A"]);
    run_fixture_git(
        &dir,
        &["commit", "-qm", &format!("fixture change {change_id}")],
    );
    let head = current_fixture_head(&dir);
    let proposal_path = change_dir.join("proposal.md");
    let proposal_body = std::fs::read_to_string(&proposal_path).expect("read fixture proposal");
    std::fs::write(
        &proposal_path,
        proposal_body.replace("0000000000000000000000000000000000000000", &head),
    )
    .expect("rewrite fixture base_sha");
    // Specs landing: add a brand-new @human rule (additions are ack-free).
    let feature_path = dir.join("llmanspec/specs/sample/sample.feature");
    let mut body = std::fs::read_to_string(&feature_path).expect("read seeded feature");
    body.push_str("\n  @req:r99 @human\n  Scenario: R99\n    System MUST cover R99.\n");
    std::fs::write(&feature_path, body).expect("append new locked rule");
    run_fixture_git(&dir, &["add", "-A"]);
    run_fixture_git(&dir, &["commit", "-qm", "specs landing"]);
}

/// r25: full finalize fixture — bound, tasks done, specs landed, clean tree.
#[given("存在可收尾的完整 change {change}")]
fn given_finalizable_change(change: String) {
    let dir = fixture_cwd();
    let change_dir = dir
        .join("llmanspec/changes")
        .join(change.trim().trim_matches('"'));
    std::fs::create_dir_all(&change_dir).expect("mkdir finalize fixture change");
    let change_id = change.trim().trim_matches('"');
    std::fs::write(
        change_dir.join("proposal.md"),
        format!("---\ndepends_on: []\nbranch: feat/{change_id}\nbase_sha: 0000000000000000000000000000000000000000\n---\n\n## Why\nr25 finalize fixture.\n\n## What Changes\n- Probe auto commit.\n"),
    )
    .expect("write fixture proposal");
    std::fs::write(change_dir.join("design.md"), "# Design\nfixture.\n").expect("write design");
    std::fs::write(change_dir.join("tasks.md"), "- [x] t1\n").expect("write tasks");
    run_fixture_git(
        &dir,
        &["checkout", "-q", "-b", &format!("feat/{change_id}")],
    );
    run_fixture_git(&dir, &["add", "-A"]);
    run_fixture_git(
        &dir,
        &["commit", "-qm", &format!("fixture change {change_id}")],
    );
    let head = current_fixture_head(&dir);
    let proposal_path = change_dir.join("proposal.md");
    let proposal_body = std::fs::read_to_string(&proposal_path).expect("read fixture proposal");
    std::fs::write(
        &proposal_path,
        proposal_body.replace("0000000000000000000000000000000000000000", &head),
    )
    .expect("rewrite fixture base_sha");
    // Specs landing (new rule, ack-free).
    let feature_path = dir.join("llmanspec/specs/sample/sample.feature");
    let mut body = std::fs::read_to_string(&feature_path).expect("read seeded feature");
    body.push_str("\n  @req:r98 @human\n  Scenario: R98\n    System MUST cover R98.\n");
    std::fs::write(&feature_path, body).expect("append new locked rule");
    run_fixture_git(&dir, &["add", "-A"]);
    run_fixture_git(&dir, &["commit", "-qm", "specs landing"]);
}

/// r132: a lone @agent scenario (no @human) must fail validation.
#[given("已初始化含单独 @agent 场景的 sdd 项目且 bdd 配置为 {mode}")]
fn given_sdd_project_lone_agent(mode: String) {
    seed_bdd_project(&mode);
    let dir = fixture_cwd();
    let feature_path = dir.join("llmanspec/specs/sample/sample.feature");
    let mut body = std::fs::read_to_string(&feature_path).expect("read seeded feature");
    body.push_str("\n  @req:r97 @agent\n  Scenario: AgentAlone\n    System MUST do A.\n");
    std::fs::write(&feature_path, body).expect("append lone @agent scenario");
}

/// r135: bound change that edits a locked rule. `kind` = "@agent" (the rule
/// carries @agent) or "普通" (plain @human). No rules_touched declared.
#[given("变更 {change} 绑定且编辑了规则 {kind}")]
fn given_change_bound_editing_locked_rule(change: String, _kind: String) {
    let dir = fixture_cwd();
    let change_dir = dir
        .join("llmanspec/changes")
        .join(change.trim().trim_matches('"'));
    std::fs::create_dir_all(&change_dir).expect("mkdir rule-edit fixture change");
    let change_id = change.trim().trim_matches('"');
    std::fs::write(
        change_dir.join("proposal.md"),
        format!("---\ndepends_on: []\nbranch: feat/{change_id}\nbase_sha: 0000000000000000000000000000000000000000\n---\n\n## Why\nr135 fixture.\n\n## What Changes\n- Edit a locked rule.\n"),
    )
    .expect("write fixture proposal");
    std::fs::write(change_dir.join("design.md"), "# Design\nfixture.\n").expect("write design");
    std::fs::write(change_dir.join("tasks.md"), "- [x] t1\n").expect("write tasks");
    run_fixture_git(
        &dir,
        &["checkout", "-q", "-b", &format!("feat/{change_id}")],
    );
    run_fixture_git(&dir, &["add", "-A"]);
    run_fixture_git(
        &dir,
        &["commit", "-qm", &format!("fixture change {change_id}")],
    );
    let head = current_fixture_head(&dir);
    let proposal_path = change_dir.join("proposal.md");
    let proposal_body = std::fs::read_to_string(&proposal_path).expect("read fixture proposal");
    std::fs::write(
        &proposal_path,
        proposal_body.replace("0000000000000000000000000000000000000000", &head),
    )
    .expect("rewrite fixture base_sha");
    run_fixture_git(&dir, &["add", "-A"]);
    run_fixture_git(&dir, &["commit", "-qm", "binding"]);
    // Edit the locked r1 rule.
    let feature_path = dir.join("llmanspec/specs/sample/sample.feature");
    fixture_edit_r1(&dir, "(edited by r135 fixture)");
    // Landing counts committed diffs; commit the rule edit.
    run_fixture_git(&dir, &["add", "-A"]);
    run_fixture_git(&dir, &["commit", "-qm", "edit locked rule"]);
}

/// r135 (issue #18): bound change that deletes one of two duplicate-`@req`
/// locked scenarios (same id, different content). The duplicate is seeded and
/// committed BEFORE binding, so the base side carries both hashes.
#[given("变更 {change} 绑定且删除了重复 @req 锁定场景之一")]
fn given_change_bound_deleting_duplicate_req_rule(change: String) {
    let dir = fixture_cwd();
    let change_id = change.trim().trim_matches('"');
    let feature_path = dir.join("llmanspec/specs/sample/sample.feature");
    let dup_block = "\n  @req:r1 @human\n  Scenario: R1b\n    System MUST cover R1 differently.\n";

    // Seed the duplicate r1 scenario on the base side.
    let mut body = std::fs::read_to_string(&feature_path).expect("read seeded feature");
    body.push_str(dup_block);
    std::fs::write(&feature_path, body).expect("append duplicate r1 rule");
    run_fixture_git(&dir, &["add", "-A"]);
    run_fixture_git(&dir, &["commit", "-qm", "seed duplicate r1 rule"]);

    // Change docs + binding (same pattern as the r135 edit fixture).
    let change_dir = dir.join("llmanspec/changes").join(change_id);
    std::fs::create_dir_all(&change_dir).expect("mkdir dup-delete fixture change");
    std::fs::write(
        change_dir.join("proposal.md"),
        format!(
            "---\ndepends_on: []\nbranch: feat/{change_id}\nbase_sha: 0000000000000000000000000000000000000000\n---\n\n## Why\nr135 duplicate-req fixture.\n\n## What Changes\n- Delete a duplicate locked rule.\n"
        ),
    )
    .expect("write fixture proposal");
    std::fs::write(change_dir.join("design.md"), "# Design\nfixture.\n").expect("write design");
    std::fs::write(change_dir.join("tasks.md"), "- [x] t1\n").expect("write tasks");
    run_fixture_git(
        &dir,
        &["checkout", "-q", "-b", &format!("feat/{change_id}")],
    );
    run_fixture_git(&dir, &["add", "-A"]);
    run_fixture_git(
        &dir,
        &["commit", "-qm", &format!("fixture change {change_id}")],
    );
    let head = current_fixture_head(&dir);
    let proposal_path = change_dir.join("proposal.md");
    let proposal_body = std::fs::read_to_string(&proposal_path).expect("read fixture proposal");
    std::fs::write(
        &proposal_path,
        proposal_body.replace("0000000000000000000000000000000000000000", &head),
    )
    .expect("rewrite fixture base_sha");
    run_fixture_git(&dir, &["add", "-A"]);
    run_fixture_git(&dir, &["commit", "-qm", "binding"]);

    // Specs landing: delete the duplicate R1b scenario (keep R1).
    let body = std::fs::read_to_string(&feature_path).expect("read feature for delete");
    let deleted = body.replace(dup_block, "");
    assert!(deleted != body, "duplicate scenario block must be present");
    std::fs::write(&feature_path, deleted).expect("delete duplicate r1 rule");
    run_fixture_git(&dir, &["add", "-A"]);
    run_fixture_git(&dir, &["commit", "-qm", "delete duplicate locked rule"]);
}

#[given("变更 {change} 含 proposal design tasks 且 attach 状态为 {attached}")]
fn given_change_with_artifacts_and_attach(change: String, attached: String) {
    let dir = fixture_cwd();
    let change_dir = dir.join("llmanspec/changes").join(&change);
    std::fs::create_dir_all(&change_dir).expect("mkdir attach-stage fixture change");
    let attach_flag = attached.trim().trim_matches('"');
    let bound = matches!(attach_flag, "yes" | "true" | "attached" | "on" | "skip");
    let base_sha_placeholder = "0000000000000000000000000000000000000000";
    let frontmatter = match attach_flag {
        "yes" | "true" | "attached" | "on" => {
            format!(
                "---\ndepends_on: []\nbranch: feat/{change}\nbase_sha: {base_sha_placeholder}\n---\n"
            )
        }
        "skip" => {
            format!(
                "---\ndepends_on: []\nbranch: feat/{change}\nbase_sha: {base_sha_placeholder}\nneeds_specs_change: false\n---\n"
            )
        }
        _ => "---\ndepends_on: []\n---\n".to_string(),
    };
    // `parse_change` (used by `show`) requires both `## Why` and `## What Changes`.
    let proposal = format!(
        "{frontmatter}\n## Why\nr93 stage fixture.\n\n## What Changes\n- Probe determine_stage.\n"
    );
    std::fs::write(change_dir.join("proposal.md"), proposal).expect("write fixture proposal");
    std::fs::write(change_dir.join("design.md"), "# Design\nr93 fixture.\n").expect("write design");
    // git-native-v2 gateChecks: the skip variant must pass EVERY gate (incl.
    // tasks-done) so `readyToImplement=true` keeps holding — mark tasks done.
    let tasks = if attach_flag == "skip" {
        "- [x] t1\n"
    } else {
        "- [ ] t1\n"
    };
    std::fs::write(change_dir.join("tasks.md"), tasks).expect("write tasks");

    if bound {
        // Attached changes live on their binding branch: create it and commit
        // the change docs. base_sha = the branch tip so `base...HEAD` stays
        // empty (specsLanded=false for r93 show scenarios) while diff plumbing
        // (r137 commitCount) has real refs to work with. The final base_sha
        // rewrite stays dirty in the working tree and is invisible to
        // committed-diff based signals — EXCEPT the skip variant, which must
        // be clean (and committed) to pass the clean-tree gate (git-native-v2).
        run_fixture_git(&dir, &["checkout", "-q", "-b", &format!("feat/{change}")]);
        run_fixture_git(&dir, &["add", "-A"]);
        run_fixture_git(
            &dir,
            &["commit", "-qm", &format!("fixture change {change}")],
        );
        let head = current_fixture_head(&dir);
        let proposal_path = change_dir.join("proposal.md");
        let proposal_body = std::fs::read_to_string(&proposal_path).expect("read fixture proposal");
        std::fs::write(
            &proposal_path,
            proposal_body.replace(base_sha_placeholder, &head),
        )
        .expect("rewrite fixture base_sha");
        if attach_flag == "skip" {
            run_fixture_git(&dir, &["add", "-A"]);
            run_fixture_git(&dir, &["commit", "-qm", "fixture skip binding"]);
        }
    }
}

fn current_fixture_head(dir: &std::path::Path) -> String {
    String::from_utf8_lossy(
        &Command::new("git")
            .args(["rev-parse", "HEAD"])
            .current_dir(dir)
            .output()
            .expect("git rev-parse fixture")
            .stdout,
    )
    .trim()
    .to_string()
}

/// Git-native v2 D1 fixture: emulates the accumulation-immune lock-gate
/// regression on a real git history — a previous change's locked-rule edit is
/// ff-merged into the local default branch, then THIS change binds (stored
/// base_sha = pre-merge merge-base), the default branch moves again with a
/// second rule edit, and this change merges it back. Zero push anywhere; the
/// change itself edits no rules and declares no ack. Under the new live
/// merge-base anchor the gate must stay green; the stored base_sha range
/// would have flagged the merged edits (blanket-ack era).
#[given("变更 {change} 绑定于先前规则编辑已合入默认分支零推送的历史")]
fn given_change_bound_after_prior_rule_merge(change: String) {
    let dir = fixture_cwd();
    let default = String::from_utf8_lossy(
        &Command::new("git")
            .args(["rev-parse", "--abbrev-ref", "HEAD"])
            .current_dir(&dir)
            .output()
            .expect("git branch name fixture")
            .stdout,
    )
    .trim()
    .to_string();

    // 1) Previous change's locked-rule edit on a side branch, ff-merged into
    //    the default branch (simulates an archived change's specs landing).
    run_fixture_git(&dir, &["checkout", "-q", "-b", "feat/prev"]);
    fixture_edit_r1(&dir, "(v2 by previous change)");
    run_fixture_git(&dir, &["add", "-A"]);
    run_fixture_git(&dir, &["commit", "-qm", "prev-rule-edit"]);
    run_fixture_git(&dir, &["checkout", "-q", &default]);
    run_fixture_git(&dir, &["merge", "-q", "--ff-only", "feat/prev"]);

    // 2) This change binds at the current merge-base (stored base_sha must
    //    stay the PRE-merge anchor to prove accumulation immunity).
    let base = current_fixture_head(&dir);
    let change_id = change.trim().trim_matches('"');
    run_fixture_git(
        &dir,
        &["checkout", "-q", "-b", &format!("feat/{change_id}")],
    );
    let change_dir = dir.join("llmanspec/changes").join(change_id);
    std::fs::create_dir_all(&change_dir).expect("mkdir acc fixture change");
    std::fs::write(
        change_dir.join("proposal.md"),
        format!(
            "---\ndepends_on: []\nbranch: feat/{change_id}\nbase_sha: {base}\nneeds_specs_change: false\n---\n\n## Why\naccumulation-immunity fixture.\n\n## What Changes\n- No rule edits (prior edits already merged).\n"
        ),
    )
    .expect("write fixture proposal");
    std::fs::write(change_dir.join("design.md"), "# Design\nfixture.\n").expect("write design");
    std::fs::write(change_dir.join("tasks.md"), "- [x] t1\n").expect("write tasks");
    run_fixture_git(&dir, &["add", "-A"]);
    run_fixture_git(&dir, &["commit", "-qm", "acc-next docs"]);

    // 3) Default branch moves again with ANOTHER rule edit; this change merges
    //    it back — merge-base advances, the stored anchor would now flag the
    //    merged edit as this change's own violation.
    run_fixture_git(&dir, &["checkout", "-q", &default]);
    fixture_edit_r1(&dir, "(v3 on default)");
    run_fixture_git(&dir, &["add", "-A"]);
    run_fixture_git(&dir, &["commit", "-qm", "later-rule-edit"]);
    run_fixture_git(&dir, &["checkout", "-q", &format!("feat/{change_id}")]);
    run_fixture_git(&dir, &["merge", "-q", "--no-edit", &default]);
}

/// Rewrite the seeded `sample` capability's locked rule statement (changes the
/// normalized lock hash without touching the tag grammar). Idempotent across
/// repeated edits: each pass appends its own marker to the base sentence, so
/// the hash moves every time regardless of prior markers.
fn fixture_edit_r1(dir: &std::path::Path, suffix: &str) {
    let feature_path = dir.join("llmanspec/specs/sample/sample.feature");
    let mut body = std::fs::read_to_string(&feature_path).expect("read seeded feature");
    body = body.replace(
        "System MUST cover R1",
        &format!("System MUST cover R1 {suffix}"),
    );
    std::fs::write(&feature_path, body).expect("rewrite locked rule");
}

fn run_fixture_git(dir: &std::path::Path, args: &[&str]) {
    let status = Command::new("git")
        .args(["-c", "user.name=t", "-c", "user.email=t@x"])
        .args(args)
        .current_dir(dir)
        .status()
        .expect("git command runs");
    assert!(status.success(), "git {args:?} failed in fixture");
}

// ---------------------------------------------------------------------------
// When steps
// ---------------------------------------------------------------------------

#[when("运行 llman {args}")]
fn when_run_llman(args: String) {
    run_llman(&args);
}

#[when("在非交互终端运行 llman {args}")]
fn when_run_llman_noninteractive(args: String) {
    // No TTY in test harness → inherently non-interactive.
    run_llman(&args);
}

#[when("用前缀 c123 运行 llman {args}")]
fn when_run_llman_prefix_c123(args: String) {
    run_llman(&args);
}

#[when("用前缀运行 llman {args}")]
fn when_run_llman_any_prefix(args: String) {
    run_llman(&args);
}

// ---------------------------------------------------------------------------
// Then steps — exit codes
// ---------------------------------------------------------------------------

#[then("退出码为 {code:i32}")]
fn then_exit_code(code: i32) {
    with_world(|w| {
        let actual = w.exit_code.unwrap_or(-1);
        assert_eq!(actual, code, "expected exit code {code}, got {actual}");
    });
}

#[then("退出码非零")]
fn then_exit_nonzero() {
    with_world(|w| {
        assert!(
            !w.success,
            "expected non-zero exit code, got success (exit {:?})",
            w.exit_code
        );
    });
}

#[then("退出码为零")]
fn then_exit_zero() {
    with_world(|w| {
        assert!(
            w.success,
            "expected zero exit code, got failure (exit {:?})\nstdout:\n{}\nstderr:\n{}",
            w.exit_code, w.stdout, w.stderr
        );
    });
}

#[then("退出码非零且 stderr 包含 {text}")]
fn then_exit_nonzero_and_stderr_contains(text: String) {
    then_exit_nonzero();
    then_stderr_contains(text);
}

#[then("退出码为零且 stdout 为合法 JSON 且含 JSON 键 {key}")]
fn then_exit_zero_json_key(key: String) {
    then_exit_zero();
    then_stdout_is_json();
    then_stdout_has_json_key(key);
}

#[then("退出码为零且 stdout 为合法 JSON 且含 JSON 键 reqId 且含 JSON 键 capability")]
fn then_exit_zero_json_reqid_and_capability() {
    then_exit_zero();
    then_stdout_is_json();
    then_stdout_has_json_key("reqId".into());
    then_stdout_has_json_key("capability".into());
}

// ---------------------------------------------------------------------------
// Then steps — output substring assertions
// ---------------------------------------------------------------------------

#[then("stdout 包含 {text}")]
fn then_stdout_contains(text: String) {
    with_world(|w| {
        assert!(
            w.stdout.contains(&text),
            "expected stdout to contain {:?}, got: {}",
            text,
            w.stdout
        );
    });
}

#[then("对应的完整 change 被找到且输出正确")]
fn then_prefix_resolved_correctly() {
    // The prefix-resolved change appears in the human-readable output and the
    // run succeeded (exact match or prefix resolution found exactly one change).
    with_world(|w| {
        assert!(
            w.success,
            "prefix run should succeed, exit {:?}",
            w.exit_code
        );
        let combined = format!("{}\n{}", w.stdout, w.stderr);
        assert!(
            combined.contains("c123-fix-bug"),
            "expected output to mention the resolved change, got: {combined}"
        );
    });
}

#[then("stderr 包含 {text}")]
fn then_stderr_contains(text: String) {
    with_world(|w| {
        assert!(
            w.stderr.contains(&text),
            "expected stderr to contain {:?}, got: {}",
            text,
            w.stderr
        );
    });
}

#[then("stdout 不含 {text}")]
fn then_stdout_not_contains(text: String) {
    with_world(|w| {
        assert!(
            !w.stdout.contains(&text),
            "expected stdout to NOT contain {:?}, got: {}",
            text,
            w.stdout
        );
    });
}

#[then("stderr 不含 {text}")]
fn then_stderr_not_contains(text: String) {
    with_world(|w| {
        assert!(
            !w.stderr.contains(&text),
            "expected stderr to NOT contain {:?}, got: {}",
            text,
            w.stderr
        );
    });
}

// ---------------------------------------------------------------------------
// Then steps — JSON structure assertions
// ---------------------------------------------------------------------------

#[then("stdout 为合法 JSON")]
fn then_stdout_is_json() {
    with_world(|w| {
        serde_json::from_str::<serde_json::Value>(&w.stdout)
            .unwrap_or_else(|e| panic!("stdout is not valid JSON: {e}\n{}", w.stdout));
    });
}

#[then("stdout 为合法 JSON 且含 JSON 键 {key}")]
fn then_stdout_is_json_with_key(key: String) {
    with_world(|w| {
        let v: serde_json::Value = serde_json::from_str(&w.stdout)
            .unwrap_or_else(|e| panic!("stdout is not valid JSON: {e}\n{}", w.stdout));
        assert!(
            v.get(&key).is_some(),
            "JSON key `{key}` missing\n{}",
            w.stdout
        );
    });
}

#[then("stdout 的 JSON 键 {key} 为数字")]
fn then_stdout_json_key_is_number(key: String) {
    with_world(|w| {
        let v: serde_json::Value = serde_json::from_str(&w.stdout)
            .unwrap_or_else(|e| panic!("stdout is not valid JSON: {e}\n{}", w.stdout));
        let mut cur = &v;
        for part in key.split('.') {
            cur = if let Some(arr) = cur.as_array() {
                // dotted path may address array elements: `changes.0.idleDays`
                let idx: usize = part.parse().unwrap_or_else(|_| {
                    panic!("JSON path `{key}`: segment `{part}` is not an array index")
                });
                arr.get(idx)
                    .unwrap_or_else(|| panic!("JSON index `{key}` out of bounds\n{}", w.stdout))
            } else {
                cur.get(part)
                    .unwrap_or_else(|| panic!("JSON key `{key}` missing\n{}", w.stdout))
            };
        }
        assert!(
            cur.is_number(),
            "JSON key `{key}` is not a number\n{}",
            w.stdout
        );
    });
}

#[then("stdout 含 JSON 键 {key}")]
fn then_stdout_has_json_key(key: String) {
    with_world(|w| {
        let value: serde_json::Value = serde_json::from_str(&w.stdout)
            .unwrap_or_else(|e| panic!("stdout is not valid JSON: {e}\n{}", w.stdout));
        let obj = value.as_object().unwrap_or_else(|| {
            panic!("stdout JSON is not an object, cannot check key {key:?}");
        });
        assert!(
            obj.contains_key(&key),
            "expected stdout JSON to contain key {key:?}, got keys: {:?}",
            obj.keys().collect::<Vec<_>>()
        );
    });
}

/// Assert a top-level stdout JSON key equals a string value.
/// rstest-bdd captures quoted placeholders verbatim, so `{value}` may arrive as
/// `"full"` — surrounding quotes are stripped before comparison.
#[then("stdout 的 JSON 键 {key} 为 {value}")]
fn then_stdout_json_key_equals(key: String, value: String) {
    with_world(|w| {
        let parsed: serde_json::Value = serde_json::from_str(&w.stdout)
            .unwrap_or_else(|e| panic!("stdout is not valid JSON: {e}\n{}", w.stdout));
        let actual = parsed
            .get(&key)
            .unwrap_or_else(|| panic!("stdout JSON missing key {key:?}; got: {parsed}"));
        // Normalize both sides to JSON string form for comparison.
        let actual_str = match actual {
            serde_json::Value::String(s) => s.clone(),
            other => other.to_string(),
        };
        let expected = value.trim().trim_matches('"').to_string();
        assert!(
            actual_str == expected,
            "expected stdout JSON {key:?} = {expected:?}, got {actual_str:?}"
        );
    });
}

#[then("相对路径 {rel} 存在")]
fn then_rel_path_exists(rel: String) {
    let path = fixture_cwd().join(rel.trim().trim_matches('"'));
    assert!(path.exists(), "expected path to exist: {}", path.display());
}

#[then("相对路径 {rel} 行数为 {n:usize}")]
fn then_rel_path_line_count(rel: String, n: usize) {
    let path = fixture_cwd().join(rel.trim().trim_matches('"'));
    let content =
        std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
    let lines = content.lines().filter(|l| !l.is_empty()).count();
    assert_eq!(
        lines,
        n,
        "expected {n} non-empty lines in {}, got {lines}: {content:?}",
        path.display()
    );
}

#[then("相对路径 {rel} 不存在")]
fn then_rel_path_absent(rel: String) {
    let path = fixture_cwd().join(rel.trim().trim_matches('"'));
    assert!(
        !path.exists(),
        "expected path to be absent: {}",
        path.display()
    );
}

#[then("相对路径 {rel} 内容包含 {text}")]
fn then_rel_path_contains(rel: String, text: String) {
    let path = fixture_cwd().join(rel.trim().trim_matches('"'));
    let content =
        std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
    let needle = text.trim().trim_matches('"');
    assert!(
        content.contains(needle),
        "expected {} to contain {:?}, got: {:?}",
        path.display(),
        needle,
        content
    );
}

// ---------------------------------------------------------------------------
// Helper
// ---------------------------------------------------------------------------

fn record_output(output: std::process::Output) {
    let code = output.status.code();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let success = output.status.success();
    WORLD.with(|w| {
        let mut w = w.borrow_mut();
        let world = w.as_mut().expect("world not initialized");
        world.exit_code = code;
        world.stderr = stderr;
        world.stdout = stdout;
        world.success = success;
    });
}

// ---------------------------------------------------------------------------
// Scenario discovery — compile-time directory binding (Git-native BDD-on).
// Tag full-mode / CLI-drivable scenarios with `@executable`. Documentation-only
// features under llmanspec/specs remain untagged and are not expanded into tests.
// ---------------------------------------------------------------------------

scenarios!("llmanspec/specs", tags = "@executable");

/// r25: last commit subject assertion (used by finalize auto-commit scenarios).
#[then("最近提交说明包含 {text}")]
fn then_last_commit_subject_contains(text: String) {
    let dir = fixture_cwd();
    let out = Command::new("git")
        .args(["log", "-1", "--format=%s"])
        .current_dir(&dir)
        .output()
        .expect("git log -1");
    assert!(out.status.success(), "git log failed");
    let subject = String::from_utf8_lossy(&out.stdout);
    assert!(
        subject.contains(&text),
        "expected commit subject to contain {:?}, got {:?}",
        text,
        subject.trim()
    );
}

#[then("最近提交说明不含 {text}")]
fn then_last_commit_subject_not_contains(text: String) {
    let dir = fixture_cwd();
    let out = Command::new("git")
        .args(["log", "-1", "--format=%s"])
        .current_dir(&dir)
        .output()
        .expect("git log -1");
    assert!(out.status.success(), "git log failed");
    let subject = String::from_utf8_lossy(&out.stdout);
    assert!(
        !subject.contains(&text),
        "expected commit subject to NOT contain {:?}, got {:?}",
        text,
        subject.trim()
    );
}

#[then("工作区存在未提交改动")]
fn then_working_tree_dirty() {
    let dir = fixture_cwd();
    let out = Command::new("git")
        .args(["status", "--porcelain"])
        .current_dir(&dir)
        .output()
        .expect("git status");
    assert!(out.status.success(), "git status failed");
    let status = String::from_utf8_lossy(&out.stdout);
    assert!(
        !status.trim().is_empty(),
        "expected dirty working tree, got clean"
    );
}