orchestratectl 0.1.6

Rust CLI for orchestrating AI-agent workflows on a developer's machine.
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
//! Integration tests for the `spinoff` subcommand family — `list`,
//! `approve`, `reject`.

use std::path::Path;
use std::process::Command;

use serde_json::{json, Value};
use tempfile::TempDir;

fn bin(home: &TempDir) -> Command {
    let mut c = Command::new(env!("CARGO_BIN_EXE_orchestratectl"));
    c.env("ORCHESTRATECTL_HOME", home.path());
    c.env("OCTL_TEST_SKIP_MATERIALIZE", "1");
    // Scrub PATH so a real `issuectl` on the developer's system can't
    // leak into the "missing issuectl" tests. Individual tests that
    // need a fixture issuectl set PATH back explicitly.
    c.env("PATH", "/nonexistent-orchestratectl-test-path");
    c
}

fn run_ok(cmd: &mut Command) -> Value {
    let out = cmd.output().expect("spawn");
    assert!(
        out.status.success(),
        "exit={:?} stderr={}",
        out.status,
        String::from_utf8_lossy(&out.stderr)
    );
    let v: Value = serde_json::from_slice(&out.stdout).expect("stdout is valid JSON");
    // AGENTS-AI-FIRST-CLI §10 success envelope contract.
    assert_eq!(v["schema_version"], 1, "envelope shape: {v}");
    assert!(v.get("data").is_some(), "envelope shape: {v}");
    assert!(v.get("error").is_none(), "envelope shape: {v}");
    // `data` must not double-carry the envelope `warnings` field.
    assert!(
        v["data"].get("warnings").is_none(),
        "data.warnings should live only at envelope level: {v}"
    );
    v
}

fn run_fail(cmd: &mut Command) -> (i32, Value) {
    let out = cmd.output().expect("spawn");
    assert!(!out.status.success(), "expected failure");
    let code = out.status.code().expect("exit code");
    let stderr = String::from_utf8(out.stderr).expect("utf8");
    let last = stderr.lines().last().expect("stderr has at least one line");
    let v: Value = serde_json::from_str(last).expect("error envelope JSON");
    (code, v)
}

fn create_run(home: &TempDir) -> String {
    let v = run_ok(bin(home).args([
        "--output", "json", "run", "create", "--kind", "spinoff", "--title", "test-run",
    ]));
    v["data"]["run_id"].as_str().unwrap().to_string()
}

/// Bootstrap a node so the reducer has an anchor for `spinoff.proposed`,
/// then append the proposal via `event create`. Returns the proposal-id.
fn propose(home: &TempDir, run_id: &str, proposal_id: &str, title: &str) {
    // node.created
    let nc = home.path().join(format!("nc-{proposal_id}.json"));
    std::fs::write(
        &nc,
        serde_json::to_vec(&json!({"kind": "spinoff"})).unwrap(),
    )
    .unwrap();
    run_ok(bin(home).args([
        "--output",
        "json",
        "event",
        "create",
        run_id,
        "--kind",
        "node.created",
        "--node-id",
        "n-0001",
        "--from-file",
        nc.to_str().unwrap(),
    ]));
    // spinoff.proposed
    let sp = home.path().join(format!("sp-{proposal_id}.json"));
    std::fs::write(
        &sp,
        serde_json::to_vec(&json!({
            "proposal_id": proposal_id,
            "node_id": "n-0001",
            "proposed_title": title,
            "proposed_kind": "spinoff",
            "rationale": "follow-up",
        }))
        .unwrap(),
    )
    .unwrap();
    run_ok(bin(home).args([
        "--output",
        "json",
        "event",
        "create",
        run_id,
        "--kind",
        "spinoff.proposed",
        "--from-file",
        sp.to_str().unwrap(),
    ]));
}

/// Write a stub `issuectl` shell script that prints a fixed JSON
/// payload and returns success. Returns the directory holding the
/// script so the caller can prepend it to PATH.
fn write_stub_issuectl(slug: &str) -> TempDir {
    let dir = TempDir::new().unwrap();
    let script = dir.path().join("issuectl");
    // `echo` is a /bin/sh builtin so it works even with PATH scrubbed
    // (`cat` would not — see the PATH= override in `bin()`).
    let body = format!(
        "#!/bin/sh\necho '{{\"slug\":\"{slug}\",\"title\":\"x\",\"path\":\"x\",\"dir\":\"x\"}}'\n"
    );
    std::fs::write(&script, body).unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
    }
    dir
}

/// Write a faithful mini-`issuectl` that is idempotent on `--slug`, mirroring
/// real `issuectl new`: it records every invocation (one line per call in
/// `count_path`) and refuses to create a second ticket for a slug already in
/// `tickets_path`, exiting non-zero with an `already exists` message exactly as
/// the real binary does. The absolute paths are baked into the script body
/// because `spinoff approve` scrubs the child's environment — the stub cannot
/// read them from an env var. Returns the dir to prepend to `PATH`.
///
/// Uses only `/bin/sh` builtins (`echo`, `read`, `while`, `[`) — `approve`
/// scrubs the child's `PATH` to just the stub dir, so external tools like
/// `grep`/`printf` are not on PATH.
fn write_idempotent_issuectl(count_path: &Path, tickets_path: &Path) -> TempDir {
    let dir = TempDir::new().unwrap();
    let script = dir.path().join("issuectl");
    let count = count_path.display();
    let tickets = tickets_path.display();
    let body = format!(
        "#!/bin/sh\n\
         echo called >> \"{count}\"\n\
         slug=\"\"\n\
         while [ $# -gt 0 ]; do\n\
         \tif [ \"$1\" = \"--slug\" ]; then slug=\"$2\"; fi\n\
         \tshift\n\
         done\n\
         found=0\n\
         if [ -f \"{tickets}\" ]; then\n\
         \twhile IFS= read -r line; do\n\
         \t\tif [ \"$line\" = \"$slug\" ]; then found=1; fi\n\
         \tdone < \"{tickets}\"\n\
         fi\n\
         if [ \"$found\" = \"1\" ]; then\n\
         \techo '{{\"error\":{{\"code\":\"command-failed\",\"message\":\"slug already exists\"}}}}' 1>&2\n\
         \texit 1\n\
         fi\n\
         echo \"$slug\" >> \"{tickets}\"\n\
         echo \"{{\\\"slug\\\":\\\"$slug\\\"}}\"\n\
         exit 0\n",
    );
    std::fs::write(&script, body).unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
    }
    dir
}

/// Count non-empty lines in a file that may not exist yet (absent ⇒ 0).
fn nonempty_lines(path: &Path) -> usize {
    std::fs::read_to_string(path)
        .unwrap_or_default()
        .lines()
        .filter(|l| !l.is_empty())
        .count()
}

// ----------------------------- list -----------------------------

#[test]
fn list_empty_when_no_proposals() {
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    let v = run_ok(bin(&home).args(["--output", "json", "spinoff", "list", &run_id]));
    let proposals = v["data"]["proposals"].as_array().unwrap();
    assert!(proposals.is_empty());
}

#[test]
fn list_returns_proposals_with_status_filter() {
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    propose(&home, &run_id, "s-01aaaaaaaaaaaaaaaaaaaaaaaa", "A");
    propose(&home, &run_id, "s-01bbbbbbbbbbbbbbbbbbbbbbbb", "B");

    let v = run_ok(bin(&home).args(["--output", "json", "spinoff", "list", &run_id]));
    let proposals = v["data"]["proposals"].as_array().unwrap();
    assert_eq!(proposals.len(), 2);
    for p in proposals {
        assert_eq!(p["status"], "pending");
    }

    // Approve one, then filter.
    run_ok(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "approve",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
        "--issue-slug",
        "manual-slug",
    ]));
    let v = run_ok(bin(&home).args([
        "--output", "json", "spinoff", "list", &run_id, "--status", "approved",
    ]));
    let approved = v["data"]["proposals"].as_array().unwrap();
    assert_eq!(approved.len(), 1);
    assert_eq!(approved[0]["proposal_id"], "s-01aaaaaaaaaaaaaaaaaaaaaaaa");
    assert_eq!(approved[0]["accepted_as_issue_slug"], "manual-slug");
}

#[test]
fn list_unknown_run_id_is_run_not_found() {
    let home = TempDir::new().unwrap();
    let (code, err) = run_fail(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "list",
        "01jzabsent0000000000000000",
    ]));
    assert_eq!(code, 1);
    assert_eq!(err["error"]["code"], "run_not_found");
}

#[test]
fn list_rejects_invalid_status_filter() {
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    let (code, err) = run_fail(bin(&home).args([
        "--output", "json", "spinoff", "list", &run_id, "--status", "bogus",
    ]));
    assert_eq!(code, 1);
    assert_eq!(err["error"]["code"], "invalid_value");
}

// ----------------------------- approve -----------------------------

#[test]
fn approve_writes_event_and_updates_projection_with_manual_slug() {
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    propose(&home, &run_id, "s-01aaaaaaaaaaaaaaaaaaaaaaaa", "A");

    let v = run_ok(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "approve",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
        "--issue-slug",
        "my-slug",
    ]));
    assert_eq!(v["data"]["issue_slug"], "my-slug");
    assert!(v["data"]["seq"].as_u64().is_some());

    let proj: Value = serde_json::from_slice(
        &std::fs::read(
            home.path()
                .join("runs")
                .join(&run_id)
                .join("spinoffs")
                .join("s-01aaaaaaaaaaaaaaaaaaaaaaaa.json"),
        )
        .unwrap(),
    )
    .unwrap();
    assert_eq!(proj["status"], "approved");
    assert_eq!(proj["accepted_as_issue_slug"], "my-slug");

    let manifest: Value = serde_json::from_slice(
        &std::fs::read(home.path().join("runs").join(&run_id).join("manifest.json")).unwrap(),
    )
    .unwrap();
    assert_eq!(manifest["pending_spinoffs"].as_u64().unwrap(), 0);
}

#[test]
fn approve_is_idempotent_on_reapproval_with_same_slug() {
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    propose(&home, &run_id, "s-01aaaaaaaaaaaaaaaaaaaaaaaa", "A");
    run_ok(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "approve",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
        "--issue-slug",
        "slug-1",
    ]));
    let v = run_ok(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "approve",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
        "--issue-slug",
        "slug-1",
    ]));
    assert_eq!(v["data"]["idempotent_replay"], true);
    assert_eq!(v["data"]["issue_slug"], "slug-1");
}

#[test]
fn approve_is_idempotent_on_reapproval_without_slug() {
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    propose(&home, &run_id, "s-01aaaaaaaaaaaaaaaaaaaaaaaa", "A");
    run_ok(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "approve",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
        "--issue-slug",
        "slug-1",
    ]));
    // Re-approve without specifying --issue-slug returns the recorded slug.
    let v = run_ok(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "approve",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
    ]));
    assert_eq!(v["data"]["idempotent_replay"], true);
    assert_eq!(v["data"]["issue_slug"], "slug-1");
}

#[test]
fn approve_with_slug_after_approval_without_recorded_slug_errors() {
    // When `issuectl new` is unavailable, the first approve records
    // `accepted_as_issue_slug = null`. A later retry that supplies
    // `--issue-slug` cannot bind it retroactively (B5 contract) — it
    // errors with `proposal_already_approved` and the structured
    // `expected` field is JSON null, not a sentinel string.
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    propose(&home, &run_id, "s-01aaaaaaaaaaaaaaaaaaaaaaaa", "A");
    let first = run_ok(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "approve",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
    ]));
    assert!(first["data"]["issue_slug"].is_null());

    let (code, err) = run_fail(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "approve",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
        "--issue-slug",
        "slug-later",
    ]));
    assert_eq!(code, 1);
    assert_eq!(err["error"]["code"], "proposal_already_approved");
    assert_eq!(err["error"]["invalid_value"], "slug-later");
    assert!(
        err["error"]["expected"].is_null(),
        "expected should be JSON null when no slug was recorded, got {}",
        err["error"]["expected"]
    );
}

#[test]
fn approve_with_different_slug_is_proposal_already_approved() {
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    propose(&home, &run_id, "s-01aaaaaaaaaaaaaaaaaaaaaaaa", "A");
    run_ok(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "approve",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
        "--issue-slug",
        "slug-1",
    ]));
    let (code, err) = run_fail(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "approve",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
        "--issue-slug",
        "slug-2",
    ]));
    assert_eq!(code, 1);
    assert_eq!(err["error"]["code"], "proposal_already_approved");
    assert_eq!(err["error"]["expected"], "slug-1");
    assert_eq!(err["error"]["invalid_value"], "slug-2");
}

#[test]
fn approve_dry_run_does_not_touch_filesystem() {
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    propose(&home, &run_id, "s-01aaaaaaaaaaaaaaaaaaaaaaaa", "A");
    let events_path = home.path().join("runs").join(&run_id).join("events.jsonl");
    let before = std::fs::read(&events_path).unwrap();

    let v = run_ok(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "approve",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
        "--issue-slug",
        "x",
        "--dry-run",
    ]));
    assert_eq!(v["data"]["dry_run"], true);
    let after = std::fs::read(&events_path).unwrap();
    assert_eq!(before, after);
}

#[test]
fn approve_unknown_proposal_is_proposal_not_found() {
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    let (code, err) = run_fail(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "approve",
        &run_id,
        "s-99999999999999999999999999",
    ]));
    assert_eq!(code, 1);
    assert_eq!(err["error"]["code"], "proposal_not_found");
}

#[test]
fn approve_after_reject_is_proposal_already_rejected() {
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    propose(&home, &run_id, "s-01aaaaaaaaaaaaaaaaaaaaaaaa", "A");
    run_ok(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "reject",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
    ]));
    let (code, err) = run_fail(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "approve",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
    ]));
    assert_eq!(code, 1);
    assert_eq!(err["error"]["code"], "proposal_already_rejected");
}

#[test]
fn approve_without_issue_slug_calls_stub_issuectl() {
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    propose(&home, &run_id, "s-01aaaaaaaaaaaaaaaaaaaaaaaa", "A title");

    let stub = write_stub_issuectl("auto-materialized-slug");

    let mut cmd = Command::new(env!("CARGO_BIN_EXE_orchestratectl"));
    cmd.env("ORCHESTRATECTL_HOME", home.path());
    cmd.env("OCTL_TEST_SKIP_MATERIALIZE", "1");
    cmd.env("PATH", stub.path());
    cmd.args([
        "--output",
        "json",
        "spinoff",
        "approve",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
    ]);
    let v = run_ok(&mut cmd);
    assert_eq!(v["data"]["issue_slug"], "auto-materialized-slug");

    let proj: Value = serde_json::from_slice(
        &std::fs::read(
            home.path()
                .join("runs")
                .join(&run_id)
                .join("spinoffs")
                .join("s-01aaaaaaaaaaaaaaaaaaaaaaaa.json"),
        )
        .unwrap(),
    )
    .unwrap();
    assert_eq!(proj["accepted_as_issue_slug"], "auto-materialized-slug");
}

#[test]
fn approve_without_issue_slug_missing_issuectl_succeeds_with_warning() {
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    propose(&home, &run_id, "s-01aaaaaaaaaaaaaaaaaaaaaaaa", "A");

    // bin() already scrubs PATH so issuectl is not found.
    let v = run_ok(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "approve",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
    ]));
    // Still recorded; no slug; no per-call warning because the
    // "missing on PATH" case is intentionally silent (issuectl is
    // optional).
    assert!(v["data"]["seq"].as_u64().is_some());
    assert!(v["data"]["issue_slug"].is_null());
    let proj: Value = serde_json::from_slice(
        &std::fs::read(
            home.path()
                .join("runs")
                .join(&run_id)
                .join("spinoffs")
                .join("s-01aaaaaaaaaaaaaaaaaaaaaaaa.json"),
        )
        .unwrap(),
    )
    .unwrap();
    assert_eq!(proj["status"], "approved");
}

#[test]
fn approve_issuectl_failure_emits_warning_and_still_records() {
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    propose(&home, &run_id, "s-01aaaaaaaaaaaaaaaaaaaaaaaa", "A");

    // Stub issuectl that exits non-zero.
    let dir = TempDir::new().unwrap();
    let script = dir.path().join("issuectl");
    std::fs::write(&script, "#!/bin/sh\necho boom 1>&2\nexit 17\n").unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
    }

    let mut cmd = Command::new(env!("CARGO_BIN_EXE_orchestratectl"));
    cmd.env("ORCHESTRATECTL_HOME", home.path());
    cmd.env("PATH", dir.path());
    cmd.args([
        "--output",
        "json",
        "spinoff",
        "approve",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
    ]);
    let v = run_ok(&mut cmd);
    let warnings = v["warnings"].as_array().expect("warnings present");
    assert!(
        warnings
            .iter()
            .any(|w| w.as_str().unwrap_or("").contains("issuectl")),
        "expected issuectl warning, got: {warnings:?}"
    );
    assert!(v["data"]["seq"].as_u64().is_some());
    assert!(v["data"]["issue_slug"].is_null());
}

// ----------------------------- reject -----------------------------

#[test]
fn reject_writes_event_and_updates_projection() {
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    propose(&home, &run_id, "s-01aaaaaaaaaaaaaaaaaaaaaaaa", "A");
    let v = run_ok(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "reject",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
        "--reason",
        "out of scope",
    ]));
    assert!(v["data"]["seq"].as_u64().is_some());

    let proj: Value = serde_json::from_slice(
        &std::fs::read(
            home.path()
                .join("runs")
                .join(&run_id)
                .join("spinoffs")
                .join("s-01aaaaaaaaaaaaaaaaaaaaaaaa.json"),
        )
        .unwrap(),
    )
    .unwrap();
    assert_eq!(proj["status"], "rejected");
    assert_eq!(proj["rejected_reason"], "out of scope");
}

#[test]
fn reject_idempotent_on_matching_reason() {
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    propose(&home, &run_id, "s-01aaaaaaaaaaaaaaaaaaaaaaaa", "A");
    run_ok(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "reject",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
        "--reason",
        "same",
    ]));
    let v = run_ok(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "reject",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
        "--reason",
        "same",
    ]));
    assert_eq!(v["data"]["idempotent_replay"], true);
}

#[test]
fn reject_with_different_reason_is_proposal_already_rejected() {
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    propose(&home, &run_id, "s-01aaaaaaaaaaaaaaaaaaaaaaaa", "A");
    run_ok(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "reject",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
        "--reason",
        "first",
    ]));
    let (code, err) = run_fail(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "reject",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
        "--reason",
        "different",
    ]));
    assert_eq!(code, 1);
    assert_eq!(err["error"]["code"], "proposal_already_rejected");
}

#[test]
fn reject_dry_run_does_not_touch_filesystem() {
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    propose(&home, &run_id, "s-01aaaaaaaaaaaaaaaaaaaaaaaa", "A");
    let events_path = home.path().join("runs").join(&run_id).join("events.jsonl");
    let before = std::fs::read(&events_path).unwrap();

    let v = run_ok(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "reject",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
        "--reason",
        "x",
        "--dry-run",
    ]));
    assert_eq!(v["data"]["dry_run"], true);
    let after = std::fs::read(&events_path).unwrap();
    assert_eq!(before, after);
}

#[test]
fn reject_after_approve_is_proposal_already_approved() {
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    propose(&home, &run_id, "s-01aaaaaaaaaaaaaaaaaaaaaaaa", "A");
    run_ok(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "approve",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
        "--issue-slug",
        "s",
    ]));
    let (code, err) = run_fail(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "reject",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
    ]));
    assert_eq!(code, 1);
    assert_eq!(err["error"]["code"], "proposal_already_approved");
}

// ----------------------------- input validation -----------------------------

#[test]
fn approve_rejects_empty_issue_slug() {
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    propose(&home, &run_id, "s-01aaaaaaaaaaaaaaaaaaaaaaaa", "A");
    let (code, err) = run_fail(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "approve",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
        "--issue-slug",
        "",
    ]));
    assert_eq!(code, 1);
    assert_eq!(err["error"]["code"], "invalid_value");
}

#[test]
fn approve_rejects_issue_slug_with_uppercase_or_spaces() {
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    propose(&home, &run_id, "s-01aaaaaaaaaaaaaaaaaaaaaaaa", "A");
    let (code, err) = run_fail(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "approve",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
        "--issue-slug",
        "My Slug",
    ]));
    assert_eq!(code, 1);
    assert_eq!(err["error"]["code"], "invalid_value");
}

#[test]
fn reject_rejects_empty_reason() {
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    propose(&home, &run_id, "s-01aaaaaaaaaaaaaaaaaaaaaaaa", "A");
    let (code, err) = run_fail(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "reject",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
        "--reason",
        "   ",
    ]));
    assert_eq!(code, 1);
    assert_eq!(err["error"]["code"], "invalid_value");
}

#[test]
fn reject_rejects_reason_with_control_chars() {
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    propose(&home, &run_id, "s-01aaaaaaaaaaaaaaaaaaaaaaaa", "A");
    let (code, err) = run_fail(bin(&home).args([
        "--output",
        "json",
        "spinoff",
        "reject",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
        "--reason",
        "out\x07of scope",
    ]));
    assert_eq!(code, 1);
    assert_eq!(err["error"]["code"], "invalid_value");
}

// ----------------------------- list ordering -----------------------------

#[test]
fn list_orders_by_proposed_at_desc_with_proposal_id_tiebreaker() {
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    propose(&home, &run_id, "s-01aaaaaaaaaaaaaaaaaaaaaaaa", "A");
    propose(&home, &run_id, "s-01bbbbbbbbbbbbbbbbbbbbbbbb", "B");
    propose(&home, &run_id, "s-01cccccccccccccccccccccccc", "C");

    let v1 = run_ok(bin(&home).args(["--output", "json", "spinoff", "list", &run_id]));
    let v2 = run_ok(bin(&home).args(["--output", "json", "spinoff", "list", &run_id]));
    // Two reads of the same state must produce byte-identical proposal order.
    assert_eq!(v1["data"]["proposals"], v2["data"]["proposals"]);
}

// --------------------------- concurrency -----------------------------------

#[cfg(unix)]
#[test]
fn concurrent_approve_appends_exactly_one_event() {
    use std::thread;
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    propose(&home, &run_id, "s-01aaaaaaaaaaaaaaaaaaaaaaaa", "race");

    // Two parallel `approve --issue-slug ...` against the same proposal.
    // The flock + decision-enum recheck must collapse the race so only
    // one `spinoff.approved` event lands and the loser sees
    // idempotent_replay.
    let home_path = home.path().to_path_buf();
    let r1 = run_id.clone();
    let r2 = run_id.clone();
    let t1 = thread::spawn(move || {
        Command::new(env!("CARGO_BIN_EXE_orchestratectl"))
            .env("ORCHESTRATECTL_HOME", &home_path)
            .env("PATH", "/nonexistent-orchestratectl-test-path")
            .args([
                "--output",
                "json",
                "spinoff",
                "approve",
                &r1,
                "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
                "--issue-slug",
                "slug-from-t1",
            ])
            .output()
            .expect("spawn")
    });
    let home_path2 = home.path().to_path_buf();
    let t2 = thread::spawn(move || {
        Command::new(env!("CARGO_BIN_EXE_orchestratectl"))
            .env("ORCHESTRATECTL_HOME", &home_path2)
            .env("PATH", "/nonexistent-orchestratectl-test-path")
            .args([
                "--output",
                "json",
                "spinoff",
                "approve",
                &r2,
                "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
                "--issue-slug",
                "slug-from-t2",
            ])
            .output()
            .expect("spawn")
    });
    let o1 = t1.join().unwrap();
    let o2 = t2.join().unwrap();

    // Exactly one spinoff.approved event in the log.
    let events =
        std::fs::read_to_string(home.path().join("runs").join(&run_id).join("events.jsonl"))
            .unwrap();
    let count = events
        .lines()
        .filter(|l| l.contains("\"kind\":\"spinoff.approved\""))
        .count();
    assert_eq!(
        count, 1,
        "expected exactly one spinoff.approved event; log:\n{events}"
    );

    // Projection holds whichever slug won.
    let proj: Value = serde_json::from_slice(
        &std::fs::read(
            home.path()
                .join("runs")
                .join(&run_id)
                .join("spinoffs")
                .join("s-01aaaaaaaaaaaaaaaaaaaaaaaa.json"),
        )
        .unwrap(),
    )
    .unwrap();
    assert_eq!(proj["status"], "approved");
    let persisted_slug = proj["accepted_as_issue_slug"].as_str().unwrap();
    assert!(
        persisted_slug == "slug-from-t1" || persisted_slug == "slug-from-t2",
        "persisted slug must be one of the two callers: {persisted_slug}"
    );

    // The caller whose slug won succeeds; the loser surfaces
    // `proposal_already_approved` (per B5: a different `--issue-slug`
    // after approval must not be silently swallowed).
    let (winner, loser, loser_slug) = if persisted_slug == "slug-from-t1" {
        (&o1, &o2, "slug-from-t2")
    } else {
        (&o2, &o1, "slug-from-t1")
    };
    assert!(
        winner.status.success(),
        "winner stderr: {}",
        String::from_utf8_lossy(&winner.stderr)
    );
    assert!(
        !loser.status.success(),
        "loser stdout: {}",
        String::from_utf8_lossy(&loser.stdout)
    );
    let winner_v: Value = serde_json::from_slice(&winner.stdout).unwrap();
    assert_eq!(winner_v["data"]["issue_slug"], persisted_slug);
    let loser_err: Value = serde_json::from_slice(&loser.stderr).unwrap();
    assert_eq!(loser_err["error"]["code"], "proposal_already_approved");
    assert_eq!(loser_err["error"]["expected"], persisted_slug);
    assert_eq!(loser_err["error"]["invalid_value"], loser_slug);
}

#[cfg(unix)]
#[test]
fn concurrent_approve_vs_reject_does_not_lie_about_outcome() {
    use std::thread;
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    propose(&home, &run_id, "s-01aaaaaaaaaaaaaaaaaaaaaaaa", "race2");

    let home_path = home.path().to_path_buf();
    let r1 = run_id.clone();
    let r2 = run_id.clone();
    let t_app = thread::spawn(move || {
        Command::new(env!("CARGO_BIN_EXE_orchestratectl"))
            .env("ORCHESTRATECTL_HOME", &home_path)
            .env("PATH", "/nonexistent-orchestratectl-test-path")
            .args([
                "--output",
                "json",
                "spinoff",
                "approve",
                &r1,
                "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
                "--issue-slug",
                "winner-app",
            ])
            .output()
            .expect("spawn")
    });
    let home_path2 = home.path().to_path_buf();
    let t_rej = thread::spawn(move || {
        Command::new(env!("CARGO_BIN_EXE_orchestratectl"))
            .env("ORCHESTRATECTL_HOME", &home_path2)
            .env("PATH", "/nonexistent-orchestratectl-test-path")
            .args([
                "--output",
                "json",
                "spinoff",
                "reject",
                &r2,
                "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
                "--reason",
                "winner-rej",
            ])
            .output()
            .expect("spawn")
    });
    let o_app = t_app.join().unwrap();
    let o_rej = t_rej.join().unwrap();
    // Whoever lost must report a deterministic error (not false success).
    let app_ok = o_app.status.success();
    let rej_ok = o_rej.status.success();
    assert!(
        app_ok ^ rej_ok,
        "exactly one must succeed; app_ok={app_ok}, rej_ok={rej_ok}"
    );

    let loser_stderr = if app_ok { &o_rej.stderr } else { &o_app.stderr };
    let stderr_s = String::from_utf8_lossy(loser_stderr);
    let last = stderr_s
        .lines()
        .last()
        .expect("loser must emit error envelope");
    let v: Value = serde_json::from_str(last).expect("loser error JSON");
    let code = v["error"]["code"].as_str().unwrap();
    assert!(
        code == "proposal_already_approved" || code == "proposal_already_rejected",
        "loser must report a status-conflict error, got: {code}"
    );
}

// --------------------- lock-first materialization --------------------------

/// Two concurrent auto-materializing approves (same proposal, same
/// `--idempotency-key`) must call `issuectl new` exactly once and append
/// exactly one `spinoff.approved` (materialization) event. This is the
/// lock-first invariant: the flock is held across the `issuectl` subprocess, so
/// the loser observes the `Approved` status and never shells out — no orphan
/// ticket.
#[cfg(unix)]
#[test]
fn concurrent_approve_same_key_materializes_exactly_once() {
    use std::thread;
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    propose(&home, &run_id, "s-01aaaaaaaaaaaaaaaaaaaaaaaa", "race-mat");

    let scratch = TempDir::new().unwrap();
    let count = scratch.path().join("count");
    let tickets = scratch.path().join("tickets");
    let stub = write_idempotent_issuectl(&count, &tickets);
    let stub_dir = stub.path().to_path_buf();

    let spawn = |home_path: std::path::PathBuf, run_id: String, stub: std::path::PathBuf| {
        thread::spawn(move || {
            Command::new(env!("CARGO_BIN_EXE_orchestratectl"))
                .env("ORCHESTRATECTL_HOME", &home_path)
                .env("PATH", &stub)
                .args([
                    "--output",
                    "json",
                    "spinoff",
                    "approve",
                    &run_id,
                    "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
                    "--idempotency-key",
                    "same-key",
                ])
                .output()
                .expect("spawn")
        })
    };
    let t1 = spawn(home.path().to_path_buf(), run_id.clone(), stub_dir.clone());
    let t2 = spawn(home.path().to_path_buf(), run_id.clone(), stub_dir.clone());
    let o1 = t1.join().unwrap();
    let o2 = t2.join().unwrap();

    // Both succeed: one applies, the other idempotently replays (no
    // `--issue-slug`, so the loser does not trip the mismatch guard).
    assert!(
        o1.status.success() && o2.status.success(),
        "both approvals should succeed; o1 stderr={}, o2 stderr={}",
        String::from_utf8_lossy(&o1.stderr),
        String::from_utf8_lossy(&o2.stderr),
    );

    assert_eq!(
        nonempty_lines(&count),
        1,
        "issuectl must be invoked exactly once; invocations:\n{}",
        std::fs::read_to_string(&count).unwrap_or_default()
    );
    assert_eq!(
        nonempty_lines(&tickets),
        1,
        "exactly one ticket must be created; tickets:\n{}",
        std::fs::read_to_string(&tickets).unwrap_or_default()
    );

    let events =
        std::fs::read_to_string(home.path().join("runs").join(&run_id).join("events.jsonl"))
            .unwrap();
    let approved = events
        .lines()
        .filter(|l| l.contains("\"kind\":\"spinoff.approved\""))
        .count();
    assert_eq!(
        approved, 1,
        "exactly one spinoff.approved event; log:\n{events}"
    );
}

/// Retry-safety: a prior approve created the external ticket (deterministic
/// slug) but crashed before appending `spinoff.approved`. Re-running approve
/// must NOT create a second ticket — `issuectl new --slug <det>` collides on
/// the known slug, and approve recovers by re-attaching it.
#[cfg(unix)]
#[test]
fn retry_after_crash_reattaches_ticket_without_duplicating() {
    let home = TempDir::new().unwrap();
    let run_id = create_run(&home);
    propose(&home, &run_id, "s-01aaaaaaaaaaaaaaaaaaaaaaaa", "retry-mat");

    let scratch = TempDir::new().unwrap();
    let count = scratch.path().join("count");
    let tickets = scratch.path().join("tickets");
    // Simulate the crashed prior attempt: the ticket already exists under the
    // deterministic slug, but no `spinoff.approved` event was appended (the
    // proposal is still pending).
    let det_slug = "spinoff-01aaaaaaaaaaaaaaaaaaaaaaaa";
    std::fs::write(&tickets, format!("{det_slug}\n")).unwrap();
    let stub = write_idempotent_issuectl(&count, &tickets);

    let mut cmd = Command::new(env!("CARGO_BIN_EXE_orchestratectl"));
    cmd.env("ORCHESTRATECTL_HOME", home.path());
    cmd.env("PATH", stub.path());
    cmd.args([
        "--output",
        "json",
        "spinoff",
        "approve",
        &run_id,
        "s-01aaaaaaaaaaaaaaaaaaaaaaaa",
    ]);
    let v = run_ok(&mut cmd);

    // Recovered: the deterministic slug is re-attached, no error, no warning.
    assert_eq!(v["data"]["issue_slug"], det_slug);
    assert!(v["data"]["seq"].as_u64().is_some());

    // The second `issuectl new` was refused — still exactly one ticket.
    assert_eq!(
        nonempty_lines(&tickets),
        1,
        "retry must not create a second ticket; tickets:\n{}",
        std::fs::read_to_string(&tickets).unwrap_or_default()
    );

    let proj: Value = serde_json::from_slice(
        &std::fs::read(
            home.path()
                .join("runs")
                .join(&run_id)
                .join("spinoffs")
                .join("s-01aaaaaaaaaaaaaaaaaaaaaaaa.json"),
        )
        .unwrap(),
    )
    .unwrap();
    assert_eq!(proj["status"], "approved");
    assert_eq!(proj["accepted_as_issue_slug"], det_slug);
}